• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.launcher3.util;
18 
19 import android.util.Log;
20 import android.view.KeyEvent;
21 import android.view.View;
22 import android.view.ViewGroup;
23 
24 import com.android.launcher3.CellLayout;
25 import com.android.launcher3.DeviceProfile;
26 import com.android.launcher3.ShortcutAndWidgetContainer;
27 import com.android.launcher3.config.FeatureFlags;
28 
29 import java.util.Arrays;
30 
31 /**
32  * Calculates the next item that a {@link KeyEvent} should change the focus to.
33  *<p>
34  * Note, this utility class calculates everything regards to icon index and its (x,y) coordinates.
35  * Currently supports:
36  * <ul>
37  *  <li> full matrix of cells that are 1x1
38  *  <li> sparse matrix of cells that are 1x1
39  *     [ 1][  ][ 2][  ]
40  *     [  ][  ][ 3][  ]
41  *     [  ][ 4][  ][  ]
42  *     [  ][ 5][ 6][ 7]
43  * </ul>
44  * *<p>
45  * For testing, one can use a BT keyboard, or use following adb command.
46  * ex. $ adb shell input keyevent 20 // KEYCODE_DPAD_LEFT
47  */
48 public class FocusLogic {
49 
50     private static final String TAG = "FocusLogic";
51     private static final boolean DEBUG = false;
52 
53     /** Item and page index related constant used by {@link #handleKeyEvent}. */
54     public static final int NOOP = -1;
55 
56     public static final int PREVIOUS_PAGE_RIGHT_COLUMN  = -2;
57     public static final int PREVIOUS_PAGE_FIRST_ITEM    = -3;
58     public static final int PREVIOUS_PAGE_LAST_ITEM     = -4;
59     public static final int PREVIOUS_PAGE_LEFT_COLUMN   = -5;
60 
61     public static final int CURRENT_PAGE_FIRST_ITEM     = -6;
62     public static final int CURRENT_PAGE_LAST_ITEM      = -7;
63 
64     public static final int NEXT_PAGE_FIRST_ITEM        = -8;
65     public static final int NEXT_PAGE_LEFT_COLUMN       = -9;
66     public static final int NEXT_PAGE_RIGHT_COLUMN      = -10;
67 
68     public static final int ALL_APPS_COLUMN = -11;
69 
70     // Matrix related constant.
71     public static final int EMPTY = -1;
72     public static final int PIVOT = 100;
73 
74     /**
75      * Returns true only if this utility class handles the key code.
76      */
shouldConsume(int keyCode)77     public static boolean shouldConsume(int keyCode) {
78         return (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ||
79                 keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN ||
80                 keyCode == KeyEvent.KEYCODE_MOVE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_END ||
81                 keyCode == KeyEvent.KEYCODE_PAGE_UP || keyCode == KeyEvent.KEYCODE_PAGE_DOWN);
82     }
83 
handleKeyEvent(int keyCode, int [][] map, int iconIdx, int pageIndex, int pageCount, boolean isRtl)84     public static int handleKeyEvent(int keyCode, int [][] map, int iconIdx, int pageIndex,
85             int pageCount, boolean isRtl) {
86 
87         int cntX = map == null ? -1 : map.length;
88         int cntY = map == null ? -1 : map[0].length;
89 
90         if (DEBUG) {
91             Log.v(TAG, String.format(
92                     "handleKeyEvent START: cntX=%d, cntY=%d, iconIdx=%d, pageIdx=%d, pageCnt=%d",
93                     cntX, cntY, iconIdx, pageIndex, pageCount));
94         }
95 
96         int newIndex = NOOP;
97         switch (keyCode) {
98             case KeyEvent.KEYCODE_DPAD_LEFT:
99                 newIndex = handleDpadHorizontal(iconIdx, cntX, cntY, map, -1 /*increment*/, isRtl);
100                 if (!isRtl && newIndex == NOOP && pageIndex > 0) {
101                     newIndex = PREVIOUS_PAGE_RIGHT_COLUMN;
102                 } else if (isRtl && newIndex == NOOP && pageIndex < pageCount - 1) {
103                     newIndex = NEXT_PAGE_RIGHT_COLUMN;
104                 }
105                 break;
106             case KeyEvent.KEYCODE_DPAD_RIGHT:
107                 newIndex = handleDpadHorizontal(iconIdx, cntX, cntY, map, 1 /*increment*/, isRtl);
108                 if (!isRtl && newIndex == NOOP && pageIndex < pageCount - 1) {
109                     newIndex = NEXT_PAGE_LEFT_COLUMN;
110                 } else if (isRtl && newIndex == NOOP && pageIndex > 0) {
111                     newIndex = PREVIOUS_PAGE_LEFT_COLUMN;
112                 }
113                 break;
114             case KeyEvent.KEYCODE_DPAD_DOWN:
115                 newIndex = handleDpadVertical(iconIdx, cntX, cntY, map, 1  /*increment*/);
116                 break;
117             case KeyEvent.KEYCODE_DPAD_UP:
118                 newIndex = handleDpadVertical(iconIdx, cntX, cntY, map, -1  /*increment*/);
119                 break;
120             case KeyEvent.KEYCODE_MOVE_HOME:
121                 newIndex = handleMoveHome();
122                 break;
123             case KeyEvent.KEYCODE_MOVE_END:
124                 newIndex = handleMoveEnd();
125                 break;
126             case KeyEvent.KEYCODE_PAGE_DOWN:
127                 newIndex = handlePageDown(pageIndex, pageCount);
128                 break;
129             case KeyEvent.KEYCODE_PAGE_UP:
130                 newIndex = handlePageUp(pageIndex);
131                 break;
132             default:
133                 break;
134         }
135 
136         if (DEBUG) {
137             Log.v(TAG, String.format("handleKeyEvent FINISH: index [%d -> %s]",
138                     iconIdx, getStringIndex(newIndex)));
139         }
140         return newIndex;
141     }
142 
143     /**
144      * Returns a matrix of size (m x n) that has been initialized with {@link #EMPTY}.
145      *
146      * @param m                 number of columns in the matrix
147      * @param n                 number of rows in the matrix
148      */
149     // TODO: get rid of dynamic matrix creation.
createFullMatrix(int m, int n)150     private static int[][] createFullMatrix(int m, int n) {
151         int[][] matrix = new int [m][n];
152 
153         for (int i=0; i < m;i++) {
154             Arrays.fill(matrix[i], EMPTY);
155         }
156         return matrix;
157     }
158 
159     /**
160      * Returns a matrix of size same as the {@link CellLayout} dimension that is initialized with the
161      * index of the child view.
162      */
163     // TODO: get rid of the dynamic matrix creation
createSparseMatrix(CellLayout layout)164     public static int[][] createSparseMatrix(CellLayout layout) {
165         ShortcutAndWidgetContainer parent = layout.getShortcutsAndWidgets();
166         final int m = layout.getCountX();
167         final int n = layout.getCountY();
168         final boolean invert = parent.invertLayoutHorizontally();
169 
170         int[][] matrix = createFullMatrix(m, n);
171 
172         // Iterate thru the children.
173         for (int i = 0; i < parent.getChildCount(); i++ ) {
174             View cell = parent.getChildAt(i);
175             if (!cell.isFocusable()) {
176                 continue;
177             }
178             int cx = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellX;
179             int cy = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellY;
180             int x = invert ? (m - cx - 1) : cx;
181             if (x < m && cy < n) { // check if view fits into matrix, else skip
182                 matrix[x][cy] = i;
183             }
184         }
185         if (DEBUG) {
186             printMatrix(matrix);
187         }
188         return matrix;
189     }
190 
191     /**
192      * Creates a sparse matrix that merges the icon and hotseat view group using the cell layout.
193      * The size of the returning matrix is [icon column count x (icon + hotseat row count)]
194      * in portrait orientation. In landscape, [(icon + hotseat) column count x (icon row count)]
195      */
196     // TODO: get rid of the dynamic matrix creation
createSparseMatrixWithHotseat( CellLayout iconLayout, CellLayout hotseatLayout, DeviceProfile dp)197     public static int[][] createSparseMatrixWithHotseat(
198             CellLayout iconLayout, CellLayout hotseatLayout, DeviceProfile dp) {
199 
200         ViewGroup iconParent = iconLayout.getShortcutsAndWidgets();
201         ViewGroup hotseatParent = hotseatLayout.getShortcutsAndWidgets();
202 
203         boolean isHotseatHorizontal = !dp.isVerticalBarLayout();
204 
205         int m, n;
206         if (isHotseatHorizontal) {
207             m = hotseatLayout.getCountX();
208             n = iconLayout.getCountY() + hotseatLayout.getCountY();
209         } else {
210             m = iconLayout.getCountX() + hotseatLayout.getCountX();
211             n = hotseatLayout.getCountY();
212         }
213         int[][] matrix = createFullMatrix(m, n);
214         // Iterate through the children of the workspace.
215         for (int i = 0; i < iconParent.getChildCount(); i++) {
216             View cell = iconParent.getChildAt(i);
217             if (!cell.isFocusable()) {
218                 continue;
219             }
220             int cx = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellX;
221             int cy = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellY;
222             matrix[cx][cy] = i;
223         }
224 
225         // Iterate thru the children of the hotseat.
226         for (int i = hotseatParent.getChildCount() - 1; i >= 0; i--) {
227             if (isHotseatHorizontal) {
228                 int cx = ((CellLayout.LayoutParams)
229                         hotseatParent.getChildAt(i).getLayoutParams()).cellX;
230                 matrix[cx][iconLayout.getCountY()] = iconParent.getChildCount() + i;
231             } else {
232                 int cy = ((CellLayout.LayoutParams)
233                         hotseatParent.getChildAt(i).getLayoutParams()).cellY;
234                 matrix[iconLayout.getCountX()][cy] = iconParent.getChildCount() + i;
235             }
236         }
237         if (DEBUG) {
238             printMatrix(matrix);
239         }
240         return matrix;
241     }
242 
243     /**
244      * Creates a sparse matrix that merges the icon of previous/next page and last column of
245      * current page. When left key is triggered on the leftmost column, sparse matrix is created
246      * that combines previous page matrix and an extra column on the right. Likewise, when right
247      * key is triggered on the rightmost column, sparse matrix is created that combines this column
248      * on the 0th column and the next page matrix.
249      *
250      * @param pivotX    x coordinate of the focused item in the current page
251      * @param pivotY    y coordinate of the focused item in the current page
252      */
253     // TODO: get rid of the dynamic matrix creation
createSparseMatrixWithPivotColumn(CellLayout iconLayout, int pivotX, int pivotY)254     public static int[][] createSparseMatrixWithPivotColumn(CellLayout iconLayout,
255             int pivotX, int pivotY) {
256 
257         ViewGroup iconParent = iconLayout.getShortcutsAndWidgets();
258 
259         int[][] matrix = createFullMatrix(iconLayout.getCountX() + 1, iconLayout.getCountY());
260 
261         // Iterate thru the children of the top parent.
262         for (int i = 0; i < iconParent.getChildCount(); i++) {
263             View cell = iconParent.getChildAt(i);
264             if (!cell.isFocusable()) {
265                 continue;
266             }
267             int cx = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellX;
268             int cy = ((CellLayout.LayoutParams) cell.getLayoutParams()).cellY;
269             if (pivotX < 0) {
270                 matrix[cx - pivotX][cy] = i;
271             } else {
272                 matrix[cx][cy] = i;
273             }
274         }
275 
276         if (pivotX < 0) {
277             matrix[0][pivotY] = PIVOT;
278         } else {
279             matrix[pivotX][pivotY] = PIVOT;
280         }
281         if (DEBUG) {
282             printMatrix(matrix);
283         }
284         return matrix;
285     }
286 
287     //
288     // key event handling methods.
289     //
290 
291     /**
292      * Calculates icon that has is closest to the horizontal axis in reference to the cur icon.
293      *
294      * Example of the check order for KEYCODE_DPAD_RIGHT:
295      * [  ][  ][13][14][15]
296      * [  ][ 6][ 8][10][12]
297      * [ X][ 1][ 2][ 3][ 4]
298      * [  ][ 5][ 7][ 9][11]
299      */
300     // TODO: add unit tests to verify all permutation.
handleDpadHorizontal(int iconIdx, int cntX, int cntY, int[][] matrix, int increment, boolean isRtl)301     private static int handleDpadHorizontal(int iconIdx, int cntX, int cntY,
302             int[][] matrix, int increment, boolean isRtl) {
303         if(matrix == null) {
304             throw new IllegalStateException("Dpad navigation requires a matrix.");
305         }
306         int newIconIndex = NOOP;
307 
308         int xPos = -1;
309         int yPos = -1;
310         // Figure out the location of the icon.
311         for (int i = 0; i < cntX; i++) {
312             for (int j = 0; j < cntY; j++) {
313                 if (matrix[i][j] == iconIdx) {
314                     xPos = i;
315                     yPos = j;
316                 }
317             }
318         }
319         if (DEBUG) {
320             Log.v(TAG, String.format("\thandleDpadHorizontal: \t[x, y]=[%d, %d] iconIndex=%d",
321                     xPos, yPos, iconIdx));
322         }
323 
324         // Rule1: check first in the horizontal direction
325         for (int x = xPos + increment; 0 <= x && x < cntX; x += increment) {
326             if ((newIconIndex = inspectMatrix(x, yPos, cntX, cntY, matrix)) != NOOP
327                     && newIconIndex != ALL_APPS_COLUMN) {
328                 return newIconIndex;
329             }
330         }
331 
332         // Rule2: check (x1-n, yPos + increment),   (x1-n, yPos - increment)
333         //              (x2-n, yPos + 2*increment), (x2-n, yPos - 2*increment)
334         int nextYPos1;
335         int nextYPos2;
336         boolean haveCrossedAllAppsColumn1 = false;
337         boolean haveCrossedAllAppsColumn2 = false;
338         int x = -1;
339         for (int coeff = 1; coeff < cntY; coeff++) {
340             nextYPos1 = yPos + coeff * increment;
341             nextYPos2 = yPos - coeff * increment;
342             x = xPos + increment * coeff;
343             if (inspectMatrix(x, nextYPos1, cntX, cntY, matrix) == ALL_APPS_COLUMN) {
344                 haveCrossedAllAppsColumn1 = true;
345             }
346             if (inspectMatrix(x, nextYPos2, cntX, cntY, matrix) == ALL_APPS_COLUMN) {
347                 haveCrossedAllAppsColumn2 = true;
348             }
349             for (; 0 <= x && x < cntX; x += increment) {
350                 int offset1 = haveCrossedAllAppsColumn1 && x < cntX - 1 ? increment : 0;
351                 newIconIndex = inspectMatrix(x, nextYPos1 + offset1, cntX, cntY, matrix);
352                 if (newIconIndex != NOOP) {
353                     return newIconIndex;
354                 }
355                 int offset2 = haveCrossedAllAppsColumn2 && x < cntX - 1 ? -increment : 0;
356                 newIconIndex = inspectMatrix(x, nextYPos2 + offset2, cntX, cntY, matrix);
357                 if (newIconIndex != NOOP) {
358                     return newIconIndex;
359                 }
360             }
361         }
362 
363         // Rule3: if switching between pages, do a brute-force search to find an item that was
364         //        missed by rules 1 and 2 (such as when going from a bottom right icon to top left)
365         if (iconIdx == PIVOT) {
366             if (isRtl) {
367                 return increment < 0 ? NEXT_PAGE_FIRST_ITEM : PREVIOUS_PAGE_LAST_ITEM;
368             }
369             return increment < 0 ? PREVIOUS_PAGE_LAST_ITEM : NEXT_PAGE_FIRST_ITEM;
370         }
371         return newIconIndex;
372     }
373 
374     /**
375      * Calculates icon that is closest to the vertical axis in reference to the current icon.
376      *
377      * Example of the check order for KEYCODE_DPAD_DOWN:
378      * [  ][  ][  ][ X][  ][  ][  ]
379      * [  ][  ][ 5][ 1][ 4][  ][  ]
380      * [  ][10][ 7][ 2][ 6][ 9][  ]
381      * [14][12][ 9][ 3][ 8][11][13]
382      */
383     // TODO: add unit tests to verify all permutation.
384     private static int handleDpadVertical(int iconIndex, int cntX, int cntY,
385             int [][] matrix, int increment) {
386         int newIconIndex = NOOP;
387         if(matrix == null) {
388             throw new IllegalStateException("Dpad navigation requires a matrix.");
389         }
390 
391         int xPos = -1;
392         int yPos = -1;
393         // Figure out the location of the icon.
394         for (int i = 0; i< cntX; i++) {
395             for (int j = 0; j < cntY; j++) {
396                 if (matrix[i][j] == iconIndex) {
397                     xPos = i;
398                     yPos = j;
399                 }
400             }
401         }
402 
403         if (DEBUG) {
404             Log.v(TAG, String.format("\thandleDpadVertical: \t[x, y]=[%d, %d] iconIndex=%d",
405                     xPos, yPos, iconIndex));
406         }
407 
408         // Rule1: check first in the dpad direction
409         for (int y = yPos + increment; 0 <= y && y <cntY && 0 <= y; y += increment) {
410             if ((newIconIndex = inspectMatrix(xPos, y, cntX, cntY, matrix)) != NOOP
411                     && newIconIndex != ALL_APPS_COLUMN) {
412                 return newIconIndex;
413             }
414         }
415 
416         // Rule2: check (xPos + increment, y_(1-n)),   (xPos - increment, y_(1-n))
417         //              (xPos + 2*increment, y_(2-n))), (xPos - 2*increment, y_(2-n))
418         int nextXPos1;
419         int nextXPos2;
420         boolean haveCrossedAllAppsColumn1 = false;
421         boolean haveCrossedAllAppsColumn2 = false;
422         int y = -1;
423         for (int coeff = 1; coeff < cntX; coeff++) {
424             nextXPos1 = xPos + coeff * increment;
425             nextXPos2 = xPos - coeff * increment;
426             y = yPos + increment * coeff;
427             if (inspectMatrix(nextXPos1, y, cntX, cntY, matrix) == ALL_APPS_COLUMN) {
428                 haveCrossedAllAppsColumn1 = true;
429             }
430             if (inspectMatrix(nextXPos2, y, cntX, cntY, matrix) == ALL_APPS_COLUMN) {
431                 haveCrossedAllAppsColumn2 = true;
432             }
433             for (; 0 <= y && y < cntY; y = y + increment) {
434                 int offset1 = haveCrossedAllAppsColumn1 && y < cntY - 1 ? increment : 0;
435                 newIconIndex = inspectMatrix(nextXPos1 + offset1, y, cntX, cntY, matrix);
436                 if (newIconIndex != NOOP) {
437                     return newIconIndex;
438                 }
439                 int offset2 = haveCrossedAllAppsColumn2 && y < cntY - 1 ? -increment : 0;
440                 newIconIndex = inspectMatrix(nextXPos2 + offset2, y, cntX, cntY, matrix);
441                 if (newIconIndex != NOOP) {
442                     return newIconIndex;
443                 }
444             }
445         }
446         return newIconIndex;
447     }
448 
449     private static int handleMoveHome() {
450         return CURRENT_PAGE_FIRST_ITEM;
451     }
452 
453     private static int handleMoveEnd() {
454         return CURRENT_PAGE_LAST_ITEM;
455     }
456 
457     private static int handlePageDown(int pageIndex, int pageCount) {
458         if (pageIndex < pageCount -1) {
459             return NEXT_PAGE_FIRST_ITEM;
460         }
461         return CURRENT_PAGE_LAST_ITEM;
462     }
463 
464     private static int handlePageUp(int pageIndex) {
465         if (pageIndex > 0) {
466             return PREVIOUS_PAGE_FIRST_ITEM;
467         } else {
468             return CURRENT_PAGE_FIRST_ITEM;
469         }
470     }
471 
472     //
473     // Helper methods.
474     //
475 
476     private static boolean isValid(int xPos, int yPos, int countX, int countY) {
477         return (0 <= xPos && xPos < countX && 0 <= yPos && yPos < countY);
478     }
479 
480     private static int inspectMatrix(int x, int y, int cntX, int cntY, int[][] matrix) {
481         int newIconIndex = NOOP;
482         if (isValid(x, y, cntX, cntY)) {
483             if (matrix[x][y] != -1) {
484                 newIconIndex = matrix[x][y];
485                 if (DEBUG) {
486                     Log.v(TAG, String.format("\t\tinspect: \t[x, y]=[%d, %d] %d",
487                             x, y, matrix[x][y]));
488                 }
489                 return newIconIndex;
490             }
491         }
492         return newIconIndex;
493     }
494 
495     /**
496      * Only used for debugging.
497      */
498     private static String getStringIndex(int index) {
499         switch(index) {
500             case NOOP: return "NOOP";
501             case PREVIOUS_PAGE_FIRST_ITEM:  return "PREVIOUS_PAGE_FIRST";
502             case PREVIOUS_PAGE_LAST_ITEM:   return "PREVIOUS_PAGE_LAST";
503             case PREVIOUS_PAGE_RIGHT_COLUMN:return "PREVIOUS_PAGE_RIGHT_COLUMN";
504             case CURRENT_PAGE_FIRST_ITEM:   return "CURRENT_PAGE_FIRST";
505             case CURRENT_PAGE_LAST_ITEM:    return "CURRENT_PAGE_LAST";
506             case NEXT_PAGE_FIRST_ITEM:      return "NEXT_PAGE_FIRST";
507             case NEXT_PAGE_LEFT_COLUMN:     return "NEXT_PAGE_LEFT_COLUMN";
508             case ALL_APPS_COLUMN:           return "ALL_APPS_COLUMN";
509             default:
510                 return Integer.toString(index);
511         }
512     }
513 
514     /**
515      * Only used for debugging.
516      */
517     private static void printMatrix(int[][] matrix) {
518         Log.v(TAG, "\tprintMap:");
519         int m = matrix.length;
520         int n = matrix[0].length;
521 
522         for (int j=0; j < n; j++) {
523             String colY = "\t\t";
524             for (int i=0; i < m; i++) {
525                 colY +=  String.format("%3d",matrix[i][j]);
526             }
527             Log.v(TAG, colY);
528         }
529     }
530 
531     /**
532      * @param edgeColumn the column of the new icon. either {@link #NEXT_PAGE_LEFT_COLUMN} or
533      * {@link #NEXT_PAGE_RIGHT_COLUMN}
534      * @return the view adjacent to {@param oldView} in the {@param nextPage} of the folder.
535      */
536     public static View getAdjacentChildInNextFolderPage(
537             ShortcutAndWidgetContainer nextPage, View oldView, int edgeColumn) {
538         final int newRow = ((CellLayout.LayoutParams) oldView.getLayoutParams()).cellY;
539 
540         int column = (edgeColumn == NEXT_PAGE_LEFT_COLUMN) ^ nextPage.invertLayoutHorizontally()
541                 ? 0 : (((CellLayout) nextPage.getParent()).getCountX() - 1);
542 
543         for (; column >= 0; column--) {
544             for (int row = newRow; row >= 0; row--) {
545                 View newView = nextPage.getChildAt(column, row);
546                 if (newView != null) {
547                     return newView;
548                 }
549             }
550         }
551         return null;
552     }
553 }
554