Debian Codegraph @

src/imports/Components/1.2/InputHandler.qml

raw
1 /*
2 * Copyright 2014 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 import QtQuick 2.4
18 import Lomiri.Components 1.2
19
20 /*
21 This component is a unified text selection and scrolling handler for both
22 TextField and TextArea components.
23 */
24
25 MultiPointTouchArea {
26 id: inputHandler
27 objectName: "input_handler"
28
29 // the root control
30 property Item main
31 // the input instance
32 property Item input
33 // the Flickable holding the input instance
34 property Flickable flickable
35
36 // item filling the visible text input area used to check handler visibility
37 property Item visibleArea: Item {
38 parent: flickable
39 anchors.fill: parent
40 }
41
42 // line size and spacing
43 property real lineSpacing: units.dp(3)
44 property real lineSize: input.font.pixelSize + lineSpacing
45 // input x/y distance from the frame
46 property point frameDistance: Qt.point(flickable.x, flickable.y)
47
48 // signal triggered when popup should be opened
49 signal pressAndHold(int pos, bool fromTouch)
50 signal tap(int pos)
51 property string oldText: ""
52 signal textModified()
53
54 function activateInput() {
55 if (!input.activeFocus) {
56 input.forceActiveFocus();
57 }
58 showInputPanel();
59 }
60
61 function showInputPanel() {
62 if (!LomiriApplication.inputMethod.visible) {
63 LomiriApplication.inputMethod.show();
64 }
65 textChanged = false;
66 }
67
68 // internal properties/functions
69 readonly property bool singleLine: input.hasOwnProperty("validator")
70 property var flickableList: new Array()
71 property bool textChanged: false
72 property var popover
73 property bool suppressReleaseEvent: false
74 property int pressedPosition: -1
75 // move properties
76 property int moveStarts: -1
77 property int moveEnds: -1
78 // set scroller to the first Flickable that scrolls the input
79 // this can be the internal Flickable if the full autosize is disabled
80 // or one of the input's parent Flickable
81 readonly property bool scrollingDisabled: main && main.hasOwnProperty("autoSize") ?
82 (main.autoSize && (main.maximumLineCount <= 0)) : false
83 onScrollingDisabledChanged: if (state == "") flickable.interactive = !scrollingDisabled
84 readonly property Flickable grandScroller: firstFlickableParent(main)
85 readonly property Flickable scroller: (scrollingDisabled && grandScroller) ? grandScroller : flickable
86
87 // ensures the text cursorRectangle is always in the internal Flickable's visible area
88 function ensureVisible(rect)
89 {
90 if (flickable.moving || flickable.flicking)
91 return;
92 if (flickable.contentX >= rect.x)
93 flickable.contentX = rect.x;
94 else if (flickable.contentX + flickable.width <= rect.x + rect.width)
95 flickable.contentX = rect.x + rect.width - flickable.width;
96 if (flickable.contentY >= rect.y)
97 flickable.contentY = rect.y;
98 else if (flickable.contentY + flickable.height <= rect.y + rect.height)
99 flickable.contentY = rect.y + rect.height - flickable.height;
100 }
101 // returns the cursor position from x,y pair
102 function unadulteratedCursorPosition(x, y) {
103 return singleLine ? input.positionAt(x, TextInput.CursorOnCharacter) : input.positionAt(x, y, TextInput.CursorOnCharacter);
104 }
105 // returns the cursor position taking frame into account
106 function cursorPosition(x, y) {
107 var frameSpacing = main.__styleInstance.frameSpacing;
108 var cursorPosition = unadulteratedCursorPosition(x, y);
109 if (cursorPosition == 0)
110 cursorPosition = unadulteratedCursorPosition(x + frameSpacing, y + frameSpacing);
111 if (cursorPosition == text.length)
112 cursorPosition = unadulteratedCursorPosition(x - frameSpacing, y - frameSpacing);
113 return cursorPosition
114 }
115
116 // returns the mouse position
117 function mousePosition(mouse) {
118 return cursorPosition(mouse.x, mouse.y);
119 }
120 // checks whether the position is in the selected text
121 function positionInSelection(pos) {
122 return (input.selectionStart !== input.selectionEnd)
123 && (pos >= Math.min(input.selectionStart, input.selectionEnd))
124 && (pos <= Math.max(input.selectionStart, input.selectionEnd));
125 }
126
127 // check whether the mouse is inside a selected text area
128 function mouseInSelection(mouse) {
129 var pos = mousePosition(mouse);
130 return positionInSelection(pos);
131 }
132 // selects text
133 function selectText(mouse) {
134 state = "select";
135 moveEnds = mousePosition(mouse);
136 if (moveStarts < 0) {
137 moveStarts = moveEnds;
138 }
139 input.select(moveStarts, moveEnds);
140 }
141 // returns the first Flickable parent of a given item
142 function firstFlickableParent(item) {
143 var p = item ? item.parent : null;
144 while (p && !p.hasOwnProperty("flicking")) {
145 p = p.parent;
146 }
147 return p;
148 }
149 // focuses the input if not yet focused, and shows the context menu
150 function openContextMenu(mouse, noAutoselect, fromTouch) {
151 var pos = mousePosition(mouse);
152 if (!main.focus || !mouseInSelection(mouse)) {
153 activateInput();
154 input.cursorPosition = pressedPosition = mousePosition(mouse);
155 if (!noAutoselect) {
156 input.selectWord();
157 }
158 }
159 // open context menu at the cursor position
160 inputHandler.pressAndHold(input.cursorPosition, fromTouch);
161 // if opened with left press (touch falls into this criteria as well), we need to set state to inactive
162 // so the mouse moves won't result in selected text loss/change
163 if (mouse.button === Qt.LeftButton) {
164 state = "inactive";
165 }
166 }
167
168 // disables interactive Flickable parents, stops at the first non-interactive flickable.
169 function toggleFlickablesInteractive(turnOn) {
170 var p;
171 if (!turnOn) {
172 // handle the scroller separately
173 p = firstFlickableParent(scroller)
174 while (p) {
175 if (p.interactive) {
176 flickableList.push(p);
177 p.interactive = false;
178 } else {
179 break;
180 }
181 p = firstFlickableParent(p);
182 }
183 } else {
184 while (flickableList.length > 0) {
185 p = flickableList.pop();
186 p.interactive = true;
187 }
188 }
189 }
190
191 // moves the specified position, called by the cursor handler
192 // positioner = "currentPosition/selectionStart/selectionEnd"
193 function positionCaret(positioner, x, y) {
194 if (positioner === "cursorPosition") {
195 input[positioner] = cursorPosition(x, y);
196 } else {
197 var pos = cursorPosition(x, y);
198 if (positioner === "selectionStart" && (pos < input.selectionEnd)) {
199 input.select(pos, input.selectionEnd);
200 } else if (positioner === "selectionEnd" && (pos > input.selectionStart)) {
201 input.select(input.selectionStart, pos);
202 }
203 }
204 }
205
206 // moves the cursor one page forward with or without positioning the cursor
207 function movePage(forward) {
208 var cx = input.cursorRectangle.x;
209 var cy = input.cursorRectangle.y;
210 if (forward) {
211 if (singleLine) {
212 cx += visibleArea.width;
213 } else {
214 cy += visibleArea.height;
215 }
216 } else {
217 if (singleLine) {
218 cx -= visibleArea.width;
219 } else {
220 cy -= visibleArea.height;
221 }
222 }
223 input.cursorPosition = cursorPosition(cx, cy);
224 }
225
226 Component.onCompleted: {
227 state = (main.focus) ? "" : "inactive";
228 // FIXME: Qt5.3 related! mouseEnabled is a 5.3 related property which has a positive
229 // default value. That value messes up the current understanding (5.2) of the
230 // MultiPointTouchArea functioning. We need to set it to false until 5.3 will be the
231 // default supported Qt version, when we can have a clean property value assignment
232 if (inputHandler.hasOwnProperty("mouseEnabled")) {
233 inputHandler.mouseEnabled = false;
234 }
235 }
236
237 // states
238 states: [
239 // override default state to turn on the saved Flickable interactive mode
240 State {
241 name: ""
242 StateChangeScript {
243 // restore interactive for all Flickable parents
244 script: toggleFlickablesInteractive(true);
245 }
246 },
247 State {
248 name: "inactive"
249 // we do not disable scroller here as in case the internal scrolling
250 // is disabled (scrollingDisabled = true) the outer scroller (grandScroller)
251 // would be blocked as well, which we don't want to
252 PropertyChanges {
253 target: flickable
254 interactive: false
255 }
256 },
257 State {
258 name: "scrolling"
259 StateChangeScript {
260 script: {
261 // stop scrolling all the parents
262 toggleFlickablesInteractive(false);
263 // stop touch timers
264 touchPoint.reset();
265 }
266 }
267 },
268 State {
269 name: "select"
270 // during select state all the flickables are blocked (interactive = false)
271 // we can use scroller here as we need to disable the outer scroller too!
272 PropertyChanges {
273 target: scroller
274 interactive: false
275 }
276 StateChangeScript {
277 script: {
278 // turn off interactive for all parent flickables
279 toggleFlickablesInteractive(false);
280 if (!positionInSelection(pressedPosition)) {
281 input.cursorPosition = pressedPosition;
282 }
283 }
284 }
285 }
286 ]
287
288 // brings the state back to default when the component looses focus
289 // and ensures input has active focus when component regains focus
290 Connections {
291 target: main
292 ignoreUnknownSignals: true
293 function onFocusChanged() {
294 LomiriApplication.inputMethod.commit()
295 state = (main.focus) ? "" : "inactive";
296 if (main.focus) {
297 input.forceActiveFocus()
298 }
299 }
300 }
301
302 // input specific signals
303 Connections {
304 target: input
305 function onCursorRectangleChanged() { ensureVisible(input.cursorRectangle) }
306 function onTextChanged() {
307 inputHandler.textChanged = true;
308 if (inputHandler.oldText != input.text) {
309 inputHandler.textModified()
310 inputHandler.oldText = input.text
311 }
312 }
313 // make sure we show the OSK
314 function onActiveFocusChanged() { showInputPanel() }
315 }
316
317 // inner or outer Flickable controlling
318 Connections {
319 target: scroller
320 // turn scrolling state on
321 function onFlickStarted() { toggleScrollingState(true) }
322 function onMovementStarted() { toggleScrollingState(true) }
323 // reset to default state
324 function onMovementEnded() { toggleScrollingState(false) }
325
326 function toggleScrollingState(turnOn) {
327 if (!main.focus) {
328 return;
329 }
330 inputHandler.state = (turnOn) ? "scrolling" : ""
331 }
332 }
333
334 // PageUp and PageDown handling
335 Keys.onPressed: {
336 if (event.key === Qt.Key_PageUp && event.modifiers === Qt.NoModifier) {
337 movePage(false);
338 } else if (event.key === Qt.Key_PageDown && event.modifiers === Qt.NoModifier) {
339 movePage(true);
340 }
341 }
342
343 // touch and mous handling
344 function handlePressed(event, touch) {
345 if (touch) {
346 // we do not have longTap or double tap, therefore we need to generate those
347 event.touch();
348 } else {
349 // consume event so it does not get forwarded to the input
350 event.accepted = true;
351 }
352 // remember pressed position as we need it when entering into selection state
353 pressedPosition = mousePosition(event);
354 }
355 function handleReleased(event, touch) {
356 if (touch) {
357 event.untouch();
358 }
359 if ((!main.focus && !main.activeFocusOnPress) || suppressReleaseEvent === true) {
360 suppressReleaseEvent = false;
361 return;
362 }
363
364 activateInput();
365 if (state === "" || touch) {
366 input.cursorPosition = mousePosition(event);
367 }
368 moveStarts = moveEnds = -1;
369 state = "";
370 // check if we get right-click from the frame or the area that has no text
371 if (event.button === Qt.RightButton) {
372 // open the popover
373 inputHandler.pressAndHold(input.cursorPosition, touch);
374 } else {
375 inputHandler.tap(input.cursorPosition);
376 }
377 }
378 function handleMove(event, touch ) {
379 // leave if not focus, not the left button or not in select state
380 if (!input.activeFocus || (!touch && event.button !== Qt.LeftButton) || !main.selectByMouse) {
381 return;
382 }
383 selectText(event);
384 }
385 function handleDblClick(event, touch) {
386 if (main.selectByMouse) {
387 openContextMenu(event, false, touch);
388 // turn selection state temporarily so the selection is not cleared on release
389 state = "selection";
390 suppressReleaseEvent = true;
391 }
392 }
393
394 // Mouse handling
395 Mouse.forwardTo: [main]
396 Mouse.onPressed: handlePressed(mouse, false)
397 Mouse.onReleased: handleReleased(mouse, false)
398 Mouse.onPositionChanged: handleMove(mouse, false)
399 Mouse.onDoubleClicked: handleDblClick(mouse, false)
400
401 // right button handling
402 MouseArea {
403 anchors.fill: parent
404 acceptedButtons: Qt.RightButton
405 // trigger pressAndHold
406 onReleased: openContextMenu(mouse, true, false)
407 }
408 Keys.onMenuPressed: inputHandler.pressAndHold(input.cursorPosition, false);
409
410 // touch handling
411 touchPoints: TouchPoint {
412 id: touchPoint
413 function touch() {
414 longTap.restart();
415 if (!doubleTap.running) {
416 doubleTap.restart();
417 } else if (doubleTap.tapCount > 0) {
418 doubleTap.running = false;
419 handleDblClick(touchPoint, true);
420 }
421 }
422 function untouch() {
423 longTap.running = false;
424 }
425 function reset() {
426 longTap.running = false;
427 doubleTap.running = false;
428 }
429 }
430 Timer {
431 id: longTap
432 // sync with QQuickMouseArea constant
433 interval: 800
434 onTriggered: {
435 // do not open context menu if the input is not focus
436 if (!main.focus) {
437 return;
438 }
439
440 // do not open context menu if this is scrolling
441 if (touchPoint.startY - touchPoint.y < -units.gu(2))
442 return;
443
444 openContextMenu(touchPoint, false, true);
445 suppressReleaseEvent = true;
446 }
447 }
448
449 property bool doubleTapInProgress: doubleTap.running
450 Timer {
451 id: doubleTap
452 property int tapCount: 0
453 interval: 400
454 onRunningChanged: {
455 tapCount = running;
456 }
457 }
458 onPressed: handlePressed(touchPoints[0], true)
459 onReleased: handleReleased(touchPoints[0], true)
460
461 property Item cursorPositionCursor: null
462 property Item selectionStartCursor: null
463 property Item selectionEndCursor: null
464
465 // cursors to use when text is selected
466 Connections {
467 target: input
468 function onSelectedTextChanged() {
469 if (selectedText !== "") {
470 if (!selectionStartCursor) {
471 selectionStartCursor = input.cursorDelegate.createObject(
472 input, {
473 "positionProperty": "selectionStart",
474 "handler": inputHandler,
475 }
476 );
477 moveSelectionCursor(selectionStartCursor);
478 selectionEndCursor = input.cursorDelegate.createObject(
479 input, {
480 "positionProperty": "selectionEnd",
481 "handler": inputHandler,
482 }
483 );
484 moveSelectionCursor(selectionEndCursor);
485 }
486 } else {
487 if (selectionStartCursor) {
488 selectionStartCursor.destroy();
489 selectionStartCursor = null;
490 selectionEndCursor.destroy();
491 selectionEndCursor = null;
492 }
493 }
494 }
495 function onSelectionStartChanged() { moveSelectionCursor(selectionStartCursor, true); }
496 function onSelectionEndChanged() { moveSelectionCursor(selectionEndCursor, true); }
497
498 function moveSelectionCursor(cursor, updateProperty) {
499 if (!cursor) {
500 return;
501 }
502 // workaround for https://bugreports.qt-project.org/browse/QTBUG-38704
503 // selectedTextChanged signal is not emitted for TextEdit when selectByMouse is false
504 if (updateProperty && QuickUtils.className(input) === "QQuickTextEdit") {
505 input.selectedTextChanged();
506 }
507
508 var pos = input.positionToRectangle(input[cursor.positionProperty]);
509 cursor.x = pos.x;
510 cursor.y = pos.y;
511 cursor.height = pos.height;
512 ensureVisible(pos);
513 }
514 }
515 }