Update lanterna, fix bugs, implement save...
[jvcard.git] / src / be / nikiroo / jvcard / tui / MainWindow.java
index 7f438d918a717792f2686d6a86379c8949d74dd2..459d1b1a4dabfea6a13dd6049c2afce3c1d95b5c 100644 (file)
@@ -1,12 +1,14 @@
 package be.nikiroo.jvcard.tui;
 
+import java.io.IOException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.LinkedList;
 import java.util.List;
 
 import be.nikiroo.jvcard.Card;
 import be.nikiroo.jvcard.Contact;
-import be.nikiroo.jvcard.i18n.Trans;
+import be.nikiroo.jvcard.Data;
 import be.nikiroo.jvcard.i18n.Trans.StringId;
 import be.nikiroo.jvcard.tui.KeyAction.Mode;
 import be.nikiroo.jvcard.tui.UiColors.Element;
@@ -29,8 +31,8 @@ import com.googlecode.lanterna.input.KeyStroke;
 import com.googlecode.lanterna.input.KeyType;
 
 /**
- * This is the main "window" of the program. It will host one
- * {@link MainContent} at any one time.
+ * This is the main "window" of the program. It can show up to one
+ * {@link MainContent} at any one time, but keeps a stack of contents.
  * 
  * @author niki
  * 
@@ -38,25 +40,37 @@ import com.googlecode.lanterna.input.KeyType;
 public class MainWindow extends BasicWindow {
        private List<KeyAction> defaultActions = new LinkedList<KeyAction>();
        private List<KeyAction> actions = new LinkedList<KeyAction>();
-       private List<MainContent> content = new LinkedList<MainContent>();
-       private boolean actionsPadded;
-       private Boolean waitForOneKeyAnswer; // true, false, (null = do not wait for
-       // an answer)
-       private String title;
+       private List<MainContent> contentStack = new LinkedList<MainContent>();
+       private boolean waitForOneKeyAnswer;
+       private KeyStroke questionKey; // key that "asked" a question, and to replay
+       // later with an answer
+       private String titleCache;
        private Panel titlePanel;
        private Panel mainPanel;
        private Panel contentPanel;
        private Panel actionPanel;
        private Panel messagePanel;
        private TextBox text;
+       private int width;
 
+       /**
+        * Create a new, empty window.
+        */
        public MainWindow() {
                this(null);
        }
 
+       /**
+        * Create a new window hosting the given content.
+        * 
+        * @param content
+        *            the content to host
+        */
        public MainWindow(MainContent content) {
                super(content == null ? "" : content.getTitle());
 
+               width = -1;
+
                setHints(Arrays.asList(Window.Hint.FULL_SCREEN,
                                Window.Hint.NO_DECORATIONS, Window.Hint.FIT_TERMINAL_WINDOW));
 
@@ -80,15 +94,14 @@ public class MainWindow extends BasicWindow {
                llayout.setSpacing(0);
                actionPanel.setLayoutManager(llayout);
 
-               llayout = new LinearLayout(Direction.VERTICAL);
-               llayout.setSpacing(0);
-               titlePanel.setLayoutManager(llayout);
+               BorderLayout blayout = new BorderLayout();
+               titlePanel.setLayoutManager(blayout);
 
                llayout = new LinearLayout(Direction.VERTICAL);
                llayout.setSpacing(0);
                messagePanel.setLayoutManager(llayout);
 
-               BorderLayout blayout = new BorderLayout();
+               blayout = new BorderLayout();
                mainPanel.setLayoutManager(blayout);
 
                blayout = new BorderLayout();
@@ -112,77 +125,266 @@ public class MainWindow extends BasicWindow {
                setComponent(mainPanel);
        }
 
+       /**
+        * "push" some content to the window stack.
+        * 
+        * @param content
+        *            the new top-of-the-stack content
+        */
        public void pushContent(MainContent content) {
                List<KeyAction> actions = null;
-               String title = null;
 
                contentPanel.removeAllComponents();
                if (content != null) {
-                       title = content.getTitle();
                        actions = content.getKeyBindings();
                        contentPanel.addComponent(content, BorderLayout.Location.CENTER);
-                       this.content.add(content);
+                       this.contentStack.add(content);
+
+                       Interactable focus = content.nextFocus(null);
+                       if (focus != null)
+                               focus.takeFocus();
                }
 
-               setTitle(title);
-               setActions(actions, true, true);
-               invalidate();
+               setTitle();
+               setActions(actions, true);
        }
 
        /**
-        * Set the application title.
+        * "pop" the latest, top-of-the-stack content from the window stack.
         * 
-        * @param title
-        *            the new title or NULL for the default title
+        * @return the removed content if any
         */
-       public void setTitle(String title) {
-               if (title == null) {
-                       title = Trans.StringId.TITLE.trans();
-               }
+       public MainContent popContent() {
+               MainContent removed = null;
+               MainContent prev = null;
+
+               MainContent content = getContent();
+               if (content != null)
+                       removed = contentStack.remove(contentStack.size() - 1);
+
+               if (contentStack.size() > 0)
+                       prev = contentStack.remove(contentStack.size() - 1);
 
-               if (!title.equals(this.title)) {
-                       super.setTitle(title);
-                       this.title = title;
+               pushContent(prev);
+
+               return removed;
+       }
+
+       /**
+        * Show the given message on screen. It will disappear at the next action.
+        * 
+        * @param mess
+        *            the message to display
+        * @param error
+        *            TRUE for an error message, FALSE for an information message
+        * 
+        * @return TRUE if changes were performed
+        */
+       public boolean setMessage(String mess, boolean error) {
+               if (mess != null || messagePanel.getChildCount() > 0) {
+                       messagePanel.removeAllComponents();
+                       if (mess != null) {
+                               Element element = (error ? UiColors.Element.LINE_MESSAGE_ERR
+                                               : UiColors.Element.LINE_MESSAGE);
+                               Label lbl = element.createLabel(" " + mess + " ");
+                               messagePanel.addComponent(lbl, LinearLayout
+                                               .createLayoutData(LinearLayout.Alignment.Center));
+                       }
+                       return true;
                }
 
-               Label lbl = new Label(title);
-               titlePanel.removeAllComponents();
+               return false;
+       }
 
-               titlePanel.addComponent(lbl, LinearLayout
-                               .createLayoutData(LinearLayout.Alignment.Center));
+       /**
+        * Show a question to the user and switch to "ask for answer" mode see
+        * {@link MainWindow#handleQuestion}. The user will be asked to enter some
+        * answer and confirm with ENTER.
+        * 
+        * @param question
+        *            the question to ask
+        * @param initial
+        *            the initial answer if any (to be edited by the user)
+        */
+       public void setQuestion(KeyStroke key, String question, String initial) {
+               setQuestion(key, question, initial, false);
+       }
+
+       /**
+        * Show a question to the user and switch to "ask for answer" mode see
+        * {@link MainWindow#handleQuestion}. The user will be asked to hit one key
+        * as an answer.
+        * 
+        * @param question
+        *            the question to ask
+        */
+       public void setQuestion(KeyStroke key, String question) {
+               setQuestion(key, question, null, true);
        }
 
        @Override
        public void draw(TextGUIGraphics graphics) {
-               setTitle(title);
-               if (!actionsPadded) {
-                       // fill with "desc" colour
-                       actionPanel.addComponent(UiColors.Element.ACTION_DESC
-                                       .createLabel(StringUtils.padString("", graphics.getSize()
-                                                       .getColumns())));
-                       actionsPadded = true;
+               int width = graphics.getSize().getColumns();
+
+               if (width != this.width) {
+                       this.width = width;
+
+                       setTitle();
+
+                       if (actions != null)
+                               setActions(new ArrayList<KeyAction>(actions), false);
                }
+
                super.draw(graphics);
        }
 
-       public MainContent popContent() {
-               MainContent removed = null;
-               MainContent prev = null;
-               if (content.size() > 0)
-                       removed = content.remove(content.size() - 1);
-               if (content.size() > 0)
-                       prev = content.remove(content.size() - 1);
-               pushContent(prev);
+       @Override
+       public void invalidate() {
+               super.invalidate();
+               for (MainContent content : contentStack) {
+                       content.invalidate();
+               }
+       }
 
-               return removed;
+       /**
+        * Show a question to the user and switch to "ask for answer" mode see
+        * {@link MainWindow#handleQuestion}.
+        * 
+        * @param question
+        *            the question to ask
+        * @param initial
+        *            the initial answer if any (to be edited by the user)
+        * @param oneKey
+        *            TRUE for a one-key answer, FALSE for a text answer validated
+        *            by ENTER
+        */
+       private void setQuestion(KeyStroke key, String question, String initial,
+                       boolean oneKey) {
+               questionKey = key;
+               waitForOneKeyAnswer = oneKey;
+
+               messagePanel.removeAllComponents();
+
+               Panel hpanel = new Panel();
+               LinearLayout llayout = new LinearLayout(Direction.HORIZONTAL);
+               llayout.setSpacing(0);
+               hpanel.setLayoutManager(llayout);
+
+               Label lbl = UiColors.Element.LINE_MESSAGE_QUESTION.createLabel(" "
+                               + question + " ");
+               text = new TextBox(new TerminalSize(width - lbl.getSize().getColumns(),
+                               1));
+               if (initial != null)
+                       text.setText(initial);
+
+               hpanel.addComponent(lbl,
+                               LinearLayout.createLayoutData(LinearLayout.Alignment.Beginning));
+               hpanel.addComponent(text,
+                               LinearLayout.createLayoutData(LinearLayout.Alignment.Fill));
+
+               messagePanel
+                               .addComponent(hpanel, LinearLayout
+                                               .createLayoutData(LinearLayout.Alignment.Beginning));
+
+               text.takeFocus();
        }
 
-       private void setActions(List<KeyAction> actions, boolean allowKeys,
-                       boolean enableDefaultactions) {
+       /**
+        * Actually set the title <b>inside</b> the window. Will also call
+        * {@link BasicWindow#setTitle} with the compuited parameters.
+        */
+       private void setTitle() {
+               String prefix = " " + Main.APPLICATION_TITLE + " (version "
+                               + Main.APPLICATION_VERSION + ")";
+
+               String title = null;
+               int count = -1;
+
+               MainContent content = getContent();
+               if (content != null) {
+                       title = content.getTitle();
+                       count = content.getCount();
+               }
+
+               if (title == null)
+                       title = "";
+
+               if (title.length() > 0) {
+                       prefix = prefix + ": ";
+               }
+
+               String countStr = "";
+               if (count > -1) {
+                       countStr = "[" + count + "]";
+               }
+
+               if (width > 0) {
+                       int padding = width - prefix.length() - title.length()
+                                       - countStr.length();
+                       if (padding > 0) {
+                               if (title.length() > 0)
+                                       title = StringUtils.padString(title, title.length()
+                                                       + padding);
+                               else
+                                       prefix = StringUtils.padString(prefix, prefix.length()
+                                                       + padding);
+                       }
+               }
+
+               String titleCache = prefix + title + count;
+               if (!titleCache.equals(this.titleCache)) {
+                       super.setTitle(prefix);
 
+                       Label lblPrefix = new Label(prefix);
+                       UiColors.Element.TITLE_MAIN.themeLabel(lblPrefix);
+
+                       Label lblTitle = null;
+                       if (title.length() > 0) {
+                               lblTitle = new Label(title);
+                               UiColors.Element.TITLE_VARIABLE.themeLabel(lblTitle);
+                       }
+
+                       Label lblCount = null;
+                       if (countStr != null) {
+                               lblCount = new Label(countStr);
+                               UiColors.Element.TITLE_COUNT.themeLabel(lblCount);
+                       }
+
+                       titlePanel.removeAllComponents();
+
+                       titlePanel.addComponent(lblPrefix, BorderLayout.Location.LEFT);
+                       if (lblTitle != null)
+                               titlePanel.addComponent(lblTitle, BorderLayout.Location.CENTER);
+                       if (lblCount != null)
+                               titlePanel.addComponent(lblCount, BorderLayout.Location.RIGHT);
+               }
+       }
+
+       /**
+        * Return the current {@link MainContent} from the stack if any.
+        * 
+        * @return the current {@link MainContent}
+        */
+       private MainContent getContent() {
+               if (contentStack.size() > 0) {
+                       return contentStack.get(contentStack.size() - 1);
+               }
+
+               return null;
+       }
+
+       /**
+        * Update the list of actions and refresh the action panel.
+        * 
+        * @param actions
+        *            the list of actions to support
+        * @param enableDefaultactions
+        *            TRUE to enable the default actions
+        */
+       private void setActions(List<KeyAction> actions,
+                       boolean enableDefaultactions) {
                this.actions.clear();
-               actionsPadded = false;
-               
+
                if (enableDefaultactions)
                        this.actions.addAll(defaultActions);
 
@@ -231,54 +433,24 @@ public class MainWindow extends BasicWindow {
 
                        actionPanel.addComponent(kPane);
                }
-       }
-
-       /**
-        * Show the given message on screen. It will disappear at the next action.
-        * 
-        * @param mess
-        *            the message to display
-        * @param error
-        *            TRUE for an error message, FALSE for an information message
-        */
-       public void setMessage(String mess, boolean error) {
-               messagePanel.removeAllComponents();
-               if (mess != null) {
-                       Element element = (error ? UiColors.Element.LINE_MESSAGE_ERR
-                                       : UiColors.Element.LINE_MESSAGE);
-                       Label lbl = element.createLabel(" " + mess + " ");
-                       messagePanel.addComponent(lbl, LinearLayout
-                                       .createLayoutData(LinearLayout.Alignment.Center));
-               }
-       }
 
-       public void setQuestion(String mess, boolean oneKey) {
-               messagePanel.removeAllComponents();
-               if (mess != null) {
-                       waitForOneKeyAnswer = oneKey;
-
-                       Panel hpanel = new Panel();
-                       LinearLayout llayout = new LinearLayout(Direction.HORIZONTAL);
-                       llayout.setSpacing(0);
-                       hpanel.setLayoutManager(llayout);
-
-                       Label lbl = UiColors.Element.LINE_MESSAGE_QUESTION.createLabel(" "
-                                       + mess + " ");
-                       text = new TextBox(new TerminalSize(getSize().getColumns()
-                                       - lbl.getSize().getColumns(), 1));
-
-                       hpanel.addComponent(lbl, LinearLayout
-                                       .createLayoutData(LinearLayout.Alignment.Beginning));
-                       hpanel.addComponent(text, LinearLayout
-                                       .createLayoutData(LinearLayout.Alignment.Fill));
-
-                       messagePanel.addComponent(hpanel, LinearLayout
-                                       .createLayoutData(LinearLayout.Alignment.Beginning));
+               // fill with "desc" colour
+               if (width > 0) {
+                       actionPanel.addComponent(UiColors.Element.ACTION_DESC
+                                       .createLabel(StringUtils.padString("", width)));
 
-                       text.takeFocus();
                }
        }
 
+       /**
+        * Handle user input when in "ask for question" mode (see
+        * {@link MainWindow#questionKey}).
+        * 
+        * @param key
+        *            the key that has been pressed by the user
+        * 
+        * @return the user's answer if done
+        */
        private String handleQuestion(KeyStroke key) {
                String answer = null;
 
@@ -295,9 +467,9 @@ public class MainWindow extends BasicWindow {
 
                if (answer != null) {
                        Interactable focus = null;
-                       if (this.content.size() > 0)
-                               // focus = content.get(0).getDefaultFocusElement();
-                               focus = content.get(0).nextFocus(null);
+                       MainContent content = getContent();
+                       if (content != null)
+                               focus = content.nextFocus(null);
 
                        focus.takeFocus();
                }
@@ -305,83 +477,183 @@ public class MainWindow extends BasicWindow {
                return answer;
        }
 
-       @Override
-       public boolean handleInput(KeyStroke key) {
+       /**
+        * Handle the input in case of "normal" (not "ask for answer") mode.
+        * 
+        * @param key
+        *            the key that was pressed
+        * @param answer
+        *            the answer given for this key
+        * 
+        * @return if the window handled the input
+        */
+       private boolean handleInput(KeyStroke key, String answer) {
                boolean handled = false;
 
-               if (waitForOneKeyAnswer != null) {
-                       String answer = handleQuestion(key);
-                       if (answer != null) {
-                               waitForOneKeyAnswer = null;
-                               setMessage("ANS: " + answer, false);
+               // reset the message pane if no answers are pending
+               if (answer == null) {
+                       if (setMessage(null, false))
+                               return true;
+               }
 
-                               handled = true;
-                       }
-               } else {
-                       setMessage(null, false);
+               for (KeyAction action : actions) {
+                       if (!action.match(key))
+                               continue;
 
-                       for (KeyAction action : actions) {
-                               if (!action.match(key))
-                                       continue;
+                       MainContent content = getContent();
+                       handled = true;
+
+                       if (action.onAction()) {
+                               Card card = action.getCard();
+                               Contact contact = action.getContact();
+                               Data data = action.getData();
+
+                               switch (action.getMode()) {
+                               case MOVE:
+                                       int x = 0;
+                                       int y = 0;
+
+                                       if (action.getKey().getKeyType() == KeyType.ArrowUp)
+                                               x = -1;
+                                       if (action.getKey().getKeyType() == KeyType.ArrowDown)
+                                               x = 1;
+                                       if (action.getKey().getKeyType() == KeyType.ArrowLeft)
+                                               y = -1;
+                                       if (action.getKey().getKeyType() == KeyType.ArrowRight)
+                                               y = 1;
+
+                                       if (content != null) {
+                                               String err = content.move(x, y);
+                                               if (err != null)
+                                                       setMessage(err, true);
+                                       }
 
-                               handled = true;
+                                       break;
+                               // mode with windows:
+                               case CONTACT_LIST:
+                                       if (card != null) {
+                                               pushContent(new ContactList(card));
+                                       }
+                                       break;
+                               case CONTACT_DETAILS:
+                                       if (contact != null) {
+                                               pushContent(new ContactDetails(contact));
+                                       }
+                                       break;
+                               // mode interpreted by MainWindow:
+                               case HELP:
+                                       // TODO
+                                       // setMessage("Help! I need somebody! Help!", false);
+                                       if (answer == null) {
+                                               setQuestion(key, "Test question?", "[initial]");
+                                       } else {
+                                               setMessage("You answered: " + answer, false);
+                                       }
 
-                               if (action.onAction()) {
-                                       switch (action.getMode()) {
-                                       case MOVE:
-                                               int x = 0;
-                                               int y = 0;
-
-                                               if (action.getKey().getKeyType() == KeyType.ArrowUp)
-                                                       x = -1;
-                                               if (action.getKey().getKeyType() == KeyType.ArrowDown)
-                                                       x = 1;
-                                               if (action.getKey().getKeyType() == KeyType.ArrowLeft)
-                                                       y = -1;
-                                               if (action.getKey().getKeyType() == KeyType.ArrowRight)
-                                                       y = 1;
-
-                                               if (content.size() > 0) {
-                                                       String err = content.get(content.size() - 1).move(
-                                                                       x, y);
-                                                       if (err != null)
-                                                               setMessage(err, true);
+                                       break;
+                               case BACK:
+                                       String warning = content.getExitWarning();
+                                       if (warning != null) {
+                                               if (answer == null) {
+                                                       setQuestion(key, warning);
+                                               } else {
+                                                       setMessage(null, false);
+                                                       if (answer.equalsIgnoreCase("y")) {
+                                                               popContent();
+                                                       }
                                                }
+                                       } else {
+                                               popContent();
+                                       }
 
-                                               break;
-                                       // mode with windows:
-                                       case CONTACT_LIST:
-                                               Card card = action.getCard();
-                                               if (card != null) {
-                                                       pushContent(new ContactList(card));
+                                       if (contentStack.size() == 0) {
+                                               close();
+                                       }
+
+                                       break;
+                               // action modes:
+                               case EDIT_DETAIL:
+                                       if (answer == null) {
+                                               if (data != null) {
+                                                       String name = data.getName();
+                                                       String value = data.getValue();
+                                                       setQuestion(key, name, value);
                                                }
-                                               break;
-                                       case CONTACT_DETAILS:
-                                               Contact contact = action.getContact();
+                                       } else {
+                                               setMessage(null, false);
+                                               data.setValue(answer);
+                                       }
+                                       break;
+                               case DELETE_CONTACT:
+                                       if (answer == null) {
                                                if (contact != null) {
-                                                       pushContent(new ContactDetails(contact));
+                                                       setQuestion(key, "Delete contact? [Y/N]");
+                                               }
+                                       } else {
+                                               setMessage(null, false);
+                                               if (answer.equalsIgnoreCase("y")) {
+                                                       if (contact.delete()) {
+                                                               content.refreshData();
+                                                               invalidate();
+                                                               setTitle();
+                                                       } else {
+                                                               setMessage("Cannot delete this contact", true);
+                                                       }
+                                               }
+                                       }
+                                       break;
+                               case SAVE_CARD:
+                                       if (answer == null) {
+                                               if (card != null) {
+                                                       setQuestion(key, "Save changes? [Y/N]");
+                                               }
+                                       } else {
+                                               setMessage(null, false);
+                                               if (answer.equalsIgnoreCase("y")) {
+                                                       boolean ok = false;
+                                                       try {
+                                                               if (card.save()) {
+                                                                       ok = true;
+                                                                       invalidate();
+                                                               }
+                                                       } catch (IOException ioe) {
+                                                               ioe.printStackTrace();
+                                                       }
+
+                                                       if (!ok) {
+                                                               setMessage("Cannot save to file", true);
+                                                       }
                                                }
-                                               break;
-                                       // mode interpreted by MainWindow:
-                                       case HELP:
-                                               // TODO
-                                               // setMessage("Help! I need somebody! Help!", false);
-                                               setQuestion("Test question?", false);
-                                               handled = true;
-                                               break;
-                                       case BACK:
-                                               popContent();
-                                               if (content.size() == 0)
-                                                       close();
-                                               break;
-                                       default:
-                                       case NONE:
-                                               break;
                                        }
+                                       break;
+                               default:
+                               case NONE:
+                                       break;
                                }
+                       }
 
-                               break;
+                       break;
+               }
+
+               return handled;
+       }
+
+       @Override
+       public boolean handleInput(KeyStroke key) {
+               boolean handled = false;
+
+               if (questionKey != null) {
+                       String answer = handleQuestion(key);
+                       if (answer != null) {
+                               handled = true;
+
+                               key = questionKey;
+                               questionKey = null;
+
+                               handleInput(key, answer);
                        }
+               } else {
+                       handled = handleInput(key, null);
                }
 
                if (!handled)