diff --git a/README.md b/README.md index 8715d4d915..0f2208ab64 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Duke project template +# duke.Duke project template This is a project template for a greenfield Java project. It's named after the Java mascot _Duke_. Given below are instructions on how to use it. @@ -13,7 +13,7 @@ Prerequisites: JDK 11, update Intellij to the most recent version. 1. If there are any further prompts, accept the defaults. 1. Configure the project to use **JDK 11** (not other versions) as explained in [here](https://www.jetbrains.com/help/idea/sdk.html#set-up-jdk).
In the same dialog, set the **Project language level** field to the `SDK default` option. -3. After that, locate the `src/main/java/Duke.java` file, right-click it, and choose `Run Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: +3. After that, locate the `src/main/java/duke.Duke.java` file, right-click it, and choose `Run duke.Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: ``` Hello from ____ _ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..f98089a678 --- /dev/null +++ b/build.gradle @@ -0,0 +1,57 @@ +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("duke.Launcher") +} + +shadowJar { + archiveBaseName = "duke" + archiveFileName = 'Sivraj.jar' + archiveClassifier = null + dependsOn("distZip", "distTar") +} + +run{ + standardInput = System.in +} diff --git a/data/duke.txt b/data/duke.txt new file mode 100644 index 0000000000..9217531e1f --- /dev/null +++ b/data/duke.txt @@ -0,0 +1,2 @@ +T | 1 | walk + diff --git a/docs/README.md b/docs/README.md index 8077118ebe..8db77d93f9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,74 @@ -# User Guide +# User Guide - Sivraj +Sivraj is a easy to use chatbot style application to schedule and manage tasks. + +It can be distributed as a .jar file. ## Features -### Feature-ABC +### Feature- Add ToDo + +Adds a task todo with only description and no deadline. + +**Format** - `todo task` + +**Example** - `todo walk` + + + + +### Feature- Add Deadline + +Adds a deadline task with description and deadline date. + +**Format** - `deadline task /by date`, (date should be in format yyyy-mm-dd) + +**example** - `deadline return book /by 2017-08-07` + + + +### Feature- Add Event +Adds an Event task with description, start date and end date. + +**Format** - `event task /from start date & time /to end date & time`, (start/end date & time are in string format) + +**example** - `event project meeting /from Mon 2pm /to 4pm` + + +### Feature- Delete task +Deletes a task based on its index number in the task list. + +**Format** - `delete indexNumber`, (indexNumber is an integer) + +**example** - `delete 3` + + + +### Feature- Mark task +Marks a specific task as done/completed using index number. + +**Format** - `mark indexNumber`, (indexNumber is an integer) + +**example** - `mark 3` + + -Description of the feature. +### Feature- Unmark task +Marks a specific task as not done/completed using index number. -### Feature-XYZ +**Format** - `unmark indexNumber`, (indexNumber is an integer) -Description of the feature. +**example** - `unmark 3` -## Usage -### `Keyword` - Describe action -Describe the action and its outcome. +### Feature- List tasks +Lists all the current and previous tasks that are recorded in a text file. -Example of usage: +**Format** - `list` -`keyword (optional arguments)` -Expected outcome: +### Feature- Bye +Gives a goodbye message and saves the current state of task list into the text file. -Description of the outcome. +**Format** - `bye` -``` -expected output -``` diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..6b29520f27 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/duke/Deadline.java b/src/main/java/duke/Deadline.java new file mode 100644 index 0000000000..3c1884f4c6 --- /dev/null +++ b/src/main/java/duke/Deadline.java @@ -0,0 +1,46 @@ +package duke; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + + +/** + * Class to handle deadline type of tasks. + */ +public class Deadline extends Task { + private LocalDate byDate; + + /** + * Initialises a deadline task. + * + * @param description task description. + * @param by deadline date. + * @param taskType type of task. + */ + public Deadline(String description, String by, char taskType) { + super(description, taskType); + this.byDate = LocalDate.parse(by, DateTimeFormatter.ofPattern("yyyy-MM-dd")); + } + + /** + * Returns the string representation of the deadline task to be stored in a file. + * + * @return File string representation of the task. + */ + @Override + public String toFileString() { + return super.toFileString() + " | " + + byDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); + } + + /** + * Returns the string representation of the deadline task. + * + * @return String representation. + */ + @Override + public String toString() { + return super.toString() + " (by: " + + byDate.format(DateTimeFormatter.ofPattern("MMM dd yyyy")) + ")"; + } +} diff --git a/src/main/java/duke/DialogBox.java b/src/main/java/duke/DialogBox.java new file mode 100644 index 0000000000..79cb83a91a --- /dev/null +++ b/src/main/java/duke/DialogBox.java @@ -0,0 +1,81 @@ +package duke; + +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; + + /** + * Initialises a DialogBox using given text and image. + * + * @param text text to be displayed on the dialog box. + * @param img image to be displayed on the dialog box. + */ + 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); + } + + /** + * Returns a new user DialogBox with the given text and image. + * + * @param text text to be displayed on the dialog box. + * @param img image to be displayed on the dialog box. + * @return new DialogBox instance. + */ + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + /** + * Returns a new chatbot DialogBox with the given text and image. + * + * @param text text to be displayed on the dialog box. + * @param img image to be displayed on the dialog box. + * @return new DialogBox instance. + */ + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} \ No newline at end of file diff --git a/src/main/java/duke/Duke.java b/src/main/java/duke/Duke.java new file mode 100644 index 0000000000..4756a954be --- /dev/null +++ b/src/main/java/duke/Duke.java @@ -0,0 +1,47 @@ +package duke; + +import java.io.FileNotFoundException; + +/** + * Duke class to receive the response from the program. + */ +public class Duke { + private Storage storage; + private TaskList taskList; + private Ui ui; + + + /** + * Initialises a new Duke instance. + */ + public Duke() { + ui = new Ui(); + storage = new Storage(); + try { + taskList = new TaskList(storage.loadPreviousTasks()); + } catch (FileNotFoundException e) { + ui.displayLoadErrorMessage(e.getMessage()); + taskList = new TaskList(); + } + assert taskList != null : "taskList should not be null."; + } + + /** + * Returns the response of Sivraj to the user-input. + * + * @param input Input given by the user. + * @return String value to be displayed on the chat screen. + */ + public String getResponse(String input) { + + try { + String response = Parser.userCommand(input, taskList, ui, storage); + return response; + } catch (DukeException e) { + String response = ui.displayErrorMessage(e.getMessage()); + return response; + } + } +} + + diff --git a/src/main/java/duke/DukeException.java b/src/main/java/duke/DukeException.java new file mode 100644 index 0000000000..871dfae91b --- /dev/null +++ b/src/main/java/duke/DukeException.java @@ -0,0 +1,17 @@ +package duke; + +/** + * Class to define a new exception that will be + * thrown by the program in certain cases. + */ +public class DukeException extends Exception { + + /** + * Initialises a DukeException with the provided message. + * + * @param message message to be shown when the exception is caught and read. + */ + public DukeException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/Event.java b/src/main/java/duke/Event.java new file mode 100644 index 0000000000..c4093de956 --- /dev/null +++ b/src/main/java/duke/Event.java @@ -0,0 +1,43 @@ +package duke; + +/** + * Class to handle tasks of type Event. + */ +public class Event extends Task { + private String from; + private String to; + + /** + * Initialises an Event task. + * + * @param description task description. + * @param from start date and time. + * @param to end date and time. + * @param taskType type of task. + */ + public Event(String description, String from, String to, char taskType) { + super(description, taskType); + this.from = from; + this.to = to; + } + + /** + * Returns the string representation of the event task to be stored in a file. + * + * @return File string representation of the task. + */ + @Override + public String toFileString() { + return super.toFileString() + " | " + from + "-" + to; + } + + /** + * Returns the string representation of the event task. + * + * @return String representation. + */ + @Override + public String toString() { + return super.toString() + " (from: " + from + " to: " + to + ")"; + } +} diff --git a/src/main/java/duke/Launcher.java b/src/main/java/duke/Launcher.java new file mode 100644 index 0000000000..10ab03c94c --- /dev/null +++ b/src/main/java/duke/Launcher.java @@ -0,0 +1,17 @@ +package duke; +import javafx.application.Application; + +/** + * Entry point of the program. + */ +public class Launcher { + + /** + * Launches the GUI of Sivraj. + * + * @param args Command line arguments. + */ + public static void main(String[] args) { + Application.launch(Main.class, args); + } +} diff --git a/src/main/java/duke/Main.java b/src/main/java/duke/Main.java new file mode 100644 index 0000000000..a647410699 --- /dev/null +++ b/src/main/java/duke/Main.java @@ -0,0 +1,41 @@ +package duke; + +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 Duke duke = new Duke(); + + + /** + * Starts the GUI program + * @param stage the primary stage for this application, onto which + * the application scene can be set. + */ + @Override + public void start(Stage stage) { + assert duke != null : "duke instance should not be null"; + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setScene(scene); + fxmlLoader.getController().setDuke(duke); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/duke/MainWindow.java b/src/main/java/duke/MainWindow.java new file mode 100644 index 0000000000..104dee459a --- /dev/null +++ b/src/main/java/duke/MainWindow.java @@ -0,0 +1,57 @@ +package duke; + +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 Ui ui = new Ui(); + + private Duke duke; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/DaUser.png")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/DaDuke.png")); + + @FXML + public void initialize() { + + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + dialogContainer.getChildren().add( + DialogBox.getDukeDialog(ui.displayWelcomeMessage(), dukeImage) + ); + } + + public void setDuke(Duke d) { + duke = d; + } + + /** + * 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 = duke.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, dukeImage) + ); + userInput.clear(); + } +} + diff --git a/src/main/java/duke/Parser.java b/src/main/java/duke/Parser.java new file mode 100644 index 0000000000..6a4f638e7b --- /dev/null +++ b/src/main/java/duke/Parser.java @@ -0,0 +1,128 @@ +package duke; + +import java.io.IOException; + +/** + * Class to understand the input user commands. + */ +public class Parser { + + /** + * Parses through the input message to understand and execute the user command. + * + * @param input user command. + * @param taskList list where all tasks are stored. + * @param ui used to generate all the output messages. + * @param storage to load and save to the text files. + * @return Final output to be read by the getResponse in Duke class. + * @throws DukeException If input is invalid. + */ + public static String userCommand(String input, TaskList taskList, + Ui ui, Storage storage) throws DukeException { + if (input.equals("bye")) { + return parseByeCommand(taskList, ui, storage); + } else if (input.equals("list")) { + return parseListCommand(taskList, ui); + } else if (input.startsWith("todo")) { + return parseToDoCommand(input, taskList, ui); + } else if (input.startsWith("deadline")) { + return parseDeadlineCommand(input, taskList, ui); + } else if (input.startsWith("event")) { + return parseEventCommand(input, taskList, ui); + } else if (input.startsWith("mark")) { + return parseMarkCommand(input, taskList, ui); + } else if (input.startsWith("unmark")) { + return parseUnmarkCommand(input, taskList, ui); + } else if (input.startsWith("delete")) { + return parseDeleteCommand(input, taskList, ui); + } else { + throw new DukeException("I'm sorry, but I don't know what that means :-("); + } + } + + private static String parseByeCommand(TaskList taskList, Ui ui, Storage storage) { + try { + storage.appendTasksToFile(taskList); + } catch (IOException e) { + return "Something went wrong: " + e.getMessage(); + } + return ui.displayByeMessage(); + } + + private static String parseListCommand(TaskList taskList, Ui ui) { + + return ui.displayListMessage(taskList); + } + + /** + * Executes todo type of commands. + * + * @param input User command. + * @param taskList List where all tasks are stored. + * @param ui Used to generate all the output messages. + * @return Final output to be read by the getResponse in Duke class. + * @throws DukeException If no task is provided. + */ + public static String parseToDoCommand(String input, TaskList taskList, + Ui ui) throws DukeException { + if (input.length() <= 5) { + throw new DukeException("The description of a todo cannot be empty."); + } + String description = input.substring(5).trim(); + taskList.addTask(new ToDo(description, 'T')); + + return ui.displayToDoMessage(taskList); + } + + private static String parseDeadlineCommand(String input, TaskList taskList, Ui ui) { + int byIndex = input.indexOf("/by"); + String description = input.substring(9, byIndex).trim(); + String by = input.substring(byIndex + 3).trim(); + taskList.addTask(new Deadline(description, by, 'D')); + return ui.displayDeadlineMessage(taskList); + } + + private static String parseEventCommand(String input, TaskList taskList, Ui ui) { + int fromIndex = input.indexOf("/from"); + int toIndex = input.indexOf("/to"); + String description = input.substring(6, fromIndex).trim(); + String from = input.substring(fromIndex + 5, toIndex).trim(); + String to = input.substring(toIndex + 3).trim(); + taskList.addTask(new Event(description, from, to, 'E')); + return ui.displayEventMessage(taskList); + } + + private static String parseMarkCommand(String input, TaskList taskList, Ui ui) { + int taskIndex = Integer.parseInt(input.substring(5).trim()) - 1; + if (taskIndex >= 0 && taskIndex < taskList.listSize()) { + taskList.getTask(taskIndex).markAsDone(); + return ui.displayMarkMessage(taskList, taskIndex); + } else { + return "Invalid task index."; + } + } + + private static String parseUnmarkCommand(String input, TaskList taskList, + Ui ui) { + int taskIndex = Integer.parseInt(input.substring(7).trim()) - 1; + if (taskIndex >= 0 && taskIndex < taskList.listSize()) { + taskList.getTask(taskIndex).markAsNotDone(); + return ui.displayUnmarkMessage(taskList, taskIndex); + } else { + return "Invalid task index."; + } + } + + private static String parseDeleteCommand(String input, TaskList taskList, + Ui ui) { + int taskIndex = Integer.parseInt(input.substring(7).trim()) - 1; + if (taskIndex >= 0 && taskIndex < taskList.listSize()) { + Task removedTask = taskList.deleteTask(taskIndex); + return ui.displayDeleteMessage(taskList, removedTask); + } else { + return "Invalid task index."; + } + } + +} + diff --git a/src/main/java/duke/Storage.java b/src/main/java/duke/Storage.java new file mode 100644 index 0000000000..b473091582 --- /dev/null +++ b/src/main/java/duke/Storage.java @@ -0,0 +1,153 @@ +package duke; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; + +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Deals with loading tasks from the file and saving tasks + * in the file. + */ +public class Storage { + private static final String DIRECTORY_PATH = "./data"; + private static final String FILE_PATH = "./data/duke.txt"; + + /** + * Creates a new data file if it does not exist. + */ + public Storage() { + + File dataDirectory = new File(DIRECTORY_PATH); + File dataFile = new File(FILE_PATH); + + if (!dataDirectory.exists()) { + dataDirectory.mkdir(); + } + + if (!dataFile.exists()) { + try { + dataFile.createNewFile(); + } catch (IOException e) { + System.out.println("Error creating a new file:" + e); + } + } + } + + /** + * Stores all the data in the file. + * + * @param taskList List of all tasks to be saved. + * @throws IOException If there is an input or output exception. + */ + public void appendTasksToFile(TaskList taskList) + throws IOException { + FileWriter fw = new FileWriter(FILE_PATH); + for (int i = 0; i < taskList.listSize(); i++) { + Task task = taskList.getTask(i); + fw.write(task.toFileString() + System.lineSeparator()); + } + fw.close(); + } + + /** + * Loads all the previously saved tasks in an ArrayList. + * + * @return ArrayList of previous tasks. + * @throws FileNotFoundException If program cannot find the data file. + */ + public ArrayList loadPreviousTasks() + throws FileNotFoundException { + File f = new File(FILE_PATH); + Scanner s = new Scanner(f); + ArrayList tasks = new ArrayList<>(); + while (s.hasNext()) { + String line = s.nextLine(); + try { + Task task = parseTaskFromLine(line); + tasks.add(task); + } catch (DukeException e) { + System.err.println("Error parsing task from file: " + e.getMessage()); + } + + } + s.close(); + return tasks; + } + + /** + * Returns a Task after parsing through a string line. + * + * @param line String line which needs to interpreted as a Task. + * @return Task object. + * @throws DukeException If the format of the string line is invalid. + */ + public Task parseTaskFromLine(String line) throws DukeException { + String[] parts = line.split(" \\| "); + if (parts.length < 3) { + throw new DukeException("Invalid data format in the file."); + } + char taskType = parts[0].charAt(0); + boolean isDone = parts[1].equals("1"); + String description = parts[2]; + + switch (taskType) { + case 'T': + return parseToDoTask(description, taskType, isDone); + case 'D': + if (parts.length < 4) { + throw new DukeException("Invalid data format for a deadline task"); + } + String deadlineBy = parts[3]; + return parseDeadlineTask(description, deadlineBy, taskType, isDone); + case 'E': + if (parts.length < 4) { + throw new DukeException("Invalid data format for an event task."); + } + String[] eventParts = parts[3].split("-"); + String eventFrom = eventParts[0]; + String eventTo = eventParts[1]; + return parseEventTask(description, eventFrom, eventTo, taskType, isDone); + default: + throw new DukeException("Invalid task type in data file."); + } + } + + private Task parseToDoTask(String description, char taskType, boolean isDone) { + ToDo toDoTask = new ToDo(description, taskType); + if (isDone) { + toDoTask.markAsDone(); + } else { + toDoTask.markAsNotDone(); + } + return toDoTask; + } + + private Task parseDeadlineTask(String description, String deadlineBy, + char taskType, boolean isDone) { + Deadline deadlineTask = new Deadline(description, deadlineBy, taskType); + if (isDone) { + deadlineTask.markAsDone(); + } else { + deadlineTask.markAsNotDone(); + } + return deadlineTask; + } + + private Task parseEventTask(String description, String eventFrom, String eventTo, + char taskType, boolean isDone) { + Event eventTask = new Event(description, eventFrom, eventTo, taskType); + if (isDone) { + eventTask.markAsDone(); + } else { + eventTask.markAsNotDone(); + } + return eventTask; + } + + +} + diff --git a/src/main/java/duke/Task.java b/src/main/java/duke/Task.java new file mode 100644 index 0000000000..03d79e3f11 --- /dev/null +++ b/src/main/java/duke/Task.java @@ -0,0 +1,64 @@ +package duke; + +/** + * Class to represent a task. + */ +public class Task { + private String description; + private boolean isDone; + private char taskType; + + /** + * Initialises a task. + * + * @param description Short description of the task. + * @param taskType Type of task. + */ + public Task(String description, char taskType) { + this.description = description; + this.isDone = false; + this.taskType = taskType; + } + + /** + * Marks the task as done. + */ + public void markAsDone() { + isDone = true; + } + + /** + * Marks the task as undone. + */ + public void markAsNotDone() { + isDone = false; + } + + /** + * Returns the status of the task whether done or not done. + * + * @return Status of the task as [X] or []. + */ + public String getStatusIcon() { + return (isDone ? "[X]" : "[ ]"); + } + + /** + * Returns the string representation of the task to be stored in a file. + * + * @return File string representation of task. + */ + public String toFileString() { + return taskType + " | " + (isDone ? "1" : "0") + " | " + description; + } + + /** + * Returns the string representation of the task. + * + * @return String representation. + */ + @Override + public String toString() { + return "[" + taskType + "]" + getStatusIcon() + " " + description; + } +} diff --git a/src/main/java/duke/TaskList.java b/src/main/java/duke/TaskList.java new file mode 100644 index 0000000000..eecaf1cbdf --- /dev/null +++ b/src/main/java/duke/TaskList.java @@ -0,0 +1,66 @@ +package duke; + +import java.util.ArrayList; + +/** + * Class to represent a list of tasks. + */ +public class TaskList { + private ArrayList taskList; + + /** + * Initialises a task list. + */ + public TaskList() { + this.taskList = new ArrayList<>(); + } + + /** + * Initialises a task list using another ArrayList of tasks. + * + * @param tasks ArrayList of tasks. + */ + public TaskList(ArrayList tasks) { + this.taskList = tasks; + } + + /** + * Adds a task to the task list. + * + * @param task Task to be added. + */ + public void addTask(Task task) { + taskList.add(task); + } + + /** + * Deletes a task from the task list. + * + * @param index Index of task to be deleted. + * @return Deleted task. + */ + public Task deleteTask(int index) { + return taskList.remove(index); + } + + /** + * Returns the size of the task list. + * + * @return Size. + */ + public int listSize() { + return taskList.size(); + } + + /** + * Returns a specific task from the task list + * using the task index. + * + * @param taskIndex Index of the task to be fetched. + * @return Task that matches the index. + */ + public Task getTask(int taskIndex) { + return taskList.get(taskIndex); + } +} + diff --git a/src/main/java/duke/ToDo.java b/src/main/java/duke/ToDo.java new file mode 100644 index 0000000000..d98181216f --- /dev/null +++ b/src/main/java/duke/ToDo.java @@ -0,0 +1,17 @@ +package duke; + +/** + * Class to handle tasks of type todo. + */ +public class ToDo extends Task { + + /** + * Initialises a task of type todo. + * + * @param description task description. + * @param taskType type of task. + */ + public ToDo(String description, char taskType) { + super(description, taskType); + } +} diff --git a/src/main/java/duke/Ui.java b/src/main/java/duke/Ui.java new file mode 100644 index 0000000000..8f0d6fb759 --- /dev/null +++ b/src/main/java/duke/Ui.java @@ -0,0 +1,146 @@ +package duke; + + +/** + * Class to handle all the various outputs of the program + * displayed on the GUI. + */ +public class Ui { + + private static final String DASH_LINE = "----------------------------------------\n"; + + /** + * Initialises the UI. + */ + public Ui() {} + + + public String displayWelcomeMessage() { + return "Hello! I'm Sivraj\n" + "What can I do for you?"; + } + + /** + * Displays the message after a todo command is executed. + * + * @param taskList List where all tasks are stored. + * @return Message to be displayed. + */ + public String displayToDoMessage(TaskList taskList) { + return DASH_LINE + " Got it. I've added this task:" + "\n" + + " " + taskList.getTask(taskList.listSize() - 1) + "\n" + + " Now you have " + taskList.listSize() + " tasks in the list.\n" + + DASH_LINE; + } + + /** + * Displays the message after a deadline command is executed. + * + * @param taskList List where all tasks are stored. + * @return Message to be displayed. + */ + public String displayDeadlineMessage(TaskList taskList) { + return DASH_LINE + " Got it. I've added this task:\n" + + " " + taskList.getTask(taskList.listSize() - 1) + + "\n" + " Now you have " + taskList.listSize() + + " tasks in the list.\n" + DASH_LINE; + } + + /** + * Displays the message after an event command is executed. + * + * @param taskList List where all tasks are stored. + * @return Message to be displayed. + */ + public String displayEventMessage(TaskList taskList) { + return DASH_LINE + " Got it. I've added this task:\n" + + " " + taskList.getTask(taskList.listSize() - 1) + + "\n" + " Now you have " + taskList.listSize() + + " tasks in the list.\n" + DASH_LINE; + } + + /** + * Displays the message after a mark command is executed. + * + * @param taskList List where all tasks are stored. + * @param taskIndex Index of task to be marked. + * @return Message to be displayed. + */ + public String displayMarkMessage(TaskList taskList, int taskIndex) { + return DASH_LINE + " Nice! I've marked this task as done:\n" + + " " + taskList.getTask(taskIndex) + "\n" + + DASH_LINE; + } + + /** + * Displays the message after an unmark command is executed. + * + * @param taskList List where all tasks are stored. + * @param taskIndex Index of task to be unmarked. + * @return Message to be displayed. + */ + public String displayUnmarkMessage(TaskList taskList, int taskIndex) { + return DASH_LINE + " OK, I've marked this task as not done yet:\n" + + " " + taskList.getTask(taskIndex) + "\n" + + DASH_LINE; + } + + /** + * Displays the message after a list command is executed. + * + * @param taskList List where all tasks are stored. + * @return Complete list. + */ + public String displayListMessage(TaskList taskList) { + String s = ""; + for (int i = 0; i < taskList.listSize(); i++) { + s = s + "\n" + (i + 1) + "." + taskList.getTask(i); + } + return DASH_LINE + + "Here are the tasks in your list:" + "\n" + + s + "\n" + DASH_LINE; + } + + /** + * Displays the message after a delete command is executed. + * + * @param taskList List where all tasks are stored. + * @param removedTask Task that has been removed. + * @return Message to be displayed. + */ + public String displayDeleteMessage(TaskList taskList, Task removedTask) { + return DASH_LINE + " Noted. I've removed this task: \n" + + " " + removedTask + "\n" + + " Now you have " + taskList.listSize() + " tasks in the list.\n" + + DASH_LINE; + } + + /** + * Displays the message if there is some error. + * + * @param message Error message. + * @return Error Message. + */ + public String displayErrorMessage(String message) { + + return DASH_LINE + " OOPS " + message + "\n" + DASH_LINE; + } + + /** + * Displays the message after a bye command is executed. + * + * @return Message to be displayed. + */ + public String displayByeMessage() { + return "Bye. Hope to see you again soon!"; + } + + /** + * Displays the message if there is some error in loading the tasks. + * + * @param errorMessage Error Message. + */ + public void displayLoadErrorMessage(String errorMessage) { + System.out.println("Error loading tasks: " + errorMessage); + } +} + 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/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..cf3e972e9a --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..123c846900 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,25 @@ + + + + + + + + + + + +