diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f578f7960d --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: Launcher + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..036a066c77 --- /dev/null +++ b/build.gradle @@ -0,0 +1,63 @@ +plugins { + id 'java' + id 'application' + id 'checkstyle' + id 'com.github.johnrengelman.shadow' version '5.1.0' +} + +repositories { + mavenCentral() +} + +dependencies { + String javaFxVersion = '11' + + 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' +} + +dependencies { + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.5.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.5.0' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClassName = "Launcher" +} + +shadowJar { + archiveBaseName = "duke" + archiveClassifier = null +} + +checkstyle { + toolVersion = '8.29' +} + +run{ + standardInput = System.in +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..143fdade75 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,399 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..135ea49ee0 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/data/Duke.txt b/data/Duke.txt new file mode 100644 index 0000000000..9e3e8ab9ef --- /dev/null +++ b/data/Duke.txt @@ -0,0 +1,3 @@ +T | 1 | abc +T | 1 | return book +D | 1 | meeting | 2020-01-01 1600 diff --git a/docs/README.md b/docs/README.md index fd44069597..9809f8d94a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,20 +1,133 @@ # User Guide - +This is a simple user guide to Duke, a personal chat-bot to manage your task-list. ## Features - -### Feature 1 -Description of feature. + There are three types of tasks in Duke: `Todo` `Deadline` and `Event` +All tasks have features **command** and **isDone** (indicating whether this task is completed or not). + - `Deadline` and `Event` have an additional feature **time**. + - Tasks can added, deleted, and marked as done. ## Usage -### `Keyword` - Describe action +### `todo COMMAND` - Adds a task that is to be done. + +Duke will add a task of type ToDo into your list. + +Example of usage: + +`todo read book` + +Expected outcome: + +`Got it. I've added this task: + [T][✘]read book + Now you have 1 tasks in the list.` + + +### `event COMMAND /at DATETIME` - Adds a task that is to be done in a certain date and time. + +Duke will add a task of type Event into your list. + +Example of usage: + +`event meeting /at 2020-01-01 1600` + +Expected outcome: + +`Got it. I've added this task: +[E][✘]meeting(by: Jan 1 2020 16:00) +Now you have 2 tasks in the list.` + + +### `deadline COMMAND /by DATETIME` - Adds a task that is to be done by a certain date and time. + +Duke will add a task of type Deadline into your list. + +Example of usage: + +`event return book /by 2000-01-01 1600` + +Expected outcome: + +`Got it. I've added this task: +[D][✘]return book(by: Jan 1 2000 16:00) +Now you have 3 tasks in the list.` + + +### `done INDEX` - Marks task as done. +Duke will mark the task indicate by INDEX as done and update the field in your task list. + +Example of usage: + +`done 1` + +Expected outcome: + +`Nice! I've marked this task as done: + [T][✓]read book` + + +### `delete INDEX` - Deletes a task from the list. +Duke will delete the task indicate by INDEX and update your task list. + +Example of usage: + +`delete 2` + +Expected outcome: + +`Noted. I've removed this task: + [E][✘]meeting(by: Jan 1 2020 16:00)` + + +### `list` - Views your current list of tasks. + +Duke will show the detailed list of your current tasks. + +Example of usage: + +`list` + +Expected outcome: + +`[T][✓]read book + [D][✘]return book(by: Jan 1 2000 16:00)` + +### `stats` - Views the statistics of your task list. + +Duke will show the total number of tasks, the number of task of each type, and the number of completed tasks in your list. + +Example of usage: + +`stats` + +Expected outcome: + +`You have 2 tasks in total, including 0 events, 1 deadlines, and 1 todos. + You have completed 1 tasks.` + + +### `find KEYWORD` - Finds tasks that matches the given keyword. + +Duke will show all tasks whose command includes the given KEYWORD. + +Example of usage: + +`find read` + +Expected outcome: + +`Here are the matching tasks in your list: +1.[T][✓]read book` + + +### `bye` - Exits Duke. -Describe action and its outcome. +Duke will close the dialogue box and exit. Example of usage: -`keyword (optional arguments)` +`bye` Expected outcome: -`outcome` +`Bye. Hope to see you again soon!` \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..e53c8fa345 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..f3d88b1c2f 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..b7c8c5dbf5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..2fe81a7d95 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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 UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000..62bd9b9cce --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@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=. +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%" == "0" goto init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/Deadline.java b/src/main/java/Deadline.java new file mode 100644 index 0000000000..c511c87120 --- /dev/null +++ b/src/main/java/Deadline.java @@ -0,0 +1,38 @@ +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents a Deadline object characterized by a command and a time. + */ +public class Deadline extends Task { + /** + * The time of a deadline. + */ + private LocalDateTime time; + + /** + * Creates a new Deadline with the given command and time. + */ + public Deadline(String command, LocalDateTime time) { + super(command); + this.time = time; + } + + /** + * Returns the time of a deadline. + * @return the time of this deadline. + */ + public LocalDateTime getTime() { + return this.time; + } + + /** + * Returns a string representation of a deadline. + * @return the string representation of this deadline. + */ + @Override + public String toString() { + return "[D]" + super.toString() + "(by: " + + time.format(DateTimeFormatter.ofPattern("MMM d yyyy HH:mm")) + ")"; + } +} diff --git a/src/main/java/DialogBox.java b/src/main/java/DialogBox.java new file mode 100644 index 0000000000..f578c16b2c --- /dev/null +++ b/src/main/java/DialogBox.java @@ -0,0 +1,59 @@ +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); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/Duke.java b/src/main/java/Duke.java index 5d313334cc..0b1a9f06d4 100644 --- a/src/main/java/Duke.java +++ b/src/main/java/Duke.java @@ -1,10 +1,82 @@ +import java.io.FileNotFoundException; + +/** + * Represents a Duke robot that deals with multiple tasks. + */ public class Duke { + /** + * The Storage used in Duke. + */ + private Storage storage; + /** + * The list of tasks. + */ + private TaskList tasks; + /** + * The user interface. + */ + private Ui ui; + /** + * The Parser used in Duke. + */ + private Parser parser; + + /** + * Creates a new Duke with the given filePath. + */ + public Duke(String filePath) { + this.ui = new Ui(); + this.storage = new Storage(filePath); + try { + this.tasks = new TaskList(storage.load()); + } catch (FileNotFoundException e) { + System.out.println(ui.showLoadingError()); + this.tasks = new TaskList(); + } + } + + /** + * Creates a new Duke. + */ + public Duke() { + this.ui = new Ui(); + this.storage = new Storage("data"); + try { + this.tasks = new TaskList(storage.load()); + } catch (FileNotFoundException e) { + System.out.println(ui.showLoadingError()); + this.tasks = new TaskList(); + } + } + + /** + * Runs Duke. + */ + public void run() { + this.parser = new Parser(ui, tasks, storage); + parser.run(); + } + + /** + * Runs Duke with the given filePath. + */ public static void main(String[] args) { - String logo = " ____ _ \n" - + "| _ \\ _ _| | _____ \n" - + "| | | | | | | |/ / _ \\\n" - + "| |_| | |_| | < __/\n" - + "|____/ \\__,_|_|\\_\\___|\n"; - System.out.println("Hello from\n" + logo); + new Duke().run(); + } + + /** + * Generates a response to user input. + * @param input the user command. + * @return a response message to user. + */ + public String getResponse(String input) { + this.parser = new Parser(ui, tasks, storage); + String response = ""; + try { + response = parser.handleCommand(input); + } catch (DukeException e) { + response = ui.showCommandError(e); + } + return response; } } diff --git a/src/main/java/DukeException.java b/src/main/java/DukeException.java new file mode 100644 index 0000000000..0ef5f7414b --- /dev/null +++ b/src/main/java/DukeException.java @@ -0,0 +1,24 @@ +/** + * Represents exceptions that may happen while running Duke. + */ +public class DukeException extends Exception { + /** + * The type of DukeException caught. + */ + private String type; + + /** + * Creates a new DukeException with the given type. + */ + public DukeException (String type) { + this.type = type; + } + + /** + * Returns the type of a DukeException. + * @return the type of this exception. + */ + public String getType() { + return this.type; + } +} diff --git a/src/main/java/Event.java b/src/main/java/Event.java new file mode 100644 index 0000000000..0386b20a6c --- /dev/null +++ b/src/main/java/Event.java @@ -0,0 +1,38 @@ +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents an Event object characterized by a command and a time. + */ +public class Event extends Task { + /** + * The time of an event. + */ + private LocalDateTime time; + + /** + * Creates a new Event with the given command and time. + */ + public Event(String command, LocalDateTime time) { + super(command); + this.time = time; + } + + /** + * Returns the time of an event. + * @return the time of this event. + */ + public LocalDateTime getTime() { + return this.time; + } + + /** + * Returns a string representation of an event. + * @return the string representation of this event. + */ + @Override + public String toString() { + return "[E]" + super.toString() + "(at: " + + time.format(DateTimeFormatter.ofPattern("MMM d yyyy HH:mm")) + ")"; + } +} diff --git a/src/main/java/Launcher.java b/src/main/java/Launcher.java new file mode 100644 index 0000000000..43d64c26fb --- /dev/null +++ b/src/main/java/Launcher.java @@ -0,0 +1,10 @@ +import javafx.application.Application; + +/** + * A launcher class to workaround classpath issues. + */ +public class Launcher { + public static void main(String[] args) { + Application.launch(Main.class, args); + } +} diff --git a/src/main/java/Main.java b/src/main/java/Main.java new file mode 100644 index 0000000000..5bbcf5d55c --- /dev/null +++ b/src/main/java/Main.java @@ -0,0 +1,29 @@ +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(); + + @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().setDuke(duke); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/MainWindow.java b/src/main/java/MainWindow.java new file mode 100644 index 0000000000..9088123ff2 --- /dev/null +++ b/src/main/java/MainWindow.java @@ -0,0 +1,55 @@ +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 Duke duke; + private Ui ui; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/DaUser.jpg")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/DaDuke.jpg")); + + /** + * Initializes Gui and greets to the user. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + dialogContainer.getChildren().add(DialogBox.getDukeDialog( + ui.printLogo() + ui.greet(), 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/Parser.java b/src/main/java/Parser.java new file mode 100644 index 0000000000..952d65388c --- /dev/null +++ b/src/main/java/Parser.java @@ -0,0 +1,108 @@ +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Scanner; + +/** + * Represents a Parser. The Parser class deals with making sense of the user command and running the command. + */ +public class Parser { + /** + * The user interface. + */ + private static Ui ui; + /** + * The list of task. + */ + private static TaskList tasks; + /** + * The storage object used. + */ + private static Storage storage; + + /** + * Creates a new Parser with the given Ui, TaskList and Storage. + */ + public Parser(Ui ui, TaskList tasks, Storage storage) { + this.ui = ui; + this.tasks = tasks; + this.storage = storage; + } + + /** + * Greets and runs the user command line by line. + */ + public static void run() { + Scanner scanner = new Scanner(System.in); + String greetingwords; + greetingwords = ui.printLogo(); + greetingwords += ui.greet(); + System.out.println(greetingwords); + + while (scanner.hasNextLine()) { + String command = scanner.nextLine(); + try { + System.out.println(handleCommand(command)); + } catch (DukeException e) { + System.out.println(ui.showCommandError(e)); + } + } + } + + /** + * Deals with the user command. + * @param command the command given by user. + * @throws DukeException when the instruction has an invalid task type, + * or the task type is specified but content is empty. + */ + public static String handleCommand(String command) throws DukeException { + String result; + if (command.equals("bye")) { + result = ui.exit(); + } else if (command.equals("list")) { + result = ui.printList(tasks.getTasks()); + } else if (command.split(" ")[0].equals("done")) { + int index = Integer.parseInt(command.split(" ")[1]); + result = tasks.done(index); + storage.record(tasks.getTasks()); + } else if (command.split(" ")[0].equals("delete")) { + result = tasks.delete(Integer.parseInt(command.split(" ")[1])); + storage.record(tasks.getTasks()); + } else if (command.split(" ")[0].equals("find")) { + String keyword = command.replace("find ", ""); + result = tasks.find(keyword); + } else if (command.split(" ")[0].equals("todo")) { + String taskcommand = command.replace("todo", ""); + if (!taskcommand.equals("")) { + result = tasks.add(new ToDo(taskcommand)); + } else { + throw new DukeException("EmptyToDo"); + } + storage.record(tasks.getTasks()); + } else if (command.split(" ")[0].equals("deadline")) { + String taskcommand = command.split("/")[0].replace("deadline", ""); + if (!taskcommand.equals("")) { + String time = command.split("/")[1].replace("by ", ""); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + result = tasks.add(new Deadline(taskcommand, LocalDateTime.parse(time, formatter))); + } else { + throw new DukeException("EmptyDeadline"); + } + storage.record(tasks.getTasks()); + } else if (command.split(" ")[0].equals("event")) { + String taskcommand = command.split("/")[0].replace("event", ""); + if (!taskcommand.equals("")) { + String time = command.split("/")[1].replace("at ", ""); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + result = tasks.add(new Deadline(taskcommand, LocalDateTime.parse(time, formatter))); + } else { + throw new DukeException("EmptyEvent"); + } + storage.record(tasks.getTasks()); + } else if (command.equals("stats")) { + result = ui.printStats(tasks); + } else { + throw new DukeException("invalid"); + } + return result; + } +} diff --git a/src/main/java/Statistics.java b/src/main/java/Statistics.java new file mode 100644 index 0000000000..8e2e4c8bb5 --- /dev/null +++ b/src/main/java/Statistics.java @@ -0,0 +1,93 @@ +/** + * Represents the task statistics. + */ +public class Statistics { + private int numberOfTasks; + private int numberOfEvents; + private int numberOfDeadlines; + private int numberOfTodos; + private int numberOfCompletedTasks; + + /** + * Creates a Statistics object. + * Initially all statistics are set to zero. + */ + public Statistics() { + this.numberOfTasks = 0; + this.numberOfEvents = 0; + this.numberOfDeadlines = 0; + this.numberOfTodos = 0; + this.numberOfCompletedTasks = 0; + } + + /** + * Records a new event. + */ + public void eventIncrement() { + numberOfTasks++; + numberOfEvents++; + } + + /** + * Records a new deadline. + */ + public void deadlineIncrement() { + numberOfTasks++; + numberOfDeadlines++; + } + + /** + * Records a new todo. + */ + public void todoIncrement() { + numberOfTasks++; + numberOfTodos++; + } + + /** + * Records a new completed task. + */ + public void completeTask() { + numberOfCompletedTasks++; + } + + /** + * Gets the total number of tasks. + * @return number of tasks. + */ + public int getNumberOfTasks() { + return numberOfTasks; + } + + /** + * Gets the total number of events. + * @return number of events. + */ + public int getNumberOfEvents() { + return numberOfEvents; + } + + /** + * Gets the total number of todos. + * @return number of todos. + */ + public int getNumberOfTodos() { + return numberOfTodos; + } + + /** + * Gets the total number of deadlines. + * @return number of deadlines. + */ + public int getNumberOfDeadlines() { + return numberOfDeadlines; + } + + /** + * Gets the total number of completed tasks. + * @return number of CompletedTasks. + */ + public int getNumberOfCompletedTasks() { + return numberOfCompletedTasks; + } +} diff --git a/src/main/java/Storage.java b/src/main/java/Storage.java new file mode 100644 index 0000000000..3c3451cde8 --- /dev/null +++ b/src/main/java/Storage.java @@ -0,0 +1,123 @@ +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Represents a Storage. The Storage class deals with loading tasks from the file and saving tasks in the file. + */ +public class Storage { + /** + * The filePath of package. + */ + private static String filePath; + /** + * The user interface. + */ + private static Ui ui; + + /** + * Creates a new Storage with the given filepath. + */ + public Storage(String filePath) { + this.filePath = filePath; + this.ui = new Ui(); + initiateFile(); + } + + /** + * Initiates the file. + **/ + private void initiateFile() { + try { + if (Files.notExists(Paths.get(filePath))) { + Files.createDirectory(Paths.get(filePath)); + } + if (Files.notExists(Paths.get(filePath + "/Duke.txt"))) { + Files.createFile(Paths.get(filePath + "/Duke.txt")); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Loads tasks from the file. + * @return the task list. + * @throws FileNotFoundException when the filePath is invalid. + */ + public static ArrayList load() throws FileNotFoundException { + File file = new File(filePath + "/Duke.txt"); + Scanner sc = new Scanner(file); + ArrayList tasks = new ArrayList(); + while (sc.hasNextLine()) { + String[] data = sc.nextLine().split(" \\| "); + if (data[0].equals("T")) { + ToDo todo = new ToDo(data[2]); + tasks.add(todo); + if (data[1].equals("1")) { + todo.setDone(); + } + } else if (data[0].equals("D")) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + LocalDateTime time = LocalDateTime.parse(data[3], formatter); + Deadline deadline = new Deadline(data[2], time); + tasks.add(deadline); + if (data[1].equals("1")) { + deadline.setDone(); + } + } else if (data[0].equals("E")) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + LocalDateTime time = LocalDateTime.parse(data[3], formatter); + Event event = new Event(data[2], time); + tasks.add(event); + if (data[1].equals("1")) { + event.setDone(); + } + } + } + return tasks; + } + + /** + * Saves tasks to the file. + * @throws IOException ioexception. + */ + public static void writeToFile(ArrayList tasks) throws IOException { + FileWriter fileWriter = new FileWriter(filePath + "/Duke.txt"); + for (int i = 0; i < tasks.size(); i++) { + Task task = tasks.get(i); + if (task instanceof ToDo) { + String text = "T | " + (task.getStatus() ? "1" : "0") + " | " + task.getCommand(); + fileWriter.write(text + System.lineSeparator()); + } else if (task instanceof Deadline) { + String text = "D | " + (task.getStatus() ? "1" : "0") + " | " + task.getCommand() + " | " + + ((Deadline) task).getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm")); + fileWriter.write(text + System.lineSeparator()); + } else if (task instanceof Event) { + String text = "E | " + (task.getStatus() ? "1" : "0") + " | " + task.getCommand() + " | " + + ((Event) task).getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm")); + fileWriter.write(text + System.lineSeparator()); + } + } + fileWriter.close(); + } + + /** + * Tries to record the changes tasks to the file. + * @param tasks the list of task to be written to file. + */ + public static void record(ArrayList tasks) { + try { + writeToFile(tasks); + } catch (IOException e) { + System.out.println(ui.showIoException(e)); + } + } +} diff --git a/src/main/java/Task.java b/src/main/java/Task.java new file mode 100644 index 0000000000..266646bb9d --- /dev/null +++ b/src/main/java/Task.java @@ -0,0 +1,58 @@ +/** + * Represents a Task object. + */ +public class Task { + /** + * The command of a task. + */ + protected String command; + /** + * Indicates whether the task is done or not. + */ + protected boolean isDone; + + /** + * Creates a new Task with the given command. + * Initially the task is not done. + */ + public Task(String command) { + this.command = command; + this.isDone = false; + } + + /** + * Returns the command of a task. + * @return the command of this task. + */ + public String getCommand() { + return this.command; + } + + /** + * Returns the status of a task. + * @return true if this task is done, false if this task is not done yet. + */ + public boolean getStatus() { + return this.isDone; + } + + /** + * Sets this task as done. + */ + public void setDone() { + this.isDone = true; + } + + /** + * Returns a string representation of a task. + * @return the string representation of this task. + */ + @Override + public String toString() { + if (isDone) { + return "[\u2713]" + this.command; + } else { + return "[\u2718]" + this.command; + } + } +} diff --git a/src/main/java/TaskList.java b/src/main/java/TaskList.java new file mode 100644 index 0000000000..d0eceb9045 --- /dev/null +++ b/src/main/java/TaskList.java @@ -0,0 +1,129 @@ +import java.util.ArrayList; + +/** + * Represents the task list that stores all current tasks. + */ +public class TaskList { + /** + * The list of task. + */ + private static ArrayList tasks; + /** + * The user interface. + */ + private static Ui ui; + + /** + * Creates a new TaskList with the given arraylist that contains tasks. + */ + public TaskList(ArrayList tasks) { + this.tasks = tasks; + this.ui = new Ui(); + } + + /** + * Creates an empty TaskList. + */ + public TaskList() { + this.tasks = new ArrayList(); + this.ui = new Ui(); + } + + /** + * Returns the task list. + * @return list of this TaskList. + */ + public ArrayList getTasks() { + return this.tasks; + } + + /** + * Adds a task to this TaskList. + * @param task The task to be added. + */ + public static String add(Task task) { + tasks.add(task); + return ui.add(task, tasks); + } + + /** + * Marks a task in this list as done. + * @param n Index of the task that is done. + */ + public static String done(int n) { + assert tasks.size() > 0; + tasks.get(n - 1).setDone(); + return ui.done(n, tasks); + } + + /** + * Deletes a task in this list. + * @param n Index of the task to be deleted. + */ + public static String delete(int n) { + assert tasks.size() > 0; + String result; + result = ui.delete(n, tasks); + tasks.remove(n - 1); + result += "\n" + ui.count(tasks); + return result; + } + + /** + * Finds tasks that matches the given keyword. + * @param keyword The given keyword. + */ + public String find(String keyword) { + ArrayList results = new ArrayList(); + for (Task task: tasks) { + if (task.getCommand().contains(keyword)) { + results.add(task); + } + } + return ui.findKeyword(results); + } + + public int getNumTask() { + return tasks.size(); + } + + public int getNumTodo() { + int result = 0; + for (Task task: tasks) { + if (task instanceof ToDo) { + result++; + } + } + return result; + } + + public int getNumEvent() { + int result = 0; + for (Task task: tasks) { + if (task instanceof Event) { + result++; + } + } + return result; + } + + public int getNumDeadline() { + int result = 0; + for (Task task: tasks) { + if (task instanceof Deadline) { + result++; + } + } + return result; + } + + public int getNumCompleted() { + int result = 0; + for (Task task: tasks) { + if (task.getStatus()) { + result++; + } + } + return result; + } +} diff --git a/src/main/java/ToDo.java b/src/main/java/ToDo.java new file mode 100644 index 0000000000..48ca9d285e --- /dev/null +++ b/src/main/java/ToDo.java @@ -0,0 +1,21 @@ +/** + * Represents a ToDo object characterized by a command. + */ +public class ToDo extends Task { + + /** + * Creates a new ToDo with the given command. + */ + public ToDo(String command) { + super(command); + } + + /** + * Returns a string representation of a todo. + * @return the string representation of this todo. + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/Ui.java b/src/main/java/Ui.java new file mode 100644 index 0000000000..ee408777e5 --- /dev/null +++ b/src/main/java/Ui.java @@ -0,0 +1,173 @@ +import java.io.IOException; +import java.util.ArrayList; + +/** + * Represents the user interface. This Ui class outputs messages and interacts with the user. + */ +public class Ui { + + /** + * Creates a new Ui. + */ + public Ui() { } + + /** + * Prints the logo of Duke. + * @return the logo of Duke. + */ + public static String printLogo() { + String logo = " ____ _ \n" + + "| _ \\ _ _| | _____ \n" + + "| | | | | | | |/ / _ \\\n" + + "| |_| | |_| | < __/\n" + + "|____/ \\__,_|_|\\_\\___|\n"; + return logo; + } + + /** + * Greets to the user. + * @return the greeting message. + */ + public static String greet() { + return "Hello! I'm Duke\n What can I do for you?"; + } + + /** + * Farewell to the user. + * @return the farewell message. + */ + public static String exit() { + return "Bye. Hope to see you again soon!"; + } + + /** + * Prints the message of adding a task for the user. + * @param task the task to be added. + * @param tasks the list where the task to be added in. + * @return add command message. + */ + public static String add(Task task, ArrayList tasks) { + return "Got it. I've added this task:\n" + task.toString() + + "\n Now you have " + tasks.size() + " tasks in the list."; + } + + /** + * Prints the message of marking a task as done. + * @param n the index of the task to be marked as done. + * @param tasks the list where the task is stored in. + * @return done command message. + */ + public static String done(int n, ArrayList tasks) { + return "Nice! I've marked this task as done: \n" + + tasks.get(n - 1).toString(); + } + + /** + * Prints the message of deleting a task. + * @param n the index of the task to be deleted. + * @param tasks the list where the task to be deleted from. + * @return delete command message. + */ + public static String delete(int n, ArrayList tasks) { + return "Noted. I've removed this task:\n" + + tasks.get(n - 1).toString(); + } + + /** + * Prints the message of counting the number of total tasks. + * @param tasks the list of tasks to be counted. + * @return count command message. + */ + public static String count(ArrayList tasks) { + return "Now you have " + tasks.size() + " tasks in the list."; + } + + /** + * Prints the list of tasks. + * @param tasks The list of tasks to be printed. + * @return the list of tasks. + */ + public static String printList(ArrayList tasks) { + String result = ""; + for (int i = 0; i < tasks.size(); i++) { + if (tasks.get(i) != null) { + result += (i + 1) + ". " + tasks.get(i).toString() + "\n"; + } + } + return result; + } + + /** + * Prints the result of tasks that matches the given keyword for the user. + * @param results The list of matching tasks. + * @return the result of searching keyword. + */ + public String findKeyword(ArrayList results) { + String result = "Here are the matching tasks in your list:\n"; + for (int i = 0; i < results.size(); i++) { + if (results.get(i) != null) { + result += (i + 1) + ". " + results.get(i).toString() + "\n"; + } + } + return result; + } + + /** + * Shows command error for the user while catching duke exceptions. + * @param e the duke exception caught. + * @return command error message. + */ + public static String showCommandError(DukeException e) { + assert e.getType() != null; + String result = ""; + if (e.getType().equals("EmptyToDo")) { + result = "OOPS!!! The description of a todo cannot be empty."; + } else if (e.getType().equals("EmptyDeadline")) { + result = "OOPS!!! The description of a deadline cannot be empty."; + } else if (e.getType().equals("EmptyEvent")) { + result = "OOPS!!! The description of a event cannot be empty."; + } else if (e.getType().equals("invalid")) { + result = "OOPS!!! I'm sorry, but I don't know what that means :-("; + } else { + } + return result; + } + + /** + * Shows loading error for the user while files are not found. + * @return loading error message. + */ + public static String showLoadingError() { + return "File not found"; + } + + /** + * Shows error for the user while catching IOExceptions. + * @param e the io exception caught. + * @return ioexception error message. + */ + public static String showIoException(IOException e) { + return "Oops! " + e.getMessage(); + } + + /** + * Prints statistics for the user. + * @param tasks The task list. + * @return task statistics. + */ + public static String printStats(TaskList tasks) { + int numberOfTasks = tasks.getNumTask(); + int numberOfEvents = tasks.getNumEvent(); + int numberOfDeadlines = tasks.getNumDeadline(); + int numberOfTodos = tasks.getNumTodo(); + int numberOfCompletedTasks = tasks.getNumCompleted(); + String result = new StringBuilder() + .append("You have ").append(numberOfTasks).append(" tasks in total, including ") + .append(numberOfEvents).append(" events, ") + .append(numberOfDeadlines).append(" deadlines, and ") + .append(numberOfTodos).append(" todos.\n") + .append("You have completed ").append(numberOfCompletedTasks).append(" tasks.\n") + .toString(); + return result; + } +} diff --git a/src/main/resources/images/DaDuke.jpg b/src/main/resources/images/DaDuke.jpg new file mode 100644 index 0000000000..da0c755a56 Binary files /dev/null and b/src/main/resources/images/DaDuke.jpg differ diff --git a/src/main/resources/images/DaUser.jpg b/src/main/resources/images/DaUser.jpg new file mode 100644 index 0000000000..2947a51285 Binary files /dev/null and b/src/main/resources/images/DaUser.jpg differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..c9521bd5af --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + \ 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..6f988e7544 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +