By: Team F10-B4
Since: Aug 2017
Licence: MIT
- 1. Setting up
- 2. Design
- 3. Implementation
- 3.1. Undo/Redo mechanism
- 3.2. Logging
- 3.3. Configuration
- 3.4. Find person(s) using different details
- 3.5. Important tag
- 3.6. Sorted persons
- 3.7. Quick add
- 3.8. Persisting colored tags
- 3.9. Google Map Mechanism
- 3.10. Theme Changer Mechanism
- 3.11. Import Mechanism
- 3.12. Add person(s) Birthday
- 3.13. Add photo to person(s)
- 3.14. Add remark to person
- 4. Documentation
- 5. Testing
- 6. Dev Ops
- Appendix A: Suggested Programming Tasks to Get Started
- Appendix B: User Stories
- Appendix C: Use Cases
- Appendix D: Non Functional Requirements
- Appendix E: Glossary
- Appendix F: Product Survey
-
JDK
1.8.0_60
or laterℹ️Having any Java 8 version is not enough.
This app will not work with earlier versions of Java 8. -
IntelliJ IDE
ℹ️IntelliJ by default has Gradle and JavaFx plugins installed.
Do not disable them. If you have disabled them, go toFile
>Settings
>Plugins
to re-enable them.
-
Fork this repo, and clone the fork to your computer
-
Open IntelliJ (if you are not in the welcome screen, click
File
>Close Project
to close the existing project dialog first) -
Set up the correct JDK version for Gradle
-
Click
Configure
>Project Defaults
>Project Structure
-
Click
New…
and find the directory of the JDK
-
-
Click
Import Project
-
Locate the
build.gradle
file and select it. ClickOK
-
Click
Open as Project
-
Click
OK
to accept the default settings -
Open a console and run the command
gradlew processResources
(Mac/Linux:./gradlew processResources
). It should finish with theBUILD SUCCESSFUL
message.
This will generate all resources required by the application and tests.
-
Run the
seedu.address.MainApp
and try a few commands -
Run the tests to ensure they all pass.
This project follows oss-generic coding standards. IntelliJ’s default style is mostly compliant with ours but it uses a different import order from ours. To rectify,
-
Go to
File
>Settings…
(Windows/Linux), orIntelliJ IDEA
>Preferences…
(macOS) -
Select
Editor
>Code Style
>Java
-
Click on the
Imports
tab to set the order-
For
Class count to use import with '*'
andNames count to use static import with '*'
: Set to999
to prevent IntelliJ from contracting the import statements -
For
Import Layout
: The order isimport static all other imports
,import java.*
,import javax.*
,import org.*
,import com.*
,import all other imports
. Add a<blank line>
between eachimport
-
Optionally, you can follow the UsingCheckstyle.adoc document to configure Intellij to check style-compliance as you write code.
After forking the repo, links in the documentation will still point to the se-edu/addressbook-level4
repo. If you plan to develop this as a separate product (i.e. instead of contributing to the se-edu/addressbook-level4
) , you should replace the URL in the variable repoURL
in DeveloperGuide.adoc
and UserGuide.adoc
with the URL of your fork.
Set up Travis to perform Continuous Integration (CI) for your fork. See UsingTravis.adoc to learn how to set it up.
Optionally, you can set up AppVeyor as a second CI (see UsingAppVeyor.adoc).
ℹ️
|
Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) |
When you are ready to start coding,
-
Get some sense of the overall design by reading the Architecture section.
-
Take a look at the section Suggested Programming Tasks to Get Started.
Figure 2.1.1 : Architecture Diagram
The Architecture Diagram given above explains the high-level design of the App. Given below is a quick overview of each component.
💡
|
The .pptx files used to create diagrams in this document can be found in the diagrams folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose Save as picture .
|
Main
has only one class called MainApp
. It is responsible for,
-
At app launch: Initializes the components in the correct sequence, and connects them up with each other.
-
At shut down: Shuts down the components and invokes cleanup method where necessary.
Commons
represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level.
-
EventsCenter
: This class (written using Google’s Event Bus library) is used by components to communicate with other components using events (i.e. a form of Event Driven design) -
LogsCenter
: Used by many classes to write log messages to the App’s log file.
The rest of the App consists of four components.
Each of the four components
-
Defines its API in an
interface
with the same name as the Component. -
Exposes its functionality using a
{Component Name}Manager
class.
For example, the Logic
component (see the class diagram given below) defines it’s API in the Logic.java
interface and exposes its functionality using the LogicManager.java
class.
Figure 2.1.2 : Class Diagram of the Logic Component
The Sequence Diagram below shows how the components interact for the scenario where the user issues the command delete 1
.
Figure 2.1.3a : Component interactions for delete 1
command (part 1)
ℹ️
|
Note how the Model simply raises a AddressBookChangedEvent when the Address Book data are changed, instead of asking the Storage to save the updates to the hard disk.
|
The diagram below shows how the EventsCenter
reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time.
Figure 2.1.3b : Component interactions for delete 1
command (part 2)
ℹ️
|
Note how the event is propagated through the EventsCenter to the Storage and UI without Model having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components.
|
The sections below give more details of each component.
Figure 2.2.1 : Structure of the UI Component
API : Ui.java
The UI consists of a MainWindow
that is made up of parts e.g.CommandBox
, ResultDisplay
, PersonListPanel
, StatusBarFooter
, BrowserPanel
etc. All these, including the MainWindow
, inherit from the abstract UiPart
class.
The UI
component uses JavaFx UI framework. The layout of these UI parts are defined in matching .fxml
files that are in the src/main/resources/view
folder. For example, the layout of the MainWindow
is specified in MainWindow.fxml
The UI
component,
-
Executes user commands using the
Logic
component. -
Binds itself to some data in the
Model
so that the UI can auto-update when data in theModel
change. -
Responds to events raised from various parts of the App and updates the UI accordingly.
Figure 2.3.1 : Structure of the Logic Component
Figure 2.3.2 : Structure of Commands in the Logic Component. This diagram shows finer details concerning XYZCommand
and Command
in Figure 2.3.1
API :
Logic.java
-
Logic
uses theAddressBookParser
class to parse the user command. -
This results in a
Command
object which is executed by theLogicManager
. -
The command execution can affect the
Model
(e.g. adding a person) and/or raise events. -
The result of the command execution is encapsulated as a
CommandResult
object which is passed back to theUi
.
Given below is the Sequence Diagram for interactions within the Logic
component for the execute("delete 1")
API call.
Figure 2.3.1 : Interactions Inside the Logic Component for the delete 1
Command
Figure 2.4.1 : Structure of the Model Component
API : Model.java
The Model
,
-
stores a
UserPref
object that represents the user’s preferences. -
stores the Address Book data.
-
exposes an unmodifiable
ObservableList<ReadOnlyPerson>
that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. -
does not depend on any of the other three components.
Figure 2.5.1 : Structure of the Storage Component
API : Storage.java
The Storage
component,
-
can save
UserPref
objects in json format and read it back. -
can save the Address Book data in xml format and read it back.
This section describes some noteworthy details on how certain features are implemented.
The undo/redo mechanism is facilitated by an UndoRedoStack
, which resides inside LogicManager
. It supports undoing and redoing of commands that modifies the state of the address book (e.g. add
, edit
). Such commands will inherit from UndoableCommand
.
UndoRedoStack
only deals with UndoableCommands
. Commands that cannot be undone will inherit from Command
instead. The following diagram shows the inheritance diagram for commands:
As you can see from the diagram, UndoableCommand
adds an extra layer between the abstract Command
class and concrete commands that can be undone, such as the DeleteCommand
. Note that extra tasks need to be done when executing a command in an undoable way, such as saving the state of the address book before execution. UndoableCommand
contains the high-level algorithm for those extra tasks while the child classes implements the details of how to execute the specific command. Note that this technique of putting the high-level algorithm in the parent class and lower-level steps of the algorithm in child classes is also known as the template pattern.
Commands that are not undoable are implemented this way:
public class ListCommand extends Command {
@Override
public CommandResult execute() {
// ... list logic ...
}
}
With the extra layer, the commands that are undoable are implemented this way:
public abstract class UndoableCommand extends Command {
@Override
public CommandResult execute() {
// ... undo logic ...
executeUndoableCommand();
}
}
public class DeleteCommand extends UndoableCommand {
@Override
public CommandResult executeUndoableCommand() {
// ... delete logic ...
}
}
Suppose that the user has just launched the application. The UndoRedoStack
will be empty at the beginning.
The user executes a new UndoableCommand
, delete 5
, to delete the 5th person in the address book. The current state of the address book is saved before the delete 5
command executes. The delete 5
command will then be pushed onto the undoStack
(the current state is saved together with the command).
As the user continues to use the program, more commands are added into the undoStack
. For example, the user may execute add n/David …
to add a new person.
ℹ️
|
If a command fails its execution, it will not be pushed to the UndoRedoStack at all.
|
The user now decides that adding the person was a mistake, and decides to undo that action using undo
.
We will pop the most recent command out of the undoStack
and push it back to the redoStack
. We will restore the address book to the state before the add
command executed.
ℹ️
|
If the undoStack is empty, then there are no other commands left to be undone, and an Exception will be thrown when popping the undoStack .
|
The following sequence diagram shows how the undo operation works:
The redo does the exact opposite (pops from redoStack
, push to undoStack
, and restores the address book to the state after the command is executed).
ℹ️
|
If the redoStack is empty, then there are no other commands left to be redone, and an Exception will be thrown when popping the redoStack .
|
The user now decides to execute a new command, clear
. As before, clear
will be pushed into the undoStack
. This time the redoStack
is no longer empty. It will be purged as it no longer make sense to redo the add n/David
command (this is the behavior that most modern desktop applications follow).
Commands that are not undoable are not added into the undoStack
. For example, list
, which inherits from Command
rather than UndoableCommand
, will not be added after execution:
The following activity diagram summarize what happens inside the UndoRedoStack
when a user executes a new command:
Aspect: Implementation of UndoableCommand
Alternative 1 (current choice): Add a new abstract method executeUndoableCommand()
Pros: We will not lose any undone/redone functionality as it is now part of the default behaviour. Classes that deal with Command
do not have to know that executeUndoableCommand()
exist.
Cons: Hard for new developers to understand the template pattern.
Alternative 2: Just override execute()
Pros: Does not involve the template pattern, easier for new developers to understand.
Cons: Classes that inherit from UndoableCommand
must remember to call super.execute()
, or lose the ability to undo/redo.
Aspect: How undo & redo executes
Alternative 1 (current choice): Saves the entire address book.
Pros: Easy to implement.
Cons: May have performance issues in terms of memory usage.
Alternative 2: Individual command knows how to undo/redo by itself.
Pros: Will use less memory (e.g. for delete
, just save the person being deleted).
Cons: We must ensure that the implementation of each individual command are correct.
Aspect: Type of commands that can be undone/redone
Alternative 1 (current choice): Only include commands that modifies the address book (add
, clear
, edit
).
Pros: We only revert changes that are hard to change back (the view can easily be re-modified as no data are lost).
Cons: User might think that undo also applies when the list is modified (undoing filtering for example), only to realize that it does not do that, after executing undo
.
Alternative 2: Include all commands.
Pros: Might be more intuitive for the user.
Cons: User have no way of skipping such commands if he or she just want to reset the state of the address book and not the view.
Additional Info: See our discussion here.
Aspect: Data structure to support the undo/redo commands
Alternative 1 (current choice): Use separate stack for undo and redo
Pros: Easy to understand for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project.
Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both HistoryManager
and UndoRedoStack
.
Alternative 2: Use HistoryManager
for undo/redo
Pros: We do not need to maintain a separate stack, and just reuse what is already in the codebase.
Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as HistoryManager
now needs to do two different things.
We are using java.util.logging
package for logging. The LogsCenter
class is used to manage the logging levels and logging destinations.
-
The logging level can be controlled using the
logLevel
setting in the configuration file (See Configuration) -
The
Logger
for a class can be obtained usingLogsCenter.getLogger(Class)
which will log messages according to the specified logging level -
Currently log messages are output through:
Console
and to a.log
file.
Logging Levels
-
SEVERE
: Critical problem detected which may possibly cause the termination of the application -
WARNING
: Can continue, but with caution -
INFO
: Information showing the noteworthy actions by the App -
FINE
: Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size
Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: config.json
).
The finds
command is an improved version from find
command. It allows user to search using other details such as phone number, email or tag instead of just name.
The user can use this command with only ONE of the following prefixes
-
n/
: To search by name(s) -
p/
: To search by phone number(s) -
e/
: To search by email(s) -
t/
: To search by tag(s)
The following sequence diagram shows how the find operation work:
ℹ️
|
The predicate used depends on which type of detail the user is using to find.
|
The 4 predicates are as follow:
-
if search by
name
thenNameContainsKeywordsPredicate
is used -
if search by
phone number
thenPhoneContainsSpecifiedKeywordsPredicate
is used -
if search by
email
thenEmailContainsSpecifiedKeywordsPredicate
is used -
if search by
tag
thenTagContainsSpecifiedKeywordsPredicate
is used
It is implemented to search with one type of detail only so that the returned results will be relevant to that type of detail used only. i.e. if a user search for a person with phone number then only the phone numbers of the returned contacts are relevant, and other details are irrelevant to the input phone number during the search.
Alternative considered is to allow user input multiple details in each search. It may help to narrow down and shorten the list of contacts that will be returned, but it is not useful as user may only recall some details of a person only. For example:
Scenario one
-
Contact 1
: NameJohn Tan
and phone number12345678
-
Contact 2
: NameJohn Doe
and phone number12349875
-
Contact 3
: NameAmy Chan
and phone number98765432
-
User wants to find
John Tan
but do not recall surname and key inJohn
only -
User cannot recall the number and key in a random number
43567823
-
There will be no results returned in this scenario as input phone number does not match the phone numbers in
Contact 1
andContact 2
that containsJohn
Scenario two
-
Contact 1
: NameJohn Tan
and phone number12345678
-
User wants to find
John Tan
and key inJohn Tan
-
User cannot recall the number and key in a random number
43567823
-
There will be no results returned in this scenario as input phone number does not match the phone number in the
Contact 1
although the name matches exactly.
From the two scenarios, we know that unless the user knows the exact details (i.e. full name, exact phone number, exact email and etc) otherwise finds
command with multiple details input is practically not useful as no results will be returned.
Aspect: Finding person with other details.
Alternative 1 (current choice): Able to search with other details but only one type of detail for each search
Pros: Easier to be implemented when only one type of detail is used.
Cons: Repeating functions for different details.
Alternative 2: Able to find with multiple details.
Pros: Lesser repeated functions is possible.
Cons: Harder to implement and increased complexity may affect efficiency.
Any person that has important
tag will be filtered and then insert to the top of the list.
It is implemented to check whether any person in addressbook has important
tag each time add
or list
command is executed
@Override
public void filterImportantTag() throws PersonNotFoundException, DuplicatePersonException {
ArrayList<ReadOnlyPerson> notImportantPersons = new ArrayList<ReadOnlyPerson>();
ArrayList<ReadOnlyPerson> importantPersons = new ArrayList<ReadOnlyPerson>();
for (int i = 0; i < addressBook.getPersonList().size(); i++) {
// ...Check through and filter all persons in addressbook with important tag to importantPersons list...
}
/**
* If any tags in addressbook contains the {@code keyword}
* then proceed to insert the contact(s) in {@code importantPersons} to the top of the addressbook
*/
if (importantPersons.size() != 0) {
// ...Perform logic to insert persons with important tag to the top...
}
}
Aspect: Perform insertion of persons with important tag to the top quickly.
Alternative 1 (current choice): Filter person with important
tag to a list and those without to another list then merge the lists together.
Pros: Easy to implement and works well when there are not a lot of persons.
Cons: Time complexity is O(n2) hence slows down as more persons are being added over time.
Alternative 2: Create additional addressbook that stores only important contacts and execute merge only when a new person is added to the addressbook.
Pros: Able to achieve O(n) time complexity.
Cons: Additional addressbook is redundant and takes up memory space.
Persons stored in the addressbook will be sorted in ascending alphabetical order based on their name.
Persons in the addressbook will be sorted each time the user execute add
or list
command.
Sorting is achieved by using java Collection.sort() method with a specified NameComparator.
public class NameComparator implements Comparator <ReadOnlyPerson> {
@Override
public int compare(ReadOnlyPerson p1, ReadOnlyPerson p2) {
return p1.getName().fullName.compareToIgnoreCase(p2.getName().fullName);
}
}
The NameComparator compares two names and ignore their case.
The following sequence diagram shows how the add and sort operations work together:
ℹ️
|
Executing list command calls sortAllPersons() and filterImportantTag().
|
Aspect: Sort the persons in the list fast.
Alternative 1 (current choice): Use java Collection.sort() which is a merge sort algorithm.
Pros: Works well with few persons in the addressbook and merge sort algorithm is stable.
Cons: Time complexity is nlog(n) hence sorting time increases as more people are being added over time.
Alternative 2: Implement insertion sort algorithm.
Pros: Able to achieve O(n) time complexity which is the fastest.
Cons: Addressbook has to be almost sorted to achieved O(n) time complexity, otherwise can result in O(n2).
Only name and phone number are the required fields.
Program will handle and create default objects for all other fields that are not fulfilled by user.
The function below is the code to create objects with default values when empty field exists.
public static Optional <String> getDetails(Optional <String> value, Prefix prefix) throws ParseException {
if (!value.isPresent()) {
if (prefix.equals(PREFIX_BIRTHDAY)) {
return value.ofNullable("00/00/0000");
} else if (prefix.equals(PREFIX_EMAIL)) {
return value.ofNullable("No email");
} else if (prefix.equals(PREFIX_ADDRESS)) {
return value.ofNullable("No address");
} else if (prefix.equals(PREFIX_REMARK)) {
return value.ofNullable("No remark");
}
}
return value;
}
Enhanced feature to allow unique colored tags to persist after the program exits without having to save color data on external files.
Full Code:
private static String getColorForTag(String tagValue) {
if (!tagColors.containsKey(tagValue)) {
int multiplier = 1;
int asciiSum = (tagValue.hashCode() > 1) ? tagValue.hashCode() : tagValue.hashCode() * -1;
int colorRed = asciiSum % 256;
int colorGreen = (asciiSum / 2) % 256;
int colorBlue = (asciiSum / 3) % 256;
while ((colorRed + colorGreen + colorBlue) > 700) {
asciiSum = (asciiSum / multiplier) * ++multiplier;
colorRed = asciiSum % 256;
colorGreen = (asciiSum / 2) % 256;
colorBlue = (asciiSum / 3) % 256;
}
String colorString = String.format("#%02x%02x%02x", colorRed, colorGreen, colorBlue);
tagColors.put(tagValue, colorString);
}
return tagColors.get(tagValue);
}
Java’s hashcode()
method from String library will be used to obtain a unique 32-bit integer hash value of the tag String. We first obtain the hashcode and ensure it is a positive value.
Function getColorForTag(String tagValue) is supposedly implemented in the PersonCard class, as expected from suggestions on developer guide UI component.
(Note: Identical strings will result in the same hashcode value)
int asciiSum = (tagValue.hashCode() > 1) ? tagValue.hashCode() : tagValue.hashCode() * -1;
We then do a separate division of each color and modulus it by 256 to ensure that it will stay within the RGB limit of 0 - 255.
int colorRed = asciiSum % 256;
int colorGreen = (asciiSum / 2) % 256;
int colorBlue = (asciiSum / 3) % 256;
To ensure that colors stays within visible range, we do a check if sum of RGB is above 700. If it is, it is likely that the color generated is too bright and would not be visible with the white font, hence regenerate the color again. We can use an incremental multiplier to regenerate another unique hashcode from the original hashcode. However, to prevent the numbers form getting exponentially large and exceeding the 32-bit sized integer, we shall first divide it by the previous multiplier. It is save to assume that chances of collision with other hashcodes is extremely low since we are using extremely large numbers.
while ((colorRed + colorGreen + colorBlue) > 700) {
asciiSum = (asciiSum / multiplier) * ++multiplier;
colorRed = asciiSum % 256;
colorGreen = (asciiSum / 2) % 256;
colorBlue = (asciiSum / 3) % 256;
}
Finally, we format the RBG values into hexadecimal format with a hex symbol in front to conform with conventional CSS color styling before adding it into the color tag.
Aspect: Generating of colors for colorTag
.
Alternative 1 (current choice): Generate unique color based on tag string.
Pros: Unique tags will always have unique colors.
Cons: Hard for new developers to understand the color code generation.
Alternative 2: Create a static list of limited colors and randomly retrieve colors from there.
Pros: Does not involve complex code generation, easier for new developers to understand.
Cons: Tag colors renew whenever program restarts.
Aspect: Saving colors retain color persistence after program shuts down.
Alternative 1 (current choice): Morph in-built hashcode()
function output to obtain RBG colors.
Pros: Color persistence without the need to save color details onto offline files.
Cons: Chances of certain tags resulting in generating very similar RGB colors.
Alternative 2: Save chosen tag colors onto external file.
Pros: Hard for new developers to understand how colors are retained.
Cons: Must create additional file and include additional unnecessary codes for read/write.
The Google map mechanism resides in a GmapCommand
which also inherits from the Command
object.
Figure 3.9.0.1 : GmapCommand object class diagram
There are two ways the user can utilize the Google map feature, first by entering the command into CommandBox or selecting the Google Map option from the dropdown menu on each PersonCard
panel.
The GmapCommand
object sequence diagram can be seen below:
Figure 3.9.1.1 : GmapCommand parser sequence diagram
As we can see, GmapCommand
object is created after input has been validated from the AddressBookParser
.
After initialization, GmapCommand
will post a DisplayGmapEvent
event while returning a command success or command failed message in result and return it to the LogicManager for GUI display.
The DisplayGmapEvent
object contains information regarding the index of person in the addressbook.
Address data of a person can then be retrieved later using this index.
Figure 3.9.1.2 : GmapCommand execution sequence diagram
Event handling of DisplayGmapEvent
is done on the BrowserPanel
that subsequently loads its loadMapPage() function.
GmapCommand
object has double constructor that takes in either index-based or a predicate containing names to be searched.
public GmapCommand(Index targetIndex) {
this.usingIndex = true;
this.targetIndex = targetIndex;
}
public GmapCommand(NameConsistsKeywordsPredicate predicate) {
this.usingIndex = false;
this.predicate = predicate;
}
Command execution residing in execute() will then attempt to validate the given index if it exists or returning the first index of a list of persons that matches all the predicate that the user has indicated.
Finally, DisplayGmapEvent will be raised with this index in its parameter.
EventsCenter.getInstance().post(new DisplayGmapEvent(targetIndex));
The second way is to select the Google Map option under the dropdown list on the GUI. Each PersonCard
has its own handler which will automatically raise a DisplayGmapEvent with the PersonCard
index as parameter.
public void handleGoogleMap() {
raise(new DisplayGmapEvent(Index.fromOneBased(this.displayedIndex)));
}
Figure 3.9.2.1 : GmapCommand GUI sequence diagram
Since the GUI already has index tagged on every PersonCardPanel, there is no need for input validation.
Hence, the event can be raised directly and be handled in the BrowserPanel
similar to Method 1.
Aspect: Loading of Google Map data.
Alternative 1 (current choice): Loading a modified URL into WebView
.
Pros: Much lesser codes needed, very easy for new developers to understand.
Cons: Lacks flexibility in utilizing Google’s map feature.
Alternative 2: Use Google’s Java client libraries.
Pros: Allows much more flexibility and use directions, places and distance features.
Cons: Currently do not need all these extra features. Integrating external libraries induces unnecessary overhead and is hard for new developers to understand the code.
This feature can be used from both the CLI and GUI.
Similar to the Google Map mechanism, the ThemeCommand
object created when using the CLI is also a subclass of Command
object.
Refer to Figure 3.10.0.1
The creation of ThemeCommand
object is also similar to most Command
classes.
Figure 3.10.1.1 : ThemeCommand parser sequence diagram
ThemeCommand
is created after AddressBookParser
validation is successful.
Figure 3.10.1.2 : ThemeCommand execution sequence diagram
Validation within the execute() function will check for valid theme index or name.
Once this validation is successful, a ChangeThemeEvent
event will be raised to EventsCenter
.
@Override
public CommandResult execute() throws CommandException {
// Theme name or index validation code
EventsCenter.getInstance().post(new ChangeThemeEvent(targetIndex));
return new CommandResult(String.format(MESSAGE_THEME_CHANGE_SUCCESS,
UiPart.getThemeNameByIndex(this.targetIndex.getZeroBased())));
}
Event handling will then be done at MainWindow
object class.
private void handleChangeThemeEvent(ChangeThemeEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
setTheme(THEME_FILE_FOLDER + THEME_LIST_DIR.get(event.targetIndex));
}
The second method of utilizing the theme feature is from the GUI. Each buttons from the menu toolbar is tied to its own theme url.
For example:
@FXML
public void handleThemeModenaYoB() {
setTheme(THEME_FILE_FOLDER + THEME_CSS_MODENA_YELLOWONBLACK);
}
The handling of theme buttons from Menu toolbar directly calls the setTheme() function.
The initial default web page displayed in BrowserPanel
is a blank default.html page that uses a static darktheme CSS file for its styles.
Changing of styles using Java 8 API by adding external stylesheet only changes the GUI for Java 8’s components.
The CSS styles for default.html will continue to reflect darktheme styles.
Hence, default.html file was modified to allow reading of parameters to indicate which themes are currently used, and update its local CSS file accordingly.
<script language="javascript">
<!-- Code to retrieve theme css URI from parameters -->
<!-- On page load, extract selected theme from parameter in the URL and edit respective css file -->
window.onload = function(e){
var theme = getParameterByName('theme');
if (theme) {
var oldlink = document.getElementsByTagName("link").item(0);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", theme);
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
}
</script>
With this in place, whenever there’s a change of themes, the default.html page will be reloaded with theme information supplied in its URL parameters.
ℹ️
|
Disclaimer: Stylesheets and images of available themes were obtained online with slight modification of the CSS file. |
Aspect: Storing of stylesheets.
Alternative 1 (current choice): Storing multiple CSS files offline and read on demand.
Pros: Easier to modify stylesheets and for new developer to understand.
Cons: Additional offline files to be stored.
Alternative 2: Creating a static set of styles in java itself.
Pros: Does not require additional offline files.
Cons: Harder to edit styles. Codes get more complicated and harder to understand, especially when there’s alot of CSS rules.
Aspect: Updating of default web page styles.
Alternative 1 (current choice): Indicating theme data with default web page parameters.
Pros: Can dynamically set web page css file to be accordance to current Java theme.
Cons: Harder for new developers to understand. Requires understanding of Javascript.
Alternative 2: Switching default web page to be transparent.
Pros: Much easier for new developers to understand.
Cons: Default web page will be made obsolete. Unable to utilize it for other improvements and features in the future.
Just like the Google Map and Theme Changing feature, the Import feature can also be used from both the CLI and GUI.
Similarly, ImportCommand
object is also a subclass of the Command
object.
ℹ️
|
Refer to Figure 3.9.0.1 for Class Diagram of ThemeCommand. |
Import feature can first be utilized using the CLI. The sequence diagram for parsing of import command input is also similar to Theme Changer Mechanism.
ℹ️
|
Refer to Figure 3.10.1.1 for Sequence Diagram of Command Parsing. |
Upon command execution after ImportCommand
has been initialized, AddressBookImportEvent
will be raised to the EventsCenter
.
Figure 3.11.1.1 : Import CLI execution sequence diagram
Event handling will then be done at the Model
component by the ModelManager
.
It will first process all records of person in the new addressbook. If the person name does not exist, it will add that person into the local addressbook.
If the person name already exist, it will check if both old and new person’s details are identical. If it is not, it will update the local copy with the new one.
Import command can also be accessed from the Menu toolbar.
ℹ️
|
Refer to UserGuide 3.9 for screenshot of using Import from Menu toolbar. |
Figure 3.11.1.1 : Import Feature GUI sequence diagram
Java 8’s FileChooser object is used to retrieve File URI from user.
File path validation will be done within the MainWindow
when handleImport() is triggered.
public void handleImport() {
try {
// Attempt to read XML file
addressBookOptional = XmlFileStorage.loadDataFromSaveFile(new File(selectedFile.getPath()));
raise(new AddressBookImportEvent(selectedFile.getPath(), addressBookOptional));
// Raise success message back to UI
cmdResult = new CommandResult(String.format(MESSAGE_IMPORT_SUCCESS, selectedFile.getPath()));
raise(new NewResultAvailableEvent(cmdResult.feedbackToUser, true));
} catch (DataConversionException e) { // Catch not well-formed XML files
cmdResult = new CommandResult(String.format(MESSAGE_INVALID_XML_FORMAT_ERROR, selectedFile.getPath()));
raise(new NewResultAvailableEvent(cmdResult.feedbackToUser, true));
} catch (IOException e) { // Catch missing files
cmdResult = new CommandResult(String.format(MESSAGE_INVALID_IMPORT_FILE_ERROR, selectedFile.getPath()));
raise(new NewResultAvailableEvent(cmdResult.feedbackToUser, true));
}
}
To validate the xml file, it will first attempt to read its content.
Non well-formed documents or file not found will be caught similar to Method 1.
Results will then be created CommandResult
and be wrapped with NewResultAvailableEvent
objects before being raised.
NewResultAvailableEvent
will then be returned to ResultDiplay
class for GUI update of action outcome.
Aspect: Modes of import.
Alternative 1 (current choice): Append new person and update existing ones.
Pros: Gives flexibility replacing entire addressbook or appending existing addressbook.
Cons: Codes slightly more complex.
Alternative 2: Replace entire addressbook with new one.
Pros: Codes are more simple and easier for new developer to understand.
Cons: Does not give the user option to append or replace existing addressbook.
The birthday
command is an improved version from add
command. It allows user to add using with as phone number, birthday, email or tag.
The user can use this command with 'b/dd/mm/yyyy'
public static final String BIRTHDAY_VALIDATION_REGEX = "\\d\\d/\\d\\d/\\d\\d\\d\\d";
public static boolean isValidBirthday(String test) {
return test.matches(BIRTHDAY_VALIDATION_REGEX);
}
public Birthday(String birthday) throws IllegalValueException {
String trimmedBirthday = (birthday != null) ? birthday : "01/01/1991";
if (isValidBirthday(trimmedBirthday) && !birthday.equals("No birthday")) {
String birthdayNew = trimmedBirthday.replaceAll("[/]", "");
isValidBirthdayValue(birthdayNew);
if (birthdayNew.equals(NO_BIRTHDAY_DEFAULT)) {
this.value = "No birthday";
} else {
this.value = trimmedBirthday;
}
} else if (birthday.equals("No birthday")) {
this.value = "No birthday";
} else {
throw new IllegalValueException(MESSAGE_BIRTHDAY_CONSTRAINTS);
}
}
Person (s) with empty birthday filed will be showing "No birthday".
The adding photo
is an new version for our app. It allows user to add photos for the person list that been added to Mybook, by clicking the command box and go to add photo
it will sent a request to open an file from the local location, and import photo to Mybook.
The user can use size of 100X100 of file 'png','jpg' or 'jpeg'
The "remark" command is to add a remark to the person together with name, phone, address, email, birthday or tag.
There are two ways the user can utilize the remark feature, first by entering the remark command into CommandBox for existing list or adding the remark
together with the rest of the information(name, phone, address etc) when creating a new contatc list.
The RemarkCommand
object sequence diagram can be seen below:
Figure 3.14.1.1 : RemarkCommand parser sequence diagram
As we can see, RemarkCommand
object is created after input has been validated from the AddressBookParser
.
We need to delete the previos Remark in order to add in a new remark for the persons.
public RemarkCommand(Index index, Remark remark) {
requireNonNull(index);
requireNonNull(remark);
this.index = index;
this.remark = remark;
}
The second way is to add the remark using "add" command.
We can create a new list by adding name, phone, email, address, birthday, remark and tag at a same time, so the user would not forget to key in the imporant remark after creating
a new list in "add" command without the remark command.
Aspect: add a remark for existing or new person
Alternative 1 (current choice): Use "remark" command to add the remark for exisiting person.
Pros: Allows the user to key in the remark for another time instead of now that the user do not know what is their remark now
Cons: NIL
Alternative 2: Use "add" command to add remark.
Pros: Allows the user to take the important remark for the new person.
Cons: NIL.
We use asciidoc for writing documentation.
ℹ️
|
We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. |
See UsingGradle.adoc to learn how to render .adoc
files locally to preview the end result of your edits.
Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your .adoc
files in real-time.
See UsingTravis.adoc to learn how to deploy GitHub Pages using Travis.
We use Google Chrome for converting documentation to PDF format, as Chrome’s PDF engine preserves hyperlinks used in webpages.
Here are the steps to convert the project documentation files to PDF format.
-
Follow the instructions in UsingGradle.adoc to convert the AsciiDoc files in the
docs/
directory to HTML format. -
Go to your generated HTML files in the
build/docs
folder, right click on them and selectOpen with
→Google Chrome
. -
Within Chrome, click on the
Print
option in Chrome’s menu. -
Set the destination to
Save as PDF
, then clickSave
to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below.
Figure 5.6.1 : Saving documentation as PDF files in Chrome
There are three ways to run tests.
💡
|
The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. |
Method 1: Using IntelliJ JUnit test runner
-
To run all tests, right-click on the
src/test/java
folder and chooseRun 'All Tests'
-
To run a subset of tests, you can right-click on a test package, test class, or a test and choose
Run 'ABC'
Method 2: Using Gradle
-
Open a console and run the command
gradlew clean allTests
(Mac/Linux:./gradlew clean allTests
)
ℹ️
|
See UsingGradle.adoc for more info on how to run tests using Gradle. |
Method 3: Using Gradle (headless)
Thanks to the TestFX library we use, our GUI tests can be run in the headless mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running.
To run tests in headless mode, open a console and run the command gradlew clean headless allTests
(Mac/Linux: ./gradlew clean headless allTests
)
We have two types of tests:
-
GUI Tests - These are tests involving the GUI. They include,
-
System Tests that test the entire App by simulating user actions on the GUI. These are in the
systemtests
package. -
Unit tests that test the individual components. These are in
seedu.address.ui
package.
-
-
Non-GUI Tests - These are tests not involving the GUI. They include,
-
Unit tests targeting the lowest level methods/classes.
e.g.seedu.address.commons.StringUtilTest
-
Integration tests that are checking the integration of multiple code units (those code units are assumed to be working).
e.g.seedu.address.storage.StorageManagerTest
-
Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together.
e.g.seedu.address.logic.LogicManagerTest
-
See UsingGradle.adoc to learn how to use Gradle for build automation.
We use Travis CI and AppVeyor to perform Continuous Integration on our projects. See UsingTravis.adoc and UsingAppVeyor.adoc for more details.
Here are the steps to create a new release.
-
Update the version number in
MainApp.java
. -
Generate a JAR file using Gradle.
-
Tag the repo with the version number. e.g.
v0.1
-
Create a new release using GitHub and upload the JAR file you created.
A project often depends on third-party libraries. For example, Address Book depends on the Jackson library for XML parsing. Managing these dependencies can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives.
a. Include those libraries in the repo (this bloats the repo size)
b. Require developers to download those libraries manually (this creates extra work for developers)
Suggested path for new programmers:
-
First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in this section Improving a Component.
-
Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. The section Creating a new command:
remark
explains how to go about adding such a feature.
Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work).
💡
|
Do take a look at the Design: Logic Component section before attempting to modify the Logic component.
|
-
Add a shorthand equivalent alias for each of the individual commands. For example, besides typing
clear
, the user can also typec
to remove all persons in the list.-
Hints
-
Just like we store each individual command word constant
COMMAND_WORD
inside*Command.java
(e.g.FindCommand#COMMAND_WORD
,DeleteCommand#COMMAND_WORD
), you need a new constant for aliases as well (e.g.FindCommand#COMMAND_ALIAS
). -
AddressBookParser
is responsible for analyzing command words.
-
-
Solution
-
Modify the switch statement in
AddressBookParser#parseCommand(String)
such that both the proper command word and alias can be used to execute the same intended command. -
See this PR for the full solution.
-
-
💡
|
Do take a look at the Design: Model Component section before attempting to modify the Model component.
|
-
Add a
removeTag(Tag)
method. The specified tag will be removed from everyone in the address book.-
Hints
-
The
Model
API needs to be updated. -
Find out which of the existing API methods in
AddressBook
andPerson
classes can be used to implement the tag removal logic.AddressBook
allows you to update a person, andPerson
allows you to update the tags.
-
-
Solution
-
Add the implementation of
deleteTag(Tag)
method inModelManager
. Loop through each person, and remove thetag
from each person. -
See this PR for the full solution.
-
-
💡
|
Do take a look at the Design: UI Component section before attempting to modify the UI component.
|
-
Use different colors for different tags inside person cards. For example,
friends
tags can be all in grey, andcolleagues
tags can be all in red.Before
After
-
Hints
-
The tag labels are created inside
PersonCard#initTags(ReadOnlyPerson)
(new Label(tag.tagName)
). JavaFX’sLabel
class allows you to modify the style of each Label, such as changing its color. -
Use the .css attribute
-fx-background-color
to add a color.
-
-
Solution
-
See this PR for the full solution.
-
-
-
Modify
NewResultAvailableEvent
such thatResultDisplay
can show a different style on error (currently it shows the same regardless of errors).Before
After
-
Hints
-
NewResultAvailableEvent
is raised byCommandBox
which also knows whether the result is a success or failure, and is caught byResultDisplay
which is where we want to change the style to. -
Refer to
CommandBox
for an example on how to display an error.
-
-
Solution
-
Modify
NewResultAvailableEvent
's constructor so that users of the event can indicate whether an error has occurred. -
Modify
ResultDisplay#handleNewResultAvailableEvent(event)
to react to this event appropriately. -
See this PR for the full solution.
-
-
-
Modify the
StatusBarFooter
to show the total number of people in the address book.Before
After
-
Hints
-
StatusBarFooter.fxml
will need a newStatusBar
. Be sure to set theGridPane.columnIndex
properly for eachStatusBar
to avoid misalignment! -
StatusBarFooter
needs to initialize the status bar on application start, and to update it accordingly whenever the address book is updated.
-
-
Solution
-
Modify the constructor of
StatusBarFooter
to take in the number of persons when the application just started. -
Use
StatusBarFooter#handleAddressBookChangedEvent(AddressBookChangedEvent)
to update the number of persons whenever there are new changes to the addressbook. -
See this PR for the full solution.
-
-
💡
|
Do take a look at the Design: Storage Component section before attempting to modify the Storage component.
|
-
Add a new method
backupAddressBook(ReadOnlyAddressBook)
, so that the address book can be saved in a fixed temporary location.-
Hint
-
Add the API method in
AddressBookStorage
interface. -
Implement the logic in
StorageManager
class.
-
-
Solution
-
See this PR for the full solution.
-
-
By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app.
Edits the remark for a person specified in the INDEX
.
Format: remark INDEX r/[REMARK]
Examples:
-
remark 1 r/Likes to drink coffee.
Edits the remark for the first person toLikes to drink coffee.
-
remark 1 r/
Removes the remark for the first person.
Let’s start by teaching the application how to parse a remark
command. We will add the logic of remark
later.
Main:
-
Add a
RemarkCommand
that extendsUndoableCommand
. Upon execution, it should just throw anException
. -
Modify
AddressBookParser
to accept aRemarkCommand
.
Tests:
-
Add
RemarkCommandTest
that tests thatexecuteUndoableCommand()
throws an Exception. -
Add new test method to
AddressBookParserTest
, which tests that typing "remark" returns an instance ofRemarkCommand
.
Let’s teach the application to parse arguments that our remark
command will accept. E.g. 1 r/Likes to drink coffee.
Main:
-
Modify
RemarkCommand
to take in anIndex
andString
and print those two parameters as the error message. -
Add
RemarkCommandParser
that knows how to parse two arguments, one index and one with prefix 'r/'. -
Modify
AddressBookParser
to use the newly implementedRemarkCommandParser
.
Tests:
-
Modify
RemarkCommandTest
to test theRemarkCommand#equals()
method. -
Add
RemarkCommandParserTest
that tests different boundary values forRemarkCommandParser
. -
Modify
AddressBookParserTest
to test that the correct command is generated according to the user input.
Let’s add a placeholder on all our PersonCard
s to display a remark for each person later.
Main:
-
Add a
Label
with any random text insidePersonListCard.fxml
. -
Add FXML annotation in
PersonCard
to tie the variable to the actual label.
Tests:
-
Modify
PersonCardHandle
so that future tests can read the contents of the remark label.
We have to properly encapsulate the remark in our ReadOnlyPerson
class. Instead of just using a String
, let’s follow the conventional class structure that the codebase already uses by adding a Remark
class.
Main:
-
Add
Remark
to model component (you can copy fromAddress
, remove the regex and change the names accordingly). -
Modify
RemarkCommand
to now take in aRemark
instead of aString
.
Tests:
-
Add test for
Remark
, to test theRemark#equals()
method.
Now we have the Remark
class, we need to actually use it inside ReadOnlyPerson
.
Main:
-
Add three methods
setRemark(Remark)
,getRemark()
andremarkProperty()
. Be sure to implement these newly created methods inPerson
, which implements theReadOnlyPerson
interface. -
You may assume that the user will not be able to use the
add
andedit
commands to modify the remarks field (i.e. the person will be created without a remark). -
Modify
SampleDataUtil
to add remarks for the sample data (delete youraddressBook.xml
so that the application will load the sample data when you launch it.)
We now have Remark
s for Person
s, but they will be gone when we exit the application. Let’s modify XmlAdaptedPerson
to include a Remark
field so that it will be saved.
Main:
-
Add a new Xml field for
Remark
. -
Be sure to modify the logic of the constructor and
toModelType()
, which handles the conversion to/fromReadOnlyPerson
.
Tests:
-
Fix
validAddressBook.xml
such that the XML tests will not fail due to a missing<remark>
element.
Our remark label in PersonCard
is still a placeholder. Let’s bring it to life by binding it with the actual remark
field.
Main:
-
Modify
PersonCard#bindListeners()
to add the binding forremark
.
Tests:
-
Modify
GuiTestAssert#assertCardDisplaysPerson(…)
so that it will compare the remark label. -
In
PersonCardTest
, callpersonWithTags.setRemark(ALICE.getRemark())
to test that changes in thePerson
's remark correctly updates the correspondingPersonCard
.
We now have everything set up… but we still can’t modify the remarks. Let’s finish it up by adding in actual logic for our remark
command.
Main:
-
Replace the logic in
RemarkCommand#execute()
(that currently just throws anException
), with the actual logic to modify the remarks of a person.
Tests:
-
Update
RemarkCommandTest
to test that theexecute()
logic works.
See this PR for the step-by-step solution.
Priorities: High (must have) - * * *
, Medium (nice to have) - * *
, Low (unlikely to have) - *
Priority | As a … | I want to … | So that I can… |
---|---|---|---|
|
new user |
see usage instructions |
refer to instructions when I forget how to use the App |
|
user |
delete a person through a button |
delete a person more conveniently |
|
user |
have the list arranged alphabetically |
search through the list as well |
|
user |
have simpler add command |
do a quick add |
|
user |
have a address button |
view the person’s address on the browser |
|
user |
find a person through other details |
find a person in many ways |
|
user |
import data from other addressbook |
save the hassle to reenter contacts |
|
user |
list persons according to a specified tag |
to list them as a group easily |
|
user |
delete a group of people with names or similar tag |
save time from deleting one by one |
|
user |
to be able to add birthday details to contacts |
check for a person’s birthday |
|
user |
add birthday date to contact |
save more details of a person |
|
user |
hide details of a person |
just see the name of the person |
|
user |
sort contacts in UI by drag and drop |
arrange them in the order of my preference |
|
user |
choose different UI theme |
customize to my preference |
|
user |
set the style and size of the font |
customize to my preference |
|
user |
have different input languages |
input different languages to my contacts. |
|
user |
be able to open and close panels in UI |
hide them when not needed. |
|
user |
have important/favorite persons at top of the list |
access to their details faster. |
|
user |
to delete a group of people using tag |
save time from deleting one by one. |
|
user |
to see the different commands in a UI panel |
refer to the command format conveniently |
|
user |
hide private contact details by default |
minimize chance of someone else seeing them by accident |
|
user with many persons in the address book |
sort persons by name |
locate a person easily |
|
user |
be able to add photo to a contact |
identify a person quicker and distinguish people with almost similar names |
|
user |
auto suggestion list for recently used command |
save time from being repetitive |
|
user |
to change color of tag in UI |
customize to my preference |
|
user |
to synchronized addressbook with other online sources |
my addressbook is up to date |
|
user |
to group contacts together |
view them as a group |
|
user |
to be able to choose which search engine to use |
customize to my preference. |
{More to be added}
(For all use cases below, the System is the AddressBook
and the Actor is the user
, unless specified otherwise)
MSS
-
User requests to list persons
-
AddressBook shows a list of persons
-
User requests to delete a specific person in the list
-
AddressBook deletes the person
Use case ends.
Extensions
-
2a. The list is empty.
Use case ends.
-
3a. The given index is invalid.
-
3a1. AddressBook shows an error message.
Use case resumes at step 2.
-
{More to be added}
-
Should work on any mainstream OS as long as it has Java
1.8.0_60
or higher installed. -
Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage.
-
A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse.
{More to be added}
Mainstream OS
Windows, Linux, Unix, OS-X
Private contact detail
A contact detail that is not meant to be shared with others