diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..d5e3222f6b --- /dev/null +++ b/build.gradle @@ -0,0 +1,56 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.10.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.10.0' + + String javaFxVersion = '17.0.7' + + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'linux' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClass.set("johnchatter.Launcher") +} + +shadowJar { + archiveBaseName = "johnchatter" + archiveClassifier = null +} + +run{ + standardInput = System.in +} diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..b2ae3f5b9d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,137 @@ -# Duke User Guide +# john chatter - User Guide -// Update the title above to match the actual product name +welcome to john chatter, a chatbot that helps you manage your various tasks -// Product screenshot goes here +## Adding basic todos -// Product intro goes here +Adds a todo to your list. -## Adding deadlines +Format: `todo NAME` -// Describe the action and its outcome. +Examples: -// Give examples of usage +`todo cs2103t project` -Example: `keyword (optional arguments)` +`todo cook dinner` -// A description of the expected outcome goes here +## Adding tasks with a deadline -``` -expected output -``` +Adds a task with a deadline to your list. -## Feature ABC +Format: `deadline NAME /by WHEN` -// Feature details +Examples: +`deadline ma1522 homework /by monday` -## Feature XYZ +`deadline return books /by 22-9-2025` + + +## Adding events with a start and end time + +Adds a task with a deadline to your list. + +Format: `event NAME /from START /to END` + +Examples: + +`event exams /from 6-10-2025 /to 11-10-2025` + +`event recess week /from 22-9-2025 /to 28-9-2025` + +## View your list of tasks + +Displays a list of your tasks with their relevant info. + +Format: `list` + +## Delete + +Removes a task from your list by its index. + +Format: `delete INDEX` + +Examples: + +`delete 1` + +`delete 2` + +## Mark complete + +Marks a task as complete using the index of the task on the list. + +Format: `mark INDEX` + +Examples: + +`mark 1` + +`mark 2` + +## Mark incomplete + +Marks a task as incomplete using the index of the task on the list. + +Format: `unmark INDEX` + +Examples: + +`unmark 1` + +`unmark 2` + +## Tag + +Adds a tag to categorise a task. Each task can have multiple tags. + +Format: `tag INDEX TAG_NAME` + +Examples: + +`tag 1 school` + +`tag 1 important` + +`tag 2 fun` + +## Untag + +Removes an existing tag from a task. + +Format: `untag INDEX TAG_NAME` + +Examples: + +`untag 1 school` + +`untag 2 fun` + +## Find by name + +Display a filtered version of your list with tasks with names that match the keywords. + +If more than one keyword is given, tasks must match ALL keywords. + +Format: `find KEYWORD OPTIONAL_KEYWORD OPTIONAL_KEYWORD ...` + +Examples: + +`find homework` + +`find math homework` + +## Find by tag + +Display a filtered version of your list with tasks that have the specified tag(s). + +If more than one tag is given, tasks must match ALL tags. + +Format: `findtag TAG OPTIONAL_TAG OPTIONAL_TAG ...` + +Examples: + +`findtag school` + +`findtag school impt` -// Feature details \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..647e003657 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/johnchatter/Deadline.java b/src/main/java/johnchatter/Deadline.java new file mode 100644 index 0000000000..64ca4e9fe1 --- /dev/null +++ b/src/main/java/johnchatter/Deadline.java @@ -0,0 +1,18 @@ +package johnchatter; + +/** + * A task that has a deadline by which it is to be completed. + */ +public class Deadline extends Task { + protected String by; + + public Deadline(String description, String by) { + super(description); + this.by = by; + } + + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + by + ")"; + } +} diff --git a/src/main/java/johnchatter/DialogBox.java b/src/main/java/johnchatter/DialogBox.java new file mode 100644 index 0000000000..99a8cbe229 --- /dev/null +++ b/src/main/java/johnchatter/DialogBox.java @@ -0,0 +1,60 @@ +package johnchatter; + +import java.io.IOException; +import java.util.Collections; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.geometry.Pos; +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; + +/** + * Represents a dialog box consisting of an ImageView to represent the speaker's face + * and a label containing text from the speaker. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + private DialogBox(String text, Image img) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + + dialog.setText(text); + displayPicture.setImage(img); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/johnchatter/Event.java b/src/main/java/johnchatter/Event.java new file mode 100644 index 0000000000..7637b27691 --- /dev/null +++ b/src/main/java/johnchatter/Event.java @@ -0,0 +1,20 @@ +package johnchatter; + +/** + * A task that represents an event with specific starting and ending times. + */ +public class Event extends Task { + protected String start; + protected String end; + + public Event(String description, String start, String end) { + super(description); + this.start = start; + this.end = end; + } + + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + start + " to: " + end + ")"; + } +} diff --git a/src/main/java/johnchatter/JohnChatter.java b/src/main/java/johnchatter/JohnChatter.java new file mode 100644 index 0000000000..f4a470de49 --- /dev/null +++ b/src/main/java/johnchatter/JohnChatter.java @@ -0,0 +1,71 @@ +package johnchatter; + +import java.io.IOException; +import java.util.Scanner; + +public class JohnChatter { + private final Storage storage; + private final TaskList tasks; + private final Ui ui; + + /** + * Constructs the JohnChatter object and initialises storage, tasks, and ui. + * + * @param filepath The filepath of the text file that stores task data + */ + public JohnChatter(String filepath) throws IOException { + assert filepath != null : "Filepath should not be null"; + + this.storage = new Storage(filepath); + assert this.storage != null : "Storage should not be null"; + + this.tasks = new TaskList(this.storage.load()); + assert this.tasks != null : "Task list should not be null"; + + this.ui = new Ui(); + assert this.ui != null : "Ui should not be null"; + } + + /** + * Gets John Chatter's response to a given user input. + * + * @return The response that will be displayed in the DialogBox + */ + public String getResponse(String input) { + assert input != null : "Input should not be null"; + try { + String response = Parser.parse(input, ui, storage, tasks); + assert response != null : "response should not be null"; + return response; + } catch (JohnChatterException | IOException e) { + return e.getMessage(); + } + } + + /** + * Handles the app's main functionality loop of scanning user input then responding appropriately. + * Terminates when the "bye" command is given. + */ + public void run() { + ui.showWelcome(); + String input; + Scanner scanner = new Scanner(System.in); + while (true) { + input = scanner.nextLine(); + try { + ui.showDividerLine(); + if (Parser.parse(input, ui, storage, tasks).equals("bye")) { + break; + } + } catch (JohnChatterException | IOException e) { + ui.showError(e.getMessage()); + } finally { + ui.showDividerLine(); + } + } + } + + public static void main(String[] args) throws IOException { + new JohnChatter("data/task_data.txt").run(); + } +} diff --git a/src/main/java/johnchatter/JohnChatterException.java b/src/main/java/johnchatter/JohnChatterException.java new file mode 100644 index 0000000000..519cc156a0 --- /dev/null +++ b/src/main/java/johnchatter/JohnChatterException.java @@ -0,0 +1,10 @@ +package johnchatter; + +/** + * An exception that is thrown by the JohnChatter program. + */ +public class JohnChatterException extends Exception { + public JohnChatterException(String message) { + super(message); + } +} diff --git a/src/main/java/johnchatter/Launcher.java b/src/main/java/johnchatter/Launcher.java new file mode 100644 index 0000000000..f2a3e5a6aa --- /dev/null +++ b/src/main/java/johnchatter/Launcher.java @@ -0,0 +1,13 @@ +package johnchatter; + +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/johnchatter/Main.java b/src/main/java/johnchatter/Main.java new file mode 100644 index 0000000000..5b13f876b4 --- /dev/null +++ b/src/main/java/johnchatter/Main.java @@ -0,0 +1,34 @@ +package johnchatter; + +import java.io.IOException; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.layout.AnchorPane; +import javafx.stage.Stage; + +/** + * A GUI for Duke using FXML. + */ +public class Main extends Application { + + private JohnChatter john = new JohnChatter("data/task_data.txt"); + + public Main() throws IOException { + } + + @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().setJohn(john); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/johnchatter/MainWindow.java b/src/main/java/johnchatter/MainWindow.java new file mode 100644 index 0000000000..277d512276 --- /dev/null +++ b/src/main/java/johnchatter/MainWindow.java @@ -0,0 +1,52 @@ +package johnchatter; + +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 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 JohnChatter john; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/john_user.png")); + private Image johnImage = new Image(this.getClass().getResourceAsStream("/images/john_answer.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + public void setJohn(JohnChatter j) { + john = j; + } + + /** + * 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 = john.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, johnImage) + ); + userInput.clear(); + } +} diff --git a/src/main/java/johnchatter/Parser.java b/src/main/java/johnchatter/Parser.java new file mode 100644 index 0000000000..f3273a1280 --- /dev/null +++ b/src/main/java/johnchatter/Parser.java @@ -0,0 +1,265 @@ +package johnchatter; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.stream.Collectors; + +/** + * Handles the parsing of commands from user input. + */ +public class Parser { + private static final String ERROR_TODO_NO_DESCRIPTION = + "oops! todo must have a description"; + private static final String ERROR_DEADLINE_NO_BY = + "oops! deadline must have a /by date"; + private static final String ERROR_EVENT_NO_FROM_TO = + "oops! event must have /from and /to dates"; + private static final String ERROR_INVALID_TASK_NUMBER = + "it seems you have input an invalid task number, please check and try again"; + private static final String ERROR_UNKNOWN_COMMAND = + "sorry, i don't know what that means"; + + // ChatGPT was used to abstract out the helper functions from the parse method + + /** + * Parses the user input and performs the appropriate action for the command given. + * + * @return John Chatter's text response that will be displayed to the user + * @throws JohnChatterException If the user issues an invalid command + */ + public static String parse(String input, Ui ui, Storage storage, TaskList tasks) throws JohnChatterException, IOException { + assert input != null : "Input should not be null"; + assert ui != null : "Ui should not be null"; + assert storage != null : "Storage should not be null"; + assert tasks != null : "Task list should not be null"; + + ArrayList list = tasks.list; + String[] tokens = input.split(" "); + String command = tokens[0]; + + switch (command) { + case "bye": + return handleBye(ui); + case "list": + return handleList(list); + case "find": + return handleFind(tokens, list, storage); + case "findtag": + return handleFindTag(tokens, list, storage); + case "mark": + return handleMark(tokens, list, tasks, storage, ui); + case "unmark": + return handleUnmark(tokens, list, tasks, storage, ui); + case "todo": + return handleTodo(input, storage, tasks, ui); + case "deadline": + return handleDeadline(input, storage, tasks, ui); + case "event": + return handleEvent(input, storage, tasks, ui); + case "delete": + return handleDelete(tokens, list, tasks, storage, ui); + case "tag": + return handleTag(tokens, list, storage, ui); + case "untag": + return handleUntag(tokens, list, storage, ui); + default: + throw new JohnChatterException(ERROR_UNKNOWN_COMMAND); + } + } + + private static String handleBye(Ui ui) { + ui.showGoodbye(); + return "bye"; + } + + private static String handleList(ArrayList list) { + return formatTaskList(list); + } + + // ChatGPT was used to improve the handleFind and handleFindTag methods + private static String handleFind(String[] tokens, ArrayList list, Storage storage) throws JohnChatterException, IOException { + if (tokens.length < 2) { + throw new JohnChatterException("usage: find ..."); + } + + // all search keywords, lowercase for case-insensitive matching + String[] keywords = new String[tokens.length - 1]; + System.arraycopy(tokens, 1, keywords, 0, tokens.length - 1); + + ArrayList filteredList = new ArrayList<>(list.stream() + .filter(task -> { + String desc = task.description.toLowerCase(); + // must match ALL keywords + for (String keyword : keywords) { + if (!desc.contains(keyword.toLowerCase())) { + return false; + } + } + return true; + }) + .toList()); + + storage.writeTaskData(list); + return formatTaskList(filteredList); + } + + private static String handleFindTag(String[] tokens, ArrayList list, Storage storage) throws JohnChatterException, IOException { + if (tokens.length < 2) { + throw new JohnChatterException("usage: findtag ..."); + } + + String[] tags = new String[tokens.length - 1]; + System.arraycopy(tokens, 1, tags, 0, tokens.length - 1); + + ArrayList filteredList = new ArrayList<>(list.stream() + .filter(task -> { + String desc = task.description.toLowerCase(); + // must match all tags + for (String tag : tags) { + if (!task.getTags().contains(tag.toLowerCase())) { + return false; + } + } + return true; + }) + .toList()); + + storage.writeTaskData(list); + return formatTaskList(filteredList); + } + + private static String formatTaskList(ArrayList list) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + Task item = list.get(i); + if (item == null) { + continue; + } + result.append(i + 1).append(".").append(item).append("\n"); + } + return result.toString(); + } + + private static String handleMark(String[] tokens, ArrayList list, TaskList tasks, Storage storage, Ui ui) throws JohnChatterException, IOException { + int index = parseIndex(tokens, list); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return tasks.mark(list.get(index), storage); + } + + private static String handleUnmark(String[] tokens, ArrayList list, TaskList tasks, Storage storage, Ui ui) throws JohnChatterException, IOException { + int index = parseIndex(tokens, list); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return tasks.unmark(list.get(index), storage); + } + + private static String handleTodo(String input, Storage storage, TaskList tasks, Ui ui) throws JohnChatterException { + if (!input.contains("todo ")) { + throw new JohnChatterException(ERROR_TODO_NO_DESCRIPTION); + } + Todo todo = new Todo(input.split("todo ")[1]); + + return tasks.addTodo(todo, storage, ui); + } + + private static String handleDeadline(String input, Storage storage, TaskList tasks, Ui ui) throws JohnChatterException { + if (!input.contains("/by ")) { + throw new JohnChatterException(ERROR_DEADLINE_NO_BY); + } + String description = input.split("deadline ")[1].split(" /by")[0]; + String deadlineDateInput = input.split("/by ")[1]; + String formattedDate = formatDate(deadlineDateInput); + + Deadline deadline = new Deadline(description, formattedDate); + return tasks.addDeadline(deadline, storage, ui); + } + + private static String handleEvent(String input, Storage storage, TaskList tasks, Ui ui) throws JohnChatterException { + if (!input.contains("/from ") || !input.contains("/to ")) { + throw new JohnChatterException(ERROR_EVENT_NO_FROM_TO); + } + String description = input.split(" /from")[0].split("event ")[1]; + String startInput = input.split(" /to")[0].split("/from ")[1]; + String endInput = input.split("/to ")[1]; + + String formattedStart = formatDate(startInput); + String formattedEnd = formatDate(endInput); + + Event event = new Event(description, formattedStart, formattedEnd); + return tasks.addEvent(event, storage, ui); + } + + private static String handleDelete(String[] tokens, ArrayList list, TaskList tasks, Storage storage, Ui ui) throws JohnChatterException { + int index = parseIndex(tokens, list); + Task task = list.get(index); + return tasks.deleteTask(task, storage, ui); + } + + private static int parseIndex(String[] tokens, ArrayList list) throws JohnChatterException { + if (tokens.length != 2 || !tokens[1].matches("\\d+")) { + throw new JohnChatterException(ERROR_INVALID_TASK_NUMBER); + } + int index = Integer.parseInt(tokens[1]) - 1; + if (index < 0 || index >= list.size()) { + throw new JohnChatterException(ERROR_INVALID_TASK_NUMBER); + } + return index; + } + + private static String formatDate(String input) { + try { + LocalDate date = LocalDate.parse(input); + return date.format(DateTimeFormatter.ofPattern("MMM d yyyy")); + } catch (DateTimeParseException e) { + return input; + } + } + + // ChatGPT was used to write this method + private static String handleTag(String[] tokens, ArrayList list, Storage storage, Ui ui) throws JohnChatterException { + if (tokens.length != 3) { + throw new JohnChatterException("usage: tag <#tag>"); + } + int index = parseIndex(new String[]{tokens[0], tokens[1]}, list); + String tag = tokens[2]; + Task task = list.get(index); + task.addTag(tag); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "added tag " + tag + " to task: " + task; + } + + // ChatGPT was used to write this method + private static String handleUntag(String[] tokens, ArrayList list, Storage storage, Ui ui) throws JohnChatterException { + if (tokens.length != 3) { + throw new JohnChatterException("usage: untag <#tag>"); + } + int index = parseIndex(new String[]{tokens[0], tokens[1]}, list); + String tag = tokens[2]; + Task task = list.get(index); + if (task.getTags().contains(tag)) { + task.removeTag(tag); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "removed tag " + tag + " from task: " + task; + } else { + return "task does not have tag " + tag; + } + } +} diff --git a/src/main/java/johnchatter/Storage.java b/src/main/java/johnchatter/Storage.java new file mode 100644 index 0000000000..97defc73bb --- /dev/null +++ b/src/main/java/johnchatter/Storage.java @@ -0,0 +1,151 @@ +package johnchatter; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Stores list data and handles writing and reading file operations to save and load data + */ +public class Storage { + String filePath; + File file; + + /** + * Constructs the Storage object, initialising the file that is to be written to and read from. + */ + public Storage(String filePath) { + assert filePath != null : "filePath should not be null"; + this.filePath = filePath; + this.file = new File(this.filePath); + } + + /** + * Writes task data to the file output, with attributes delineated by pipes. + * Called after every operation that makes a change to the list of tasks. + * + * @param items The updated list of tasks + * @throws IOException If an exception occurs in writing + */ + public void writeTaskData(ArrayList items) throws IOException { + assert items != null : "ArrayList should not be null"; + assert this.file != null : "file to write to should not be null"; + + FileWriter writer = new FileWriter(this.file); + for (Task item : items) { + StringBuilder nextLine = new StringBuilder(); + if (item instanceof Todo) { + nextLine.append("T|") + .append(item.isDone ? "1" : "0").append("|") + .append(item.description); + } else if (item instanceof Deadline deadline) { + nextLine.append("D|") + .append(deadline.isDone ? "1" : "0").append("|") + .append(deadline.description).append("|") + .append(deadline.by); + } else if (item instanceof Event event) { + nextLine.append("E|") + .append(event.isDone ? "1" : "0").append("|") + .append(event.description).append("|") + .append(event.start).append("|") + .append(event.end); + } + + if (!item.getTags().isEmpty()) { + nextLine.append("|") + .append(String.join(",", item.getTags())); + } else { + nextLine.append("|"); + } + + writer.write(nextLine.toString()); + writer.write(System.lineSeparator()); + } + writer.close(); + } + + // This method was written with the assistance of ChatGPT + /** + * Reads task data from the disk, which is then used by the rest of the program. + * + * @return ArrayList The saved list of tasks + * @throws IOException If an exception occurs in scanning + */ + public ArrayList loadTaskData() throws IOException { + ArrayList items = new ArrayList<>(); + + assert this.file != null : "file to load from should not be null"; + Scanner scanner = new Scanner(this.file); + while (scanner.hasNextLine()) { + String line = scanner.nextLine().trim(); + if (line.isEmpty()) continue; + + String[] parts = line.split("\\|"); + String taskType = parts[0]; + boolean isDone = parts[1].equals("1"); + Task task = null; + + switch (taskType) { + case "T": + task = new Todo(parts[2]); + break; + case "D": + task = new Deadline(parts[2], parts[3]); + break; + case "E": + task = new Event(parts[2], parts[3], parts[4]); + break; + default: + System.out.println("unrecognised task type"); + } + + if (task == null) { + continue; + } + + if (isDone) task.markAsDone(); + + int tagFieldIndex = switch (taskType) { + case "T" -> 3; + case "D" -> 4; + case "E" -> 5; + default -> -1; + }; + + if (tagFieldIndex != -1 && parts.length > tagFieldIndex) { + String tagsString = parts[tagFieldIndex]; + if (!tagsString.isEmpty()) { + for (String tag : tagsString.split(",")) { + task.addTag(tag); + } + } + } + + items.add(task); + } + return items; + } + + /** + * Creates the directories where the data will be stored if necessary, before loading the data. + * + * @return ArrayList + * @throws IOException If the necessary directories fail to be created + */ + public ArrayList load() throws IOException { + File taskDataParent = this.file.getParentFile(); + if (!taskDataParent.exists()) { + if (!taskDataParent.mkdirs()) { + throw new IOException("mkdirs failed"); + } + } + if (!this.file.exists()) { + if (!this.file.createNewFile()) { + throw new IOException("createNewFile failed"); + } + } + return loadTaskData(); + } +} diff --git a/src/main/java/johnchatter/Task.java b/src/main/java/johnchatter/Task.java new file mode 100644 index 0000000000..c5d2018aa9 --- /dev/null +++ b/src/main/java/johnchatter/Task.java @@ -0,0 +1,49 @@ +package johnchatter; + +import java.util.HashSet; +import java.util.Set; + +/** + * Represents a task on the user's list + */ +public class Task { + protected String description; + protected boolean isDone; + protected Set tags; + + public Task(String description) { + this.description = description; + this.isDone = false; + this.tags = new HashSet<>(); + } + + public String getStatusIcon() { + return (isDone ? "X" : " "); + } + + public void markAsDone() { + this.isDone = true; + } + + public void markAsUndone() { + this.isDone = false; + } + + public void addTag(String tag) { + tags.add(tag); + } + + public void removeTag(String tag) { + tags.remove(tag); + } + + public Set getTags() { + return tags; + } + + @Override + public String toString() { + String tagString = tags.isEmpty() ? "" : " " + tags.toString(); + return "[" + this.getStatusIcon() + "] " + this.description + tagString; + } +} diff --git a/src/main/java/johnchatter/TaskList.java b/src/main/java/johnchatter/TaskList.java new file mode 100644 index 0000000000..37bdd0ed92 --- /dev/null +++ b/src/main/java/johnchatter/TaskList.java @@ -0,0 +1,112 @@ +package johnchatter; + +import java.io.IOException; +import java.util.ArrayList; + +/** + * Contains the methods for operating on the list of tasks. + */ +public class TaskList { + public ArrayList list; + + /** + * Constructs the TaskList. + */ + public TaskList(ArrayList list) { + this.list = list; + } + + /** + * Marks a task as completed. + */ + public String mark(Task task, Storage storage) throws IOException { + if (task == null) { + return "i cannot mark a task that doesn't exist yet"; + } + + task.markAsDone(); + storage.writeTaskData(list); + return "marked " + task.description + " as done"; + } + + /** + * Marks a task as incomplete. + */ + public String unmark(Task task, Storage storage) throws IOException { + if (task == null) { + return "i cannot mark a task that doesn't exist yet"; + } + + task.markAsUndone(); + storage.writeTaskData(list); + return "marked " + task.description + " as undone"; + } + + /** + * Adds a Todo to the list and writes the new data to file. + */ + public String addTodo(Todo todo, Storage storage, Ui ui) { + assert todo != null : "todo should not be null"; + assert ui != null : "Ui should not be null"; + assert storage != null : "Storage should not be null"; + + list.add(todo); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "added:\n" + todo; + } + + /** + * Adds a Deadline to the list and writes the new data to file. + */ + public String addDeadline(Deadline deadline, Storage storage, Ui ui) { + assert deadline != null : "deadline should not be null"; + assert ui != null : "Ui should not be null"; + assert storage != null : "Storage should not be null"; + + list.add(deadline); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "added:\n" + deadline; + } + + /** + * Adds an Event to the list and writes the new data to file. + */ + public String addEvent(Event event, Storage storage, Ui ui) { + assert event != null : "event should not be null"; + assert ui != null : "Ui should not be null"; + assert storage != null : "Storage should not be null"; + + list.add(event); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "added:\n" + event; + } + + /** + * Deletes a Task from the list and writes the updated data to file. + */ + public String deleteTask(Task task, Storage storage, Ui ui) { + assert task != null : "task should not be null"; + assert ui != null : "Ui should not be null"; + assert storage != null : "Storage should not be null"; + + list.remove(task); + try { + storage.writeTaskData(list); + } catch (IOException e) { + ui.showError(e.getMessage()); + } + return "deleted task: " + task; + } +} diff --git a/src/main/java/johnchatter/Todo.java b/src/main/java/johnchatter/Todo.java new file mode 100644 index 0000000000..48069b7dec --- /dev/null +++ b/src/main/java/johnchatter/Todo.java @@ -0,0 +1,15 @@ +package johnchatter; + +/** + * A simple task with no time data. + */ +public class Todo extends Task { + public Todo(String description) { + super(description); + } + + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/johnchatter/Ui.java b/src/main/java/johnchatter/Ui.java new file mode 100644 index 0000000000..88afd2e27d --- /dev/null +++ b/src/main/java/johnchatter/Ui.java @@ -0,0 +1,25 @@ +package johnchatter; + +/** + * Handles interactions with the user. + */ +public class Ui { + public Ui() { + } + + public void showWelcome() { + System.out.println("it is i, john chatter"); + } + + public void showGoodbye() { + System.out.println("goodbye!"); + } + + public void showDividerLine() { + System.out.println("------------------"); + } + + public void showError(String message) { + System.out.println("something went wrong: " + message); + } +} diff --git a/src/main/resources/images/DaDuke.png b/src/main/resources/images/DaDuke.png new file mode 100644 index 0000000000..d893658717 Binary files /dev/null and b/src/main/resources/images/DaDuke.png differ diff --git a/src/main/resources/images/DaUser.png b/src/main/resources/images/DaUser.png new file mode 100644 index 0000000000..3c82f45461 Binary files /dev/null and b/src/main/resources/images/DaUser.png differ diff --git a/src/main/resources/images/john_answer.png b/src/main/resources/images/john_answer.png new file mode 100644 index 0000000000..f7139291af Binary files /dev/null and b/src/main/resources/images/john_answer.png differ diff --git a/src/main/resources/images/john_user.png b/src/main/resources/images/john_user.png new file mode 100644 index 0000000000..49519a9abb Binary files /dev/null and b/src/main/resources/images/john_user.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..fe672c90ea --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..63ed8d1d87 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,44 @@ + + + + + + + + + + + +