diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..328a8d406f --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'checkstyle' +} + +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("Whiost.Launcher") +} + +checkstyle { + toolVersion = '10.2' +} + +shadowJar { + archiveBaseName = "whiost" + archiveClassifier = null +} + +run{ + standardInput = System.in +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..eb761a9b9a --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..39efb6e4ac --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..d1e8f7b495 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,133 @@ -# Duke User Guide +# Whiost Chatbot User Guide -// Update the title above to match the actual product name -// Product screenshot goes here +![Screenshot of an user using the chatbot.](/Ui.png) + +Whiost is a chatbot that helps you record your tasks on a smart memo pad. + + +## Storing format +'[T][] taskname (time)' +the first bracket shows the type of the task: 'T' for 'todo', 'D' for 'deadline' and 'E' for 'event'. +the second bracket shows the mark status of the task: 'x' for marked and none for unmarked. +the third bracket shows the time of the task. (if applicable) + + +## Exit +exit by input: bye -// Product intro goes here ## Adding deadlines +Adding deadlines by input: deadline 'what' /by 'when' + +Example: +input 'deadline homework /by tonight' + +expected output + +``` +Got it. I've added this task: +[D][] homework (by tonight) +Now you have x tasks in the list. +``` -// Describe the action and its outcome. -// Give examples of usage +## Adding todos +Adding deadlines by input: todo 'what' -Example: `keyword (optional arguments)` +Example: +input 'todo homework' -// A description of the expected outcome goes here +expected output ``` +Got it. I've added this task: +[T][] homework +Now you have x tasks in the list. +``` + + +## Adding events +Adding events by input: event 'what' /from 'when' /to 'when' + +Example: +input 'event party /from tonight /to tomorrow' + expected output + ``` +Got it. I've added this task: +[E][] party (from: tonight to: tomorrow) +Now you have x tasks in the list. +``` + + +## Check current task list +Check current task list by input: list -## Feature ABC +Example: +input 'list' -// Feature details +expected output (depends on what you have added in the past) + +``` +1.[D][] homework (by tonight) +2.[E][] party (from: tonight to: tomorrow) +``` -## Feature XYZ +## Marking/Unmarking tasks +Marking/Unmarking tasks by input: mark/unmark tasknumber -// Feature details \ No newline at end of file +Example: +current task list: +1.[D][] homework (by tonight) +2.[E][] party (from: tonight to: tomorrow) + +input 'mark 1' + +expected output + +``` +Nice! I've marked this task as done: +[D][X] homework (by tonight) +``` + + +## Delete tasks +Delete tasks by input: delete tasknumber + +Example: +current task list: +1.[D][X] homework (by tonight) +2.[E][] party (from: tonight to: tomorrow) + +input 'delete 1' + +expected output + +``` +Noted. I've removed this task: +[D][X] homework (by tonight) +Now you have 1 tasks in the list. +``` + + +## Finding tasks +Find tasks by input: find keywords + +Example: +current task list: +1.[E][] party (from: tonight to: tomorrow) +2.[T][] homework +3.[D][]back to home (by 9pm) + +input 'find home' + +expected output + +``` +Here are the matching tasks in your list: +1.[T][] homework +2.[D][]back to home (by 9pm) +``` \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..f28d75f756 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/.idea/.name b/src/.idea/.name new file mode 100644 index 0000000000..c186b974ad --- /dev/null +++ b/src/.idea/.name @@ -0,0 +1 @@ +Whiost.java \ No newline at end of file diff --git a/src/data/whiost.txt b/src/data/whiost.txt new file mode 100644 index 0000000000..e69de29bb2 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/Whiost/Command/Command.java b/src/main/java/Whiost/Command/Command.java new file mode 100644 index 0000000000..300de5ed5b --- /dev/null +++ b/src/main/java/Whiost/Command/Command.java @@ -0,0 +1,14 @@ +package Whiost.Command; + +public class Command { + private final CommandType type; + private final String[] args; + + public Command(CommandType type, String[] args) { + this.type = type; + this.args = args; + } + + public CommandType getType() { return type; } + public String[] getArgs() { return args; } +} diff --git a/src/main/java/Whiost/Command/CommandParser.java b/src/main/java/Whiost/Command/CommandParser.java new file mode 100644 index 0000000000..28e67d78cb --- /dev/null +++ b/src/main/java/Whiost/Command/CommandParser.java @@ -0,0 +1,88 @@ +package Whiost.Command; + +import Whiost.WhiostException; + +public class CommandParser { + public static Command parse(String input) throws WhiostException { + if (input == null || input.trim().isEmpty()) { + throw new WhiostException("Input cannot be empty"); + } + + String[] parts = input.split(" ", 2); + String command = parts[0].toLowerCase(); + String args = parts.length > 1 ? parts[1] : ""; + + return switch (command) { + case "bye" -> new Command(CommandType.BYE, new String[0]); + case "list" -> new Command(CommandType.LIST, new String[0]); + case "todo" -> parseTodo(args); + case "deadline" -> parseDeadline(args); + case "event" -> parseEvent(args); + case "mark" -> parseIndexCommand(args, CommandType.MARK); + case "unmark" -> parseIndexCommand(args, CommandType.UNMARK); + case "delete" -> parseIndexCommand(args, CommandType.DELETE); + case "find" -> parseFind(args); + default -> throw new WhiostException("I don't understand that command"); + }; + } + + private static Command parseTodo(String args) throws WhiostException { + if (args.isBlank()) throw new WhiostException("Todo description empty"); + return new Command(CommandType.TODO, new String[]{args}); + } + private static Command parseDeadline(String args) throws WhiostException { + if (args.isBlank()) throw new WhiostException("Deadline description empty"); + + String[] parts = args.split(" /by ", 2); + if (parts.length < 2) { + throw new WhiostException("Deadline requires '/by' time"); + } + + String description = parts[0].trim(); + String by = parts[1].trim(); + return new Command(CommandType.DEADLINE, new String[]{description, by}); + } + + private static Command parseEvent(String args) throws WhiostException { + if (args.isBlank()) throw new WhiostException("Event description empty"); + + String[] parts = args.split(" /from | /to ", 3); + if (parts.length < 3) { + throw new WhiostException("Event requires '/from' and '/to' times"); + } + + String description = parts[0].trim(); + String from = parts[1].trim(); + String to = parts[2].trim(); + return new Command(CommandType.EVENT, new String[]{description, from, to}); + } + + private static Command parseMark(String args) throws WhiostException { + return parseIndexCommand(args, CommandType.MARK); + } + + private static Command parseUnmark(String args) throws WhiostException { + return parseIndexCommand(args, CommandType.UNMARK); + } + + private static Command parseDelete(String args) throws WhiostException { + return parseIndexCommand(args, CommandType.DELETE); + } + + private static Command parseFind(String args) throws WhiostException { + if (args.isBlank()) throw new WhiostException("Find keyword empty"); + return new Command(CommandType.FIND, new String[]{args.trim()}); + } + + private static Command parseIndexCommand(String args, CommandType type) + throws WhiostException { + if (args.isBlank()) throw new WhiostException("Missing task index"); + + try { + int index = Integer.parseInt(args.trim()) - 1; + return new Command(type, new String[]{String.valueOf(index)}); + } catch (NumberFormatException e) { + throw new WhiostException("Invalid task index"); + } + } +} diff --git a/src/main/java/Whiost/Command/CommandType.java b/src/main/java/Whiost/Command/CommandType.java new file mode 100644 index 0000000000..7342133c97 --- /dev/null +++ b/src/main/java/Whiost/Command/CommandType.java @@ -0,0 +1,5 @@ +package Whiost.Command; + +public enum CommandType { + BYE, LIST, TODO, DEADLINE, EVENT, MARK, UNMARK, DELETE, FIND, UNKNOWN +} diff --git a/src/main/java/Whiost/DialogBox.java b/src/main/java/Whiost/DialogBox.java new file mode 100644 index 0000000000..6b1e8e8874 --- /dev/null +++ b/src/main/java/Whiost/DialogBox.java @@ -0,0 +1,59 @@ +package Whiost; +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; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/InputCommand/InputCommand.java b/src/main/java/Whiost/InputCommand/InputCommand.java new file mode 100644 index 0000000000..7eab102da9 --- /dev/null +++ b/src/main/java/Whiost/InputCommand/InputCommand.java @@ -0,0 +1,133 @@ +package Whiost.InputCommand; + +/** + * Check and handle user input + */ +public class InputCommand { + public int[] response; + public String name; + public int target; + public int target1; + public int target2; + public int timeChecker; + public String month; + public String date; + public String year; + public String time; + public String startTime; + public String endTime; + + /** + * Check the user inputs and set response command to main class + * + * @param userInput user input + */ + public InputCommand(String userInput) { + this.response = new int[11]; + for (int i = 0; i < 11; i++) { + this.response[i] = 0; + } + if (userInput.length() >= 5 && userInput.substring(0, 5).equals("todo ")) { //3 + String check = ""; + for (int i = 0; i < userInput.length() - 5; i++) { + check += " "; + } + if (userInput.equals("todo " + check)) { + this.response[0] = 1; + } else { + this.name = userInput.substring(5); + this.response[3] = 1; + } + } else if (userInput.equals("list")) { //2 + this.response[2] = 1; + } else if (userInput.length() >= 9 && userInput.substring(0, 9).equals("deadline ")) { //4 + String check = ""; + for (int i = 0; i < userInput.length() - 9; i++) { + check += " "; + } + if (userInput.equals("deadline " + check)) { + this.response[0] = 1; + } else { + this.target = userInput.indexOf('/'); + String sub = userInput.substring(this.target + 1); + if (sub.length() > 10 && sub.charAt(7) == '-' && sub.charAt(10) == '-') { + this.timeChecker = 1; + this.month = sub.substring(8, 10); + this.date = sub.substring(11, 13); + this.year = sub.substring(3, 7); + } else { + this.time = userInput.substring(this.target + 1); + this.timeChecker = 0; + } + this.name = userInput.substring(9, this.target); + this.response[4] = 1; + } + } else if (userInput.length() >= 6 && userInput.substring(0, 6).equals("event ")) { + String check = userInput.substring(6).trim(); // Get the part after "event " + + // Check if the description is empty or lacks required '/' + if (check.isEmpty() || !check.contains("/from") || !check.contains("/to")) { + this.response[0] = 1; // Trigger "empty description" error + } else { + try { + this.target1 = userInput.indexOf("/from"); + this.target2 = userInput.indexOf("/to"); + + // Validate indices + if (this.target1 == -1 || this.target2 == -1 || this.target1 >= this.target2) { + this.response[0] = 1; // Invalid format + return; + } + + this.name = userInput.substring(6, this.target1).trim(); + this.startTime = userInput.substring(this.target1 + 5, this.target2).trim(); + this.endTime = userInput.substring(this.target2 + 3).trim(); + + this.response[5] = 1; // Valid event command + } catch (StringIndexOutOfBoundsException e) { + this.response[0] = 1; // Fallback error + } + } + } else if (userInput.length() >= 5 && userInput.substring(0, 5).equals("mark ")) { //6 + String numberStr = userInput.substring(5).trim(); + try { + this.target = Integer.parseInt(numberStr) - 1; + this.response[6] = 1; + } catch (NumberFormatException e) { + this.response[0] = 1; + } + } else if (userInput.length() >= 7 && userInput.substring(0, 7).equals("unmark ")) { //7 + String numberStr = userInput.substring(7).trim(); + try { + this.target = Integer.parseInt(numberStr) - 1; + this.response[7] = 1; + } catch (NumberFormatException e) { + this.response[0] = 1; + } + } else if (userInput.length() >= 7 && userInput.substring(0, 7).equals("delete ")) { //8 + String numberStr = userInput.substring(7).trim(); + try { + this.target = Integer.parseInt(numberStr) - 1; // Parse full number + this.response[8] = 1; + } catch (NumberFormatException e) { + this.response[0] = 1; // Invalid number format + } + } else if (userInput.length() >= 5 && userInput.substring(0, 5).equals("find ")){ //9 + String check = ""; + for (int i = 0; i < userInput.length() - 5; i++) { + check += " "; + } + if (userInput.equals("find " + check)) { + this.response[0] = 1; + } else { + this.name = userInput.substring(5); + this.response[9] = 1; + } + } else if (userInput.equals("bye")) { + this.response[1] = 1; + + } else { //10 + this.response[10] = 1; + } + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Launcher.java b/src/main/java/Whiost/Launcher.java new file mode 100644 index 0000000000..5cbddd0a0c --- /dev/null +++ b/src/main/java/Whiost/Launcher.java @@ -0,0 +1,11 @@ +package Whiost; +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); + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Main.java b/src/main/java/Whiost/Main.java new file mode 100644 index 0000000000..cda8729997 --- /dev/null +++ b/src/main/java/Whiost/Main.java @@ -0,0 +1,31 @@ +package Whiost; +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 Whiost whiost = new Whiost("./src/data/whiost.txt"); + + @Override + public void start(Stage stage) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setTitle("Whiost"); + stage.setScene(scene); + fxmlLoader.getController().setWhiost(whiost); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/MainWindow.java b/src/main/java/Whiost/MainWindow.java new file mode 100644 index 0000000000..b5e9b35d98 --- /dev/null +++ b/src/main/java/Whiost/MainWindow.java @@ -0,0 +1,62 @@ +package Whiost; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.VBox; +import javafx.application.Platform; +import javafx.stage.Stage; +/** + * 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 Whiost whiost; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/user1.png")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/user2.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + /** Injects the Duke instance */ + public void setWhiost(Whiost whiost) { + this.whiost = whiost; + String greeting = whiost.getGreeting(); + dialogContainer.getChildren().addAll( + DialogBox.getDukeDialog(greeting, dukeImage) + ); + } + + /** + * 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 = whiost.handleInput(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, dukeImage) + ); + userInput.clear(); + if (response.equals(whiost.getUi().getGoodbyeMessage())) { + Stage stage = (Stage) dialogContainer.getScene().getWindow(); + stage.close(); + Platform.exit(); + } + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Storage/Storage.java b/src/main/java/Whiost/Storage/Storage.java new file mode 100644 index 0000000000..33b122843f --- /dev/null +++ b/src/main/java/Whiost/Storage/Storage.java @@ -0,0 +1,65 @@ +package Whiost.Storage; + +import Whiost.Task.*; +import Whiost.WhiostException; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; + +public class Storage { + private final Path filePath; + + public Storage(String filePath) { + this.filePath = Paths.get(filePath); + } + + public TaskList load() throws WhiostException { + TaskList tasks = new TaskList(); + try { + if (!Files.exists(filePath)) return tasks; + List lines = Files.readAllLines(filePath); + for (String line : lines) { + Task task = parseTask(line); + tasks.addTask(task); + } + } catch (Exception e) { + throw new WhiostException("Failed to load tasks: " + e.getMessage()); + } + return tasks; + } + + public void save(TaskList tasks) throws WhiostException { + try { + Files.createDirectories(filePath.getParent()); + List lines = tasks.findTasks("").stream() // Get all tasks + .map(Task::toFileFormat) + .collect(Collectors.toList()); + Files.write(filePath, lines); + } catch (Exception e) { + throw new WhiostException("Failed to save tasks: " + e.getMessage()); + } + } + + private Task parseTask(String line) throws WhiostException { + String[] parts = line.split(" \\| "); + if (parts.length < 3) throw new WhiostException("Corrupted task data"); + + String type = parts[0]; + boolean isDone = parts[1].equals("1"); + String description = parts[2]; + + Task task = switch (type) { + case "T" -> new Todo(description); + case "D" -> new Deadline(description, parts.length > 3 ? parts[3] : ""); + case "E" -> new Event(description, parts.length > 3 ? parts[3] : "", parts.length > 4 ? parts[4] : ""); + default -> throw new WhiostException("Unknown task type: " + type); + }; + + if (isDone) task.markDone(); + return task; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Task/Deadline.java b/src/main/java/Whiost/Task/Deadline.java new file mode 100644 index 0000000000..fb91331124 --- /dev/null +++ b/src/main/java/Whiost/Task/Deadline.java @@ -0,0 +1,20 @@ +package Whiost.Task; + +public class Deadline extends Task { + private final String by; + + public Deadline(String description, String by) { + super(description); + this.by = by; + } + + @Override + public String toFileFormat() { + return "D | " + (isDone ? "1" : "0") + " | " + description + " | " + by; + } + + @Override + public String toString() { + return "[D]" + getStatusIcon() + " " + description + " (by: " + by + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Task/Event.java b/src/main/java/Whiost/Task/Event.java new file mode 100644 index 0000000000..fcb0e364a9 --- /dev/null +++ b/src/main/java/Whiost/Task/Event.java @@ -0,0 +1,24 @@ +package Whiost.Task; + +public class Event extends Task { + private final String from; + private final String to; + + public Event(String description, String from, String to) { + super(description); + this.from = from; + this.to = to; + } + + @Override + public String toFileFormat() { + return "E | " + (isDone ? "1" : "0") + " | " + description + + " | " + from + " | " + to; + } + + @Override + public String toString() { + return "[E]" + getStatusIcon() + " " + description + + " (from: " + from + " to: " + to + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Task/Task.java b/src/main/java/Whiost/Task/Task.java new file mode 100644 index 0000000000..e12de5b0f3 --- /dev/null +++ b/src/main/java/Whiost/Task/Task.java @@ -0,0 +1,38 @@ +package Whiost.Task; + + +/** + * Represent current tasks created by user + */ +public abstract class Task { + protected String description; + protected boolean isDone; + + public Task(String description) { + this.description = description; + this.isDone = false; + } + + public String getDescription() { + return description; + } + + public void markDone() { + isDone = true; + } + + public void unmarkDone() { + isDone = false; + } + + public abstract String toFileFormat(); + + public String getStatusIcon() { + return isDone ? "[X]" : "[ ]"; + } + + @Override + public String toString() { + return getStatusIcon() + " " + description; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Task/TaskList.java b/src/main/java/Whiost/Task/TaskList.java new file mode 100644 index 0000000000..c3edbe5581 --- /dev/null +++ b/src/main/java/Whiost/Task/TaskList.java @@ -0,0 +1,59 @@ +package Whiost.Task; + +import Whiost.WhiostException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class TaskList { + private final List tasks = new ArrayList<>(); + + public boolean isEmpty() { + return tasks.isEmpty(); + } + + public int size() { + return tasks.size(); + } + + public Task getTask(int index) throws WhiostException { + if (index < 0 || index >= tasks.size()) { + throw new WhiostException("Task index out of bounds"); + } + return tasks.get(index); + } + + public void addTask(Task task) { + tasks.add(task); + } + + public void deleteTask(int index) throws WhiostException { + if (index < 0 || index >= tasks.size()) { + throw new WhiostException("Task index out of bounds"); + } + tasks.remove(index); + } + + public List findTasks(String keyword) { + return tasks.stream() + .filter(task -> task.getDescription().contains(keyword)) + .collect(Collectors.toList()); + } + + public String formatTaskList() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < tasks.size(); i++) { + sb.append(i + 1).append(". ").append(tasks.get(i)).append("\n"); + } + return sb.toString().trim(); + } + + public void markTask(int index, boolean isDone) throws WhiostException { + Task task = getTask(index); // Reuse existing bounds checking + if (isDone) { + task.markDone(); + } else { + task.unmarkDone(); + } + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Task/Todo.java b/src/main/java/Whiost/Task/Todo.java new file mode 100644 index 0000000000..33f3dd24a6 --- /dev/null +++ b/src/main/java/Whiost/Task/Todo.java @@ -0,0 +1,17 @@ +package Whiost.Task; + +public class Todo extends Task { + public Todo(String description) { + super(description); + } + + @Override + public String toFileFormat() { + return "T | " + (isDone ? "1" : "0") + " | " + description; + } + + @Override + public String toString() { + return "[T]" + getStatusIcon() + " " + description; + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Ui/Ui.java b/src/main/java/Whiost/Ui/Ui.java new file mode 100644 index 0000000000..e3a832cc53 --- /dev/null +++ b/src/main/java/Whiost/Ui/Ui.java @@ -0,0 +1,36 @@ +package Whiost.Ui; + +import Whiost.Task.*; +import java.util.List; + +public class Ui { + public String getGreeting() { + return "Hello! I'm Whiost\nWhat can I do for you?"; + } + + public String getGoodbyeMessage() { + return "Goodbye! Hope to see you again soon!"; + } + + public String getAddTaskMessage(Task task, int totalTasks) { + return String.format( + "Got it. I've added this task:\n %s\nNow you have %d tasks in the list.", + task, totalTasks + ); + } + + public String getDeleteMessage(Task task, int remainingTasks) { + return String.format( + "Noted. I've removed this task:\n %s\nNow you have %d tasks in the list.", + task, remainingTasks + ); + } + + public String showError(String message) { + return "OOPS!!! " + message; + } + + public String showReminders(TaskList tasks) { + return "Reminders:\n" + tasks.formatTaskList(); + } +} \ No newline at end of file diff --git a/src/main/java/Whiost/Whiost.java b/src/main/java/Whiost/Whiost.java new file mode 100644 index 0000000000..6623657638 --- /dev/null +++ b/src/main/java/Whiost/Whiost.java @@ -0,0 +1,162 @@ +package Whiost; + +import Whiost.Command.*; +import Whiost.Task.*; +import Whiost.Storage.*; +import Whiost.Ui.*; +import java.util.List; + +public class Whiost { + private final Ui ui = new Ui(); + private final Storage storage; + private final TaskList tasks; + + public Whiost(String filePath) { + this.storage = new Storage(filePath); + this.tasks = loadTasks(); + } + + private TaskList loadTasks() { + try { + return storage.load(); + } catch (WhiostException e) { + System.out.println(e.getMessage()); + return new TaskList(); + } + } + + public String getGreeting() { + return ui.getGreeting() + (tasks.isEmpty() ? "" : "\n" + ui.showReminders(tasks)); + } + + public String handleInput(String input) { + try { + Command command = CommandParser.parse(input); + return executeCommand(command); + } catch (WhiostException e) { + return ui.showError(e.getMessage()); + } + } + + private String executeCommand(Command command) throws WhiostException { + return switch (command.getType()) { + case BYE -> handleBye(); + case LIST -> handleList(); + case TODO -> handleTodo(command.getArgs()); + case DEADLINE -> handleDeadline(command.getArgs()); + case EVENT -> handleEvent(command.getArgs()); + case MARK -> handleMark(command.getArgs()); + case UNMARK -> handleUnmark(command.getArgs()); + case DELETE -> handleDelete(command.getArgs()); + case FIND -> handleFind(command.getArgs()); + default -> throw new WhiostException("Unknown command"); + }; + } + + // Command Handlers + private String handleBye() { + try { + storage.save(tasks); + return ui.getGoodbyeMessage(); + } catch (WhiostException e) { + return ui.showError("Failed to save tasks: " + e.getMessage()); + } + } + + private String handleList() { + if (tasks.isEmpty()) { + return ui.showError("There are no tasks in your list"); + } + return "Here are your tasks:\n" + tasks.formatTaskList(); + } + + private String handleTodo(String[] args) throws WhiostException { + if (args.length < 1 || args[0].isEmpty()) { + throw new WhiostException("Todo description cannot be empty"); + } + Task task = new Todo(args[0]); + tasks.addTask(task); + return ui.getAddTaskMessage(task, tasks.size()); + } + + private String handleDeadline(String[] args) throws WhiostException { + if (args.length < 2 || args[0].isEmpty() || args[1].isEmpty()) { + throw new WhiostException("Invalid deadline format. Use: deadline /by