Better exception handling. Formatting. Copyright update.
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / gui / humaninput / KeyboardFocusTracker.java
1 /*
2  * Sixth 3D engine. Copyright ©2012-2018, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 3 of the GNU Lesser General Public License
6  * or later as published by the Free Software Foundation.
7  *
8  */
9
10 package eu.svjatoslav.sixth.e3d.gui.humaninput;
11
12 import eu.svjatoslav.sixth.e3d.gui.ViewContext;
13
14 import java.util.Stack;
15
16 public class KeyboardFocusTracker {
17
18     private final ViewContext viewContext;
19     WorldNavigationTracker defaultInputHandler = new WorldNavigationTracker();
20     Stack<UserInputHandler> inputHandlers = new Stack<>();
21     private UserInputHandler currentUserInputHandler;
22
23     public KeyboardFocusTracker(final ViewContext viewContext) {
24         this.viewContext = viewContext;
25         setFocusOwner(defaultInputHandler);
26     }
27
28     public UserInputHandler getCurrentFocusOwner() {
29         return currentUserInputHandler;
30     }
31
32     public void popFocusOwner() {
33         if (currentUserInputHandler == null)
34             return;
35
36         if (inputHandlers.isEmpty())
37             return;
38
39         currentUserInputHandler.focusLost(viewContext);
40
41         currentUserInputHandler = inputHandlers.pop();
42
43         currentUserInputHandler.focusReceived(viewContext);
44     }
45
46     public void setFocusOwner(final UserInputHandler inputHandler) {
47         if (currentUserInputHandler == inputHandler)
48             return;
49
50         if (currentUserInputHandler != null) {
51             currentUserInputHandler.focusLost(viewContext);
52             inputHandlers.push(currentUserInputHandler);
53         }
54
55         currentUserInputHandler = inputHandler;
56
57         currentUserInputHandler.focusReceived(viewContext);
58     }
59 }