summaryrefslogtreecommitdiff
path: root/android/source/src/java/org/libreoffice/InvalidationHandler.java
blob: 8aec88ca3c429ddd82b0a777fc29b7434927be70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package org.libreoffice;

import android.content.Intent;
import android.graphics.PointF;
import android.graphics.RectF;
import android.net.Uri;
import android.util.Log;

import org.libreoffice.canvas.SelectionHandle;
import org.libreoffice.kit.Document;
import org.libreoffice.overlay.DocumentOverlay;
import org.mozilla.gecko.gfx.GeckoLayerClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Parses (interprets) and handles invalidation messages from LibreOffice.
 */
public class InvalidationHandler implements Document.MessageCallback {
    private static String LOGTAG = InvalidationHandler.class.getSimpleName();
    private final DocumentOverlay mDocumentOverlay;
    private final GeckoLayerClient mLayerClient;
    private OverlayState mState;
    private boolean mKeyEvent = false;

    public InvalidationHandler(LibreOfficeMainActivity mainActivity) {
        mDocumentOverlay = mainActivity.getDocumentOverlay();
        mLayerClient = LibreOfficeMainActivity.getLayerClient();
        mState = OverlayState.NONE;
    }

    /**
     * Processes callback message
     *
     * @param messageID - ID of the message
     * @param payload   - additional invalidation message payload
     */
    @Override
    public void messageRetrieved(int messageID, String payload) {
        if (!LOKitShell.isEditingEnabled()) {
            // enable handling of hyperlinks even in the Viewer
            if (messageID != Document.CALLBACK_INVALIDATE_TILES && messageID != Document.CALLBACK_HYPERLINK_CLICKED)
                return;
        }
        switch (messageID) {
            case Document.CALLBACK_INVALIDATE_TILES:
                invalidateTiles(payload);
                break;
            case Document.CALLBACK_INVALIDATE_VISIBLE_CURSOR:
                invalidateCursor(payload);
                break;
            case Document.CALLBACK_TEXT_SELECTION:
                textSelection(payload);
                break;
            case Document.CALLBACK_TEXT_SELECTION_START:
                textSelectionStart(payload);
                break;
            case Document.CALLBACK_TEXT_SELECTION_END:
                textSelectionEnd(payload);
                break;
            case Document.CALLBACK_CURSOR_VISIBLE:
                cursorVisibility(payload);
                break;
            case Document.CALLBACK_GRAPHIC_SELECTION:
                graphicSelection(payload);
                break;
            case Document.CALLBACK_HYPERLINK_CLICKED:
                if (!payload.startsWith("http://") && !payload.startsWith("https://")) {
                    payload = "http://" + payload;
                }
                Intent urlIntent = new Intent(Intent.ACTION_VIEW);
                urlIntent.setData(Uri.parse(payload));
                LibreOfficeMainActivity.mAppContext.startActivity(urlIntent);
                break;
            case Document.CALLBACK_STATE_CHANGED:
                stateChanged(payload);
                break;
            default:
                Log.d(LOGTAG, "LOK_CALLBACK uncatched: " + messageID + " : " + payload);
        }
    }

    private void stateChanged(String payload) {
        String[] parts = payload.split("=");
        if (parts.length < 2) {
            Log.e(LOGTAG, "LOK_CALLBACK_STATE_CHANGED unexpected payload: " + payload);
            return;
        }
        boolean pressed = Boolean.parseBoolean(parts[1]);
        if (parts[0].equals(".uno:Bold")) {
            LOKitShell.getToolbarController().onToggleStateChanged(Document.BOLD, pressed);
        } else if (parts[0].equals(".uno:Italic")) {
            LOKitShell.getToolbarController().onToggleStateChanged(Document.ITALIC, pressed);
        } else if (parts[0].equals(".uno:Underline")) {
            LOKitShell.getToolbarController().onToggleStateChanged(Document.UNDERLINE, pressed);
        } else if (parts[0].equals(".uno:Strikeout")) {
            LOKitShell.getToolbarController().onToggleStateChanged(Document.STRIKEOUT, pressed);
        } else {
            Log.d(LOGTAG, "LOK_CALLBACK_STATE_CHANGED type uncatched: " + payload);
        }
    }

    /**
     * Parses the payload text with rectangle coordinates and converts to rectangle in pixel coordinates
     *
     * @param payload - invalidation message payload text
     * @return rectangle in pixel coordinates
     */
    private RectF convertPayloadToRectangle(String payload) {
        String payloadWithoutWhitespace = payload.replaceAll("\\s", ""); // remove all whitespace from the string

        if (payloadWithoutWhitespace.isEmpty() || payloadWithoutWhitespace.equals("EMPTY")) {
            return null;
        }

        String[] coordinates = payloadWithoutWhitespace.split(",");

        if (coordinates.length != 4) {
            return null;
        }

        int x = Integer.decode(coordinates[0]);
        int y = Integer.decode(coordinates[1]);
        int width = Integer.decode(coordinates[2]);
        int height = Integer.decode(coordinates[3]);

        float dpi = LOKitShell.getDpi();

        return new RectF(
                LOKitTileProvider.twipToPixel(x, dpi),
                LOKitTileProvider.twipToPixel(y, dpi),
                LOKitTileProvider.twipToPixel(x + width, dpi),
                LOKitTileProvider.twipToPixel(y + height, dpi)
        );
    }

    /**
     * Parses the payload text with more rectangles (separated by ';') and converts to a list of rectangles.
     *
     * @param payload - invalidation message payload text
     * @return list of rectangles
     */
    private List<RectF> convertPayloadToRectangles(String payload) {
        List<RectF> rectangles = new ArrayList<RectF>();
        String[] rectangleArray = payload.split(";");

        for (String coordinates : rectangleArray) {
            RectF rectangle = convertPayloadToRectangle(coordinates);
            if (rectangle != null) {
                rectangles.add(rectangle);
            }

        }

        return rectangles;
    }

    /**
     * Handles the tile invalidation message
     *
     * @param payload
     */
    private void invalidateTiles(String payload) {
        RectF rectangle = convertPayloadToRectangle(payload);
        if (rectangle != null) {
            LOKitShell.sendTileInvalidationRequest(rectangle);
        }
    }

    /**
     * Handles the cursor invalidation message
     *
     * @param payload
     */
    private synchronized void invalidateCursor(String payload) {
        RectF cursorRectangle = convertPayloadToRectangle(payload);
        if (cursorRectangle != null) {
            mDocumentOverlay.positionCursor(cursorRectangle);
            mDocumentOverlay.positionHandle(SelectionHandle.HandleType.MIDDLE, cursorRectangle);

            if (mState == OverlayState.TRANSITION || mState == OverlayState.CURSOR) {
                changeStateTo(OverlayState.CURSOR);
            }

            if (mKeyEvent) {
                moveViewportToMakeCursorVisible(cursorRectangle);
                mKeyEvent = false;
            }
        }
    }

    /**
     * Move the viewport to show the cursor. The cursor will appear at the
     * viewport position depending on where the cursor is relative to the
     * viewport (either cursor is above, below, on left or right).
     *
     * @param cursorRectangle - cursor position on the document
     */
    public void moveViewportToMakeCursorVisible(RectF cursorRectangle) {
        RectF moveToRect = mLayerClient.getViewportMetrics().getCssViewport();
        if (moveToRect.contains(cursorRectangle)) {
            return;
        }

        float newLeft = moveToRect.left;
        float newTop = moveToRect.top;

        if (cursorRectangle.right < moveToRect.left || cursorRectangle.left < moveToRect.left) {
            newLeft = cursorRectangle.left - (moveToRect.width() * 0.1f);
        } else if (cursorRectangle.right > moveToRect.right || cursorRectangle.left > moveToRect.right) {
            newLeft = cursorRectangle.right - (moveToRect.width() * 0.9f);
        }

        if (cursorRectangle.top < moveToRect.top || cursorRectangle.bottom < moveToRect.top) {
            newTop = cursorRectangle.top - (moveToRect.height() * 0.1f);
        } else if (cursorRectangle.bottom > moveToRect.bottom || cursorRectangle.top > moveToRect.bottom) {
            newTop = cursorRectangle.bottom - (moveToRect.height() / 2.0f);
        }

        LOKitShell.moveViewportTo(new PointF(newLeft, newTop), null);
    }

    /**
     * Handles the text selection start message
     *
     * @param payload
     */
    private synchronized void textSelectionStart(String payload) {
        RectF selectionRect = convertPayloadToRectangle(payload);
        if (selectionRect != null) {
            mDocumentOverlay.positionHandle(SelectionHandle.HandleType.START, selectionRect);
        }
    }

    /**
     * Handles the text selection end message
     *
     * @param payload
     */
    private synchronized void textSelectionEnd(String payload) {
        RectF selectionRect = convertPayloadToRectangle(payload);
        if (selectionRect != null) {
            mDocumentOverlay.positionHandle(SelectionHandle.HandleType.END, selectionRect);
        }
    }

    /**
     * Handles the text selection message
     *
     * @param payload
     */
    private synchronized void textSelection(String payload) {
        if (payload.isEmpty() || payload.equals("EMPTY")) {
            if (mState == OverlayState.SELECTION) {
                changeStateTo(OverlayState.TRANSITION);
            }
            mDocumentOverlay.changeSelections(Collections.EMPTY_LIST);
        } else {
            List<RectF> rectangles = convertPayloadToRectangles(payload);
            if (mState != OverlayState.SELECTION) {
                changeStateTo(OverlayState.TRANSITION);
            }
            changeStateTo(OverlayState.SELECTION);
            mDocumentOverlay.changeSelections(rectangles);
        }
    }

    /**
     * Handles the cursor visibility message
     *
     * @param payload
     */
    private synchronized void cursorVisibility(String payload) {
        if (payload.equals("true")) {
            mDocumentOverlay.showCursor();
            if (mState != OverlayState.SELECTION) {
                mDocumentOverlay.showHandle(SelectionHandle.HandleType.MIDDLE);
            }
        } else if (payload.equals("false")) {
            mDocumentOverlay.hideCursor();
            mDocumentOverlay.hideHandle(SelectionHandle.HandleType.MIDDLE);
        }
    }

    /**
     * Handles the graphic selection change message
     *
     * @param payload
     */
    private void graphicSelection(String payload) {
        if (payload.isEmpty() || payload.equals("EMPTY")) {
            if (mState == OverlayState.GRAPHIC_SELECTION) {
                changeStateTo(OverlayState.TRANSITION);
            }
        } else {
            RectF rectangle = convertPayloadToRectangle(payload);
            mDocumentOverlay.changeGraphicSelection(rectangle);
            if (mState != OverlayState.GRAPHIC_SELECTION) {
                changeStateTo(OverlayState.TRANSITION);
            }
            changeStateTo(OverlayState.GRAPHIC_SELECTION);
        }
    }

    /**
     * Trigger a transition to a new overlay state.
     *
     * @param next - new state to transition to
     */
    public synchronized void changeStateTo(OverlayState next) {
        changeState(mState, next);
    }

    /**
     * Executes a transition from old overlay state to a new overlay state.
     *
     * @param previous - old state
     * @param next - new state
     */
    private synchronized void changeState(OverlayState previous, OverlayState next) {
        mState = next;
        handleGeneralChangeState(previous, next);
        switch (next) {
            case CURSOR:
                handleCursorState(previous);
                break;
            case SELECTION:
                handleSelectionState(previous);
                break;
            case GRAPHIC_SELECTION:
                handleGraphicSelectionState(previous);
                break;
            case TRANSITION:
                handleTransitionState(previous);
                break;
            case NONE:
                handleNoneState(previous);
                break;
        }
    }

    /**
     * Handle a general transition - executed for all transitions.
     */
    private void handleGeneralChangeState(OverlayState previous, OverlayState next) {
        if (previous == OverlayState.NONE) {
            LOKitShell.getToolbarController().switchToEditMode();
        } else if (next == OverlayState.NONE) {
            LOKitShell.getToolbarController().switchToViewMode();
        }
    }

    /**
     * Handle a transition to OverlayState.NONE state.
     */
    private void handleNoneState(OverlayState previous) {
        if (previous == OverlayState.NONE) {
            return;
        }

        // Just hide everything
        mDocumentOverlay.hideHandle(SelectionHandle.HandleType.START);
        mDocumentOverlay.hideHandle(SelectionHandle.HandleType.END);
        mDocumentOverlay.hideHandle(SelectionHandle.HandleType.MIDDLE);
        mDocumentOverlay.hideSelections();
        mDocumentOverlay.hideCursor();
        mDocumentOverlay.hideGraphicSelection();
        LibreOfficeMainActivity.mAppContext.hideSoftKeyboard();
    }

    /**
     * Handle a transition to OverlayState.SELECTION state.
     */
    private void handleSelectionState(OverlayState previous) {
        mDocumentOverlay.showHandle(SelectionHandle.HandleType.START);
        mDocumentOverlay.showHandle(SelectionHandle.HandleType.END);
        mDocumentOverlay.showSelections();
    }

    /**
     * Handle a transition to OverlayState.CURSOR state.
     */
    private void handleCursorState(OverlayState previous) {
        LibreOfficeMainActivity.mAppContext.showSoftKeyboard();
        if (previous == OverlayState.TRANSITION) {
            mDocumentOverlay.showHandle(SelectionHandle.HandleType.MIDDLE);
            mDocumentOverlay.showCursor();
        }
    }

    /**
     * Handle a transition to OverlayState.TRANSITION state.
     */
    private void handleTransitionState(OverlayState previous) {
        if (previous == OverlayState.SELECTION) {
            mDocumentOverlay.hideHandle(SelectionHandle.HandleType.START);
            mDocumentOverlay.hideHandle(SelectionHandle.HandleType.END);
            mDocumentOverlay.hideSelections();
        } else if (previous == OverlayState.CURSOR) {
            mDocumentOverlay.hideHandle(SelectionHandle.HandleType.MIDDLE);
        } else if (previous == OverlayState.GRAPHIC_SELECTION) {
            mDocumentOverlay.hideGraphicSelection();
        }
    }

    /**
     * Handle a transition to OverlayState.GRAPHIC_SELECTION state.
     */
    private void handleGraphicSelectionState(OverlayState previous) {
        mDocumentOverlay.showGraphicSelection();
        LibreOfficeMainActivity.mAppContext.hideSoftKeyboard();
    }

    /**
     * The current state the overlay is in.
     */
    public OverlayState getCurrentState() {
        return mState;
    }

    /**
     * A key event happened (i.e. user started typing).
     */
    public void keyEvent() {
        mKeyEvent = true;
    }

    /**
     * The states the overlay.
     */
    public enum OverlayState {
        /**
         * State where the overlay is empty
         */
        NONE,
        /**
         * In-between state where we need to transition to a new overlay state.
         * In this state we properly disable the older state and wait to transition
         * to a new state triggered by an invalidation.
         */
        TRANSITION,
        /**
         * State where we operate with the cursor.
         */
        CURSOR,
        /**
         * State where we operate the graphic selection.
         */
        GRAPHIC_SELECTION,
        /**
         * State where we operate the text selection.
         */
        SELECTION
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */