115b2fbc4bb90a22302498310ecc8b8dd807c672
[WebKit-https.git] / Source / WebKit / blackberry / WebKitSupport / InputHandler.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2012 Research In Motion Limited. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #include "config.h"
20 #include "InputHandler.h"
21
22 #include "BackingStore.h"
23 #include "BackingStoreClient.h"
24 #include "CSSStyleDeclaration.h"
25 #include "Chrome.h"
26 #include "ColorPickerClient.h"
27 #include "DOMSupport.h"
28 #include "DatePickerClient.h"
29 #include "Document.h"
30 #include "DocumentLoader.h"
31 #include "DocumentMarkerController.h"
32 #include "FocusController.h"
33 #include "Frame.h"
34 #include "FrameView.h"
35 #include "HTMLFormElement.h"
36 #include "HTMLInputElement.h"
37 #include "HTMLNames.h"
38 #include "HTMLOptGroupElement.h"
39 #include "HTMLOptionElement.h"
40 #include "HTMLSelectElement.h"
41 #include "HTMLTextAreaElement.h"
42 #include "NotImplemented.h"
43 #include "Page.h"
44 #include "PlatformKeyboardEvent.h"
45 #include "PluginView.h"
46 #include "Range.h"
47 #include "RenderLayer.h"
48 #include "RenderMenuList.h"
49 #include "RenderPart.h"
50 #include "RenderText.h"
51 #include "RenderTextControl.h"
52 #include "RenderWidget.h"
53 #include "RenderedDocumentMarker.h"
54 #include "ScopePointer.h"
55 #include "SelectPopupClient.h"
56 #include "SelectionHandler.h"
57 #include "SpellChecker.h"
58 #include "TextCheckerClient.h"
59 #include "TextIterator.h"
60 #include "VisiblePosition.h"
61 #include "WebPageClient.h"
62 #include "WebPage_p.h"
63 #include "WebSettings.h"
64 #include "htmlediting.h"
65 #include "visible_units.h"
66
67 #include <BlackBerryPlatformIMF.h>
68 #include <BlackBerryPlatformKeyboardEvent.h>
69 #include <BlackBerryPlatformLog.h>
70 #include <BlackBerryPlatformMisc.h>
71 #include <BlackBerryPlatformScreen.h>
72 #include <BlackBerryPlatformSettings.h>
73 #include <sys/keycodes.h>
74 #include <wtf/text/CString.h>
75
76 #define ENABLE_INPUT_LOG 0
77 #define ENABLE_FOCUS_LOG 0
78 #define ENABLE_SPELLING_LOG 0
79
80 static const unsigned MaxLearnTextDataSize = 500;
81
82 using namespace BlackBerry::Platform;
83 using namespace WebCore;
84
85 #if ENABLE_INPUT_LOG
86 #define InputLog(severity, format, ...) logAlways(severity, format, ## __VA_ARGS__)
87 #else
88 #define InputLog(severity, format, ...)
89 #endif // ENABLE_INPUT_LOG
90
91 #if ENABLE_FOCUS_LOG
92 #define FocusLog(severity, format, ...) logAlways(severity, format, ## __VA_ARGS__)
93 #else
94 #define FocusLog(severity, format, ...)
95 #endif // ENABLE_FOCUS_LOG
96
97 #if ENABLE_SPELLING_LOG
98 #define SpellingLog(severity, format, ...) logAlways(severity, format, ## __VA_ARGS__)
99 #else
100 #define SpellingLog(severity, format, ...)
101 #endif // ENABLE_SPELLING_LOG
102
103 namespace BlackBerry {
104 namespace WebKit {
105
106 class ProcessingChangeGuard {
107 public:
108     ProcessingChangeGuard(InputHandler* inputHandler)
109         : m_inputHandler(inputHandler)
110         , m_savedProcessingChange(false)
111     {
112         ASSERT(m_inputHandler);
113
114         m_savedProcessingChange = m_inputHandler->processingChange();
115         m_inputHandler->setProcessingChange(true);
116     }
117
118     ~ProcessingChangeGuard()
119     {
120         m_inputHandler->setProcessingChange(m_savedProcessingChange);
121     }
122
123 private:
124     InputHandler* m_inputHandler;
125     bool m_savedProcessingChange;
126 };
127
128 InputHandler::InputHandler(WebPagePrivate* page)
129     : m_webPage(page)
130     , m_currentFocusElement(0)
131     , m_inputModeEnabled(false)
132     , m_processingChange(false)
133     , m_changingFocus(false)
134     , m_currentFocusElementType(TextEdit)
135     , m_currentFocusElementTextEditMask(DEFAULT_STYLE)
136     , m_composingTextStart(0)
137     , m_composingTextEnd(0)
138     , m_pendingKeyboardVisibilityChange(NoChange)
139     , m_delayKeyboardVisibilityChange(false)
140     , m_request(0)
141     , m_processingTransactionId(-1)
142     , m_receivedBackspaceKeyDown(false)
143     , m_expectedKeyUpChar(0)
144 {
145 }
146
147 InputHandler::~InputHandler()
148 {
149 }
150
151 static BlackBerryInputType convertInputType(const HTMLInputElement* inputElement)
152 {
153     if (inputElement->isPasswordField())
154         return InputTypePassword;
155     if (inputElement->isSearchField())
156         return InputTypeSearch;
157     if (inputElement->isEmailField())
158         return InputTypeEmail;
159     if (inputElement->isMonthControl())
160         return InputTypeMonth;
161     if (inputElement->isNumberField())
162         return InputTypeNumber;
163     if (inputElement->isTelephoneField())
164         return InputTypeTelephone;
165     if (inputElement->isURLField())
166         return InputTypeURL;
167 #if ENABLE(INPUT_TYPE_COLOR)
168     if (inputElement->isColorControl())
169         return InputTypeColor;
170 #endif
171     if (inputElement->isDateControl())
172         return InputTypeDate;
173     if (inputElement->isDateTimeControl())
174         return InputTypeDateTime;
175     if (inputElement->isDateTimeLocalControl())
176         return InputTypeDateTimeLocal;
177     if (inputElement->isTimeControl())
178         return InputTypeTime;
179     // FIXME: missing WEEK popup selector
180     if (DOMSupport::elementIdOrNameIndicatesEmail(inputElement))
181         return InputTypeEmail;
182     if (DOMSupport::elementIdOrNameIndicatesUrl(inputElement))
183         return InputTypeURL;
184     if (DOMSupport::elementPatternIndicatesNumber(inputElement))
185         return InputTypeNumber;
186     if (DOMSupport::elementPatternIndicatesHexadecimal(inputElement))
187         return InputTypeHexadecimal;
188
189     return InputTypeText;
190 }
191
192 static int64_t inputStyle(BlackBerryInputType type, const Element* element)
193 {
194     switch (type) {
195     case InputTypeEmail:
196     case InputTypeURL:
197     case InputTypeSearch:
198     case InputTypeText:
199     case InputTypeTextArea:
200         {
201             DOMSupport::AttributeState autoCompleteState = DOMSupport::elementSupportsAutocomplete(element);
202             DOMSupport::AttributeState autoCorrectState = DOMSupport::elementSupportsAutocorrect(element);
203
204             // Autocomplete disabled explicitly.
205             if (autoCompleteState == DOMSupport::Off) {
206                 if (autoCorrectState == DOMSupport::On)
207                     return NO_PREDICTION;
208                 return NO_AUTO_TEXT | NO_PREDICTION | NO_AUTO_CORRECTION;
209             }
210
211             // Autocomplete enabled explicitly.
212             if (autoCompleteState == DOMSupport::On) {
213                 if (autoCorrectState == DOMSupport::Off)
214                     return NO_AUTO_TEXT | NO_AUTO_CORRECTION;
215                 return DEFAULT_STYLE;
216             }
217
218             // Check for reserved strings and known types.
219             if (type == InputTypeEmail || type == InputTypeURL || DOMSupport::elementIdOrNameIndicatesNoAutocomplete(element)) {
220                 if (autoCorrectState == DOMSupport::On)
221                     return NO_PREDICTION;
222                 return NO_AUTO_TEXT | NO_PREDICTION | NO_AUTO_CORRECTION;
223             }
224
225             // Autocomplete state wasn't provided if it is a text area or autocorrect is on, apply support.
226             if (autoCorrectState == DOMSupport::On || (type == InputTypeTextArea && autoCorrectState != DOMSupport::Off))
227                 return DEFAULT_STYLE;
228
229             // Single line text input, without special features explicitly turned on or a textarea
230             // with autocorrect disabled explicitly. Only enable predictions.
231             return NO_AUTO_TEXT | NO_AUTO_CORRECTION;
232         }
233     case InputTypePassword:
234     case InputTypeNumber:
235     case InputTypeTelephone:
236     case InputTypeHexadecimal:
237         // Disable special handling.
238         return NO_AUTO_TEXT | NO_PREDICTION | NO_AUTO_CORRECTION;
239     default:
240         break;
241     }
242     return DEFAULT_STYLE;
243 }
244
245 static VirtualKeyboardType convertInputTypeToVKBType(BlackBerryInputType inputType)
246 {
247     switch (inputType) {
248     case InputTypeURL:
249         return VKBTypeUrl;
250     case InputTypeEmail:
251         return VKBTypeEmail;
252     case InputTypeTelephone:
253         return VKBTypePhone;
254     case InputTypePassword:
255         return VKBTypePassword;
256     case InputTypeNumber:
257     case InputTypeHexadecimal:
258         return VKBTypePin;
259     default:
260         // All other types are text based use default keyboard.
261         return VKBTypeDefault;
262     }
263 }
264
265 static VirtualKeyboardType convertStringToKeyboardType(const AtomicString& string)
266 {
267     DEFINE_STATIC_LOCAL(AtomicString, Default, ("default"));
268     DEFINE_STATIC_LOCAL(AtomicString, Url, ("url"));
269     DEFINE_STATIC_LOCAL(AtomicString, Email, ("email"));
270     DEFINE_STATIC_LOCAL(AtomicString, Password, ("password"));
271     DEFINE_STATIC_LOCAL(AtomicString, Web, ("web"));
272     DEFINE_STATIC_LOCAL(AtomicString, Number, ("number"));
273     DEFINE_STATIC_LOCAL(AtomicString, Symbol, ("symbol"));
274     DEFINE_STATIC_LOCAL(AtomicString, Phone, ("phone"));
275     DEFINE_STATIC_LOCAL(AtomicString, Pin, ("pin"));
276     DEFINE_STATIC_LOCAL(AtomicString, Hex, ("hexadecimal"));
277
278     if (string.isEmpty())
279         return VKBTypeNotSet;
280     if (equalIgnoringCase(string, Default))
281         return VKBTypeDefault;
282     if (equalIgnoringCase(string, Url))
283         return VKBTypeUrl;
284     if (equalIgnoringCase(string, Email))
285         return VKBTypeEmail;
286     if (equalIgnoringCase(string, Password))
287         return VKBTypePassword;
288     if (equalIgnoringCase(string, Web))
289         return VKBTypeWeb;
290     if (equalIgnoringCase(string, Number))
291         return VKBTypeNumPunc;
292     if (equalIgnoringCase(string, Symbol))
293         return VKBTypeSymbol;
294     if (equalIgnoringCase(string, Phone))
295         return VKBTypePhone;
296     if (equalIgnoringCase(string, Pin) || equalIgnoringCase(string, Hex))
297         return VKBTypePin;
298     return VKBTypeNotSet;
299 }
300
301 static VirtualKeyboardType keyboardTypeAttribute(const WebCore::Element* element)
302 {
303     DEFINE_STATIC_LOCAL(QualifiedName, keyboardTypeAttr, (nullAtom, "data-blackberry-virtual-keyboard-type", nullAtom));
304
305     if (element->fastHasAttribute(keyboardTypeAttr)) {
306         AtomicString attributeString = element->fastGetAttribute(keyboardTypeAttr);
307         return convertStringToKeyboardType(attributeString);
308     }
309
310     if (element->isFormControlElement()) {
311         const HTMLFormControlElement* formElement = static_cast<const HTMLFormControlElement*>(element);
312         if (formElement->form() && formElement->form()->fastHasAttribute(keyboardTypeAttr)) {
313             AtomicString attributeString = formElement->form()->fastGetAttribute(keyboardTypeAttr);
314             return convertStringToKeyboardType(attributeString);
315         }
316     }
317
318     return VKBTypeNotSet;
319 }
320
321 static VirtualKeyboardEnterKeyType convertStringToKeyboardEnterKeyType(const AtomicString& string)
322 {
323     DEFINE_STATIC_LOCAL(AtomicString, Default, ("default"));
324     DEFINE_STATIC_LOCAL(AtomicString, Connect, ("connect"));
325     DEFINE_STATIC_LOCAL(AtomicString, Done, ("done"));
326     DEFINE_STATIC_LOCAL(AtomicString, Go, ("go"));
327     DEFINE_STATIC_LOCAL(AtomicString, Join, ("join"));
328     DEFINE_STATIC_LOCAL(AtomicString, Next, ("next"));
329     DEFINE_STATIC_LOCAL(AtomicString, Search, ("search"));
330     DEFINE_STATIC_LOCAL(AtomicString, Send, ("send"));
331     DEFINE_STATIC_LOCAL(AtomicString, Submit, ("submit"));
332
333     if (string.isEmpty())
334         return VKBEnterKeyNotSet;
335     if (equalIgnoringCase(string, Default))
336         return VKBEnterKeyDefault;
337     if (equalIgnoringCase(string, Connect))
338         return VKBEnterKeyConnect;
339     if (equalIgnoringCase(string, Done))
340         return VKBEnterKeyDone;
341     if (equalIgnoringCase(string, Go))
342         return VKBEnterKeyGo;
343     if (equalIgnoringCase(string, Join))
344         return VKBEnterKeyJoin;
345     if (equalIgnoringCase(string, Next))
346         return VKBEnterKeyNext;
347     if (equalIgnoringCase(string, Search))
348         return VKBEnterKeySearch;
349     if (equalIgnoringCase(string, Send))
350         return VKBEnterKeySend;
351     if (equalIgnoringCase(string, Submit))
352         return VKBEnterKeySubmit;
353     return VKBEnterKeyNotSet;
354 }
355
356 static VirtualKeyboardEnterKeyType keyboardEnterKeyTypeAttribute(const WebCore::Element* element)
357 {
358     DEFINE_STATIC_LOCAL(QualifiedName, keyboardEnterKeyTypeAttr, (nullAtom, "data-blackberry-virtual-keyboard-enter-key", nullAtom));
359
360     if (element->fastHasAttribute(keyboardEnterKeyTypeAttr)) {
361         AtomicString attributeString = element->fastGetAttribute(keyboardEnterKeyTypeAttr);
362         return convertStringToKeyboardEnterKeyType(attributeString);
363     }
364
365     if (element->isFormControlElement()) {
366         const HTMLFormControlElement* formElement = static_cast<const HTMLFormControlElement*>(element);
367         if (formElement->form() && formElement->form()->fastHasAttribute(keyboardEnterKeyTypeAttr)) {
368             AtomicString attributeString = formElement->form()->fastGetAttribute(keyboardEnterKeyTypeAttr);
369             return convertStringToKeyboardEnterKeyType(attributeString);
370         }
371     }
372
373     return VKBEnterKeyNotSet;
374 }
375
376 void InputHandler::setProcessingChange(bool processingChange)
377 {
378     if (processingChange == m_processingChange)
379         return;
380
381     m_processingChange = processingChange;
382
383     if (!m_processingChange)
384         m_webPage->m_selectionHandler->inputHandlerDidFinishProcessingChange();
385 }
386
387 WTF::String InputHandler::elementText()
388 {
389     if (!isActiveTextEdit())
390         return WTF::String();
391
392     return DOMSupport::inputElementText(m_currentFocusElement.get());
393 }
394
395 BlackBerryInputType InputHandler::elementType(Element* element) const
396 {
397     if (const HTMLInputElement* inputElement = static_cast<const HTMLInputElement*>(element->toInputElement()))
398         return convertInputType(inputElement);
399
400     if (element->hasTagName(HTMLNames::textareaTag))
401         return InputTypeTextArea;
402
403     // Default to InputTypeTextArea for content editable fields.
404     return InputTypeTextArea;
405 }
406
407 void InputHandler::focusedNodeChanged()
408 {
409     ASSERT(m_webPage->m_page->focusController());
410     Frame* frame = m_webPage->m_page->focusController()->focusedOrMainFrame();
411     if (!frame || !frame->document())
412         return;
413
414     Node* node = frame->document()->focusedNode();
415
416     if (isActiveTextEdit() && m_currentFocusElement == node) {
417         notifyClientOfKeyboardVisibilityChange(true);
418         return;
419     }
420
421     if (node && node->isElementNode()) {
422         Element* element = static_cast<Element*>(node);
423         if (DOMSupport::isElementTypePlugin(element)) {
424             setPluginFocused(element);
425             return;
426         }
427
428         if (DOMSupport::isTextBasedContentEditableElement(element)) {
429             // Focused node is a text based input field, textarea or content editable field.
430             setElementFocused(element);
431             return;
432         }
433     }
434
435     if (isActiveTextEdit() && m_currentFocusElement->isContentEditable()) {
436         // This is a special handler for content editable fields. The focus node is the top most
437         // field that is content editable, however, by enabling / disabling designmode and
438         // content editable, it is possible through javascript or selection to trigger the focus node to
439         // change even while maintaining editing on the same selection point. If the focus element
440         // isn't contentEditable, but the current selection is, don't send a change notification.
441
442         // When processing changes selection changes occur that may reset the focus element
443         // and could potentially cause a crash as m_currentFocusElement should not be
444         // changed during processing of an EditorCommand.
445         if (processingChange())
446             return;
447
448         Frame* frame = m_currentFocusElement->document()->frame();
449         ASSERT(frame);
450
451         // Test the current selection to make sure that the content in focus is still content
452         // editable. This may mean Javascript triggered a focus change by modifying the
453         // top level parent of this object's content editable state without actually modifying
454         // this particular object.
455         // Example site: html5demos.com/contentEditable - blur event triggers focus change.
456         if (frame == m_webPage->focusedOrMainFrame() && frame->selection()->start().anchorNode()
457             && frame->selection()->start().anchorNode()->isContentEditable())
458                 return;
459     }
460
461     // No valid focus element found for handling.
462     setElementUnfocused();
463 }
464
465 void InputHandler::setPluginFocused(Element* element)
466 {
467     ASSERT(DOMSupport::isElementTypePlugin(element));
468
469     if (isActiveTextEdit())
470         setElementUnfocused();
471
472     m_currentFocusElementType = Plugin;
473     m_currentFocusElement = element;
474 }
475
476 static bool convertStringToWchar(const WTF::String& string, wchar_t* dest, int destCapacity, int* destLength)
477 {
478     ASSERT(dest);
479
480     if (!string.length()) {
481         destLength = 0;
482         return true;
483     }
484
485     UErrorCode ec = U_ZERO_ERROR;
486     // wchar_t strings sent to IMF are 32 bit so casting to UChar32 is safe.
487     u_strToUTF32(reinterpret_cast<UChar32*>(dest), destCapacity, destLength, string.characters(), string.length(), &ec);
488     if (ec) {
489         logAlways(LogLevelCritical, "InputHandler::convertStringToWchar Error converting string ec (%d).", ec);
490         destLength = 0;
491         return false;
492     }
493     return true;
494 }
495
496 static bool convertStringToWcharVector(const WTF::String& string, WTF::Vector<wchar_t>& wcharString)
497 {
498     ASSERT(wcharString.isEmpty());
499
500     int length = string.length();
501     if (!length)
502         return true;
503
504     if (!wcharString.tryReserveCapacity(length + 1)) {
505         logAlways(LogLevelCritical, "InputHandler::convertStringToWcharVector Cannot allocate memory for string.");
506         return false;
507     }
508
509     int destLength = 0;
510     if (!convertStringToWchar(string, wcharString.data(), length + 1, &destLength))
511         return false;
512
513     wcharString.resize(destLength);
514     return true;
515 }
516
517 static WTF::String convertSpannableStringToString(spannable_string_t* src)
518 {
519     if (!src || !src->str || !src->length)
520         return WTF::String();
521
522     WTF::Vector<UChar> dest;
523     int destCapacity = (src->length * 2) + 1;
524     if (!dest.tryReserveCapacity(destCapacity)) {
525         logAlways(LogLevelCritical, "InputHandler::convertSpannableStringToString Cannot allocate memory for string.");
526         return WTF::String();
527     }
528
529     int destLength = 0;
530     UErrorCode ec = U_ZERO_ERROR;
531     // wchar_t strings sent from IMF are 32 bit so casting to UChar32 is safe.
532     u_strFromUTF32(dest.data(), destCapacity, &destLength, reinterpret_cast<UChar32*>(src->str), src->length, &ec);
533     if (ec) {
534         logAlways(LogLevelCritical, "InputHandler::convertSpannableStringToString Error converting string ec (%d).", ec);
535         return WTF::String();
536     }
537     dest.resize(destLength);
538     return WTF::String(dest.data(), destLength);
539 }
540
541 void InputHandler::sendLearnTextDetails(const WTF::String& string)
542 {
543     Vector<wchar_t> wcharString;
544     if (!convertStringToWcharVector(string, wcharString) || wcharString.isEmpty())
545         return;
546
547     m_webPage->m_client->inputLearnText(wcharString.data(), wcharString.size());
548 }
549
550 void InputHandler::learnText()
551 {
552     if (!isActiveTextEdit())
553         return;
554
555     // Do not send (or calculate) the text when the field is NO_PREDICTION or NO_AUTO_TEXT.
556     if (m_currentFocusElementTextEditMask & NO_PREDICTION || m_currentFocusElementTextEditMask & NO_AUTO_TEXT)
557         return;
558
559     WTF::String textInField(elementText());
560     textInField = textInField.substring(std::max(0, static_cast<int>(textInField.length() - MaxLearnTextDataSize)), textInField.length());
561     textInField.remove(0, textInField.find(" "));
562
563     // Build up the 500 character strings in word chunks.
564     // Spec says 1000, but memory corruption has been observed.
565     ASSERT(textInField.length() <= MaxLearnTextDataSize);
566
567     if (textInField.isEmpty())
568         return;
569
570     InputLog(LogLevelInfo, "InputHandler::learnText '%s'", textInField.latin1().data());
571     sendLearnTextDetails(textInField);
572 }
573
574 void InputHandler::requestCheckingOfString(PassRefPtr<WebCore::TextCheckingRequest> textCheckingRequest)
575 {
576     m_request = textCheckingRequest;
577
578     if (!m_request) {
579         SpellingLog(LogLevelWarn, "InputHandler::requestCheckingOfString did not receive a valid request.");
580         return;
581     }
582
583     unsigned requestLength = m_request->text().length();
584
585     // Check if the field should be spellchecked.
586     if (!isActiveTextEdit() || !shouldSpellCheckElement(m_currentFocusElement.get()) || requestLength < 2) {
587         m_request->didCancel();
588         return;
589     }
590
591     if (requestLength > MaxSpellCheckingStringLength) {
592         // Cancel this request and send it off in newly created chunks.
593         m_request->didCancel();
594         if (m_currentFocusElement->document() && m_currentFocusElement->document()->frame() && m_currentFocusElement->document()->frame()->selection()) {
595             // Convert from position back to selection so we can expand the range to include the previous line. This should handle cases when the user hits
596             // enter to finish composing a word and create a new line.
597             VisiblePosition caretPosition = m_currentFocusElement->document()->frame()->selection()->start();
598             VisibleSelection visibleSelection = VisibleSelection(previousLinePosition(caretPosition, caretPosition.lineDirectionPointForBlockDirectionNavigation()), caretPosition);
599             spellCheckBlock(visibleSelection, TextCheckingProcessIncremental);
600         }
601         return;
602     }
603
604     wchar_t* checkingString = (wchar_t*)malloc(sizeof(wchar_t) * (requestLength + 1));
605     if (!checkingString) {
606         logAlways(LogLevelCritical, "InputHandler::requestCheckingOfString Cannot allocate memory for string.");
607         m_request->didCancel();
608         return;
609     }
610
611     int paragraphLength = 0;
612     if (!convertStringToWchar(m_request->text(), checkingString, requestLength + 1, &paragraphLength)) {
613         logAlways(LogLevelCritical, "InputHandler::requestCheckingOfString Failed to convert String to wchar type.");
614         free(checkingString);
615         m_request->didCancel();
616         return;
617     }
618
619     m_processingTransactionId = m_webPage->m_client->checkSpellingOfStringAsync(checkingString, static_cast<unsigned>(paragraphLength));
620     free(checkingString);
621
622     // If the call to the input service did not go through, then cancel the request so we don't block endlessly.
623     // This should still take transactionId as a parameter to maintain the same behavior as if InputMethodSupport
624     // were to cancel a request during processing.
625     if (m_processingTransactionId == -1) { // Error before sending request to input service.
626         m_request->didCancel();
627         return;
628     }
629 }
630
631 void InputHandler::spellCheckingRequestCancelled(int32_t transactionId)
632 {
633     SpellingLog(LogLevelWarn, "InputHandler::spellCheckingRequestCancelled Expected transaction id %d, received %d. %s"
634                 , transactionId
635                 , m_processingTransactionId
636                 , transactionId == m_processingTransactionId ? "" : "We are out of sync with input service.");
637
638     m_request->didCancel();
639     m_processingTransactionId = -1;
640 }
641
642 void InputHandler::spellCheckingRequestProcessed(int32_t transactionId, spannable_string_t* spannableString)
643 {
644     SpellingLog(LogLevelWarn, "InputHandler::spellCheckingRequestProcessed Expected transaction id %d, received %d. %s"
645                 , transactionId
646                 , m_processingTransactionId
647                 , transactionId == m_processingTransactionId ? "" : "We are out of sync with input service.");
648
649     if (!spannableString || !isActiveTextEdit()) {
650         SpellingLog(LogLevelWarn, "InputHandler::spellCheckingRequestProcessed Cancelling request with transactionId %d.", transactionId);
651         m_request->didCancel();
652         m_processingTransactionId = -1;
653         return;
654     }
655
656     Vector<TextCheckingResult> results;
657
658     // Convert the spannableString to TextCheckingResult then append to results vector.
659     WTF::String replacement;
660     TextCheckingResult textCheckingResult;
661     textCheckingResult.type = TextCheckingTypeSpelling;
662     textCheckingResult.replacement = replacement;
663     textCheckingResult.location = 0;
664     textCheckingResult.length = 0;
665
666     span_t* span = spannableString->spans;
667     for (unsigned int i = 0; i < spannableString->spans_count; i++) {
668         if (!span)
669             break;
670         if (span->end < span->start) {
671             m_request->didCancel();
672             return;
673         }
674         if (span->attributes_mask & MISSPELLED_WORD_ATTRIB) {
675             textCheckingResult.location = span->start;
676             // The end point includes the character that it is before. Ie, 0, 0
677             // applies to the first character as the end point includes the character
678             // at the position. This means the endPosition is always +1.
679             textCheckingResult.length = span->end - span->start + 1;
680             results.append(textCheckingResult);
681         }
682         span++;
683     }
684
685     m_request->didSucceed(results);
686 }
687
688 SpellChecker* InputHandler::getSpellChecker()
689 {
690     if (!m_currentFocusElement || !m_currentFocusElement->document())
691         return 0;
692
693     if (Frame* frame = m_currentFocusElement->document()->frame())
694         if (Editor* editor = frame->editor())
695             return editor->spellChecker();
696
697     return 0;
698 }
699
700 bool InputHandler::shouldRequestSpellCheckingOptionsForPoint(Platform::IntPoint& point, const Element* touchedElement, imf_sp_text_t& spellCheckingOptionRequest)
701 {
702     if (!isActiveTextEdit())
703         return false;
704
705     Element* currentFocusElement = m_currentFocusElement.get();
706     if (!currentFocusElement || !currentFocusElement->isElementNode())
707         return false;
708
709     while (!currentFocusElement->isRootEditableElement()) {
710         Element* parentElement = currentFocusElement->parentElement();
711         if (!parentElement)
712             break;
713         currentFocusElement = parentElement;
714     }
715
716     if (touchedElement != currentFocusElement)
717         return false;
718
719     LayoutPoint contentPos(m_webPage->mapFromViewportToContents(point));
720     contentPos = DOMSupport::convertPointToFrame(m_webPage->mainFrame(), m_webPage->focusedOrMainFrame(), roundedIntPoint(contentPos));
721
722     Document* document = currentFocusElement->document();
723     ASSERT(document);
724
725     RenderedDocumentMarker* marker = document->markers()->renderedMarkerContainingPoint(contentPos, DocumentMarker::Spelling);
726     if (!marker)
727         return false;
728
729     // Populate the marker details in preparation for the request as the marker is
730     // not guaranteed to be valid after the cursor is placed.
731     spellCheckingOptionRequest.startTextPosition = marker->startOffset();
732     spellCheckingOptionRequest.endTextPosition = marker->endOffset();
733
734     SpellingLog(LogLevelInfo, "InputHandler::shouldRequestSpellCheckingOptionsForPoint Found spelling marker at point %d, %d\nMarker start %d end %d",
735         point.x(), point.y(), spellCheckingOptionRequest.startTextPosition, spellCheckingOptionRequest.endTextPosition);
736
737     return true;
738 }
739
740 void InputHandler::requestSpellingCheckingOptions(imf_sp_text_t& spellCheckingOptionRequest, const WebCore::IntSize& screenOffset)
741 {
742     // If the caret is no longer active, no message should be sent.
743     if (m_webPage->focusedOrMainFrame()->selection()->selectionType() != VisibleSelection::CaretSelection)
744         return;
745
746     // imf_sp_text_t should be generated in pixel viewport coordinates.
747     WebCore::IntRect caretRect = m_webPage->focusedOrMainFrame()->selection()->selection().visibleStart().absoluteCaretBounds();
748     caretRect = m_webPage->focusedOrMainFrame()->view()->contentsToRootView(caretRect);
749     const WebCore::IntPoint scrollPosition = m_webPage->mainFrame()->view()->scrollPosition();
750     caretRect.move(scrollPosition.x(), scrollPosition.y());
751
752     // Calculate the offset for contentEditable since the marker offsets are relative to the node.
753     // Get caret position. Though the spelling markers might no longer exist, if this method is called we can assume the caret was placed on top of a marker earlier.
754     VisiblePosition caretPosition = m_currentFocusElement->document()->frame()->selection()->selection().visibleStart();
755
756     // Create a range from the start to end of word.
757     RefPtr<Range> rangeSelection = VisibleSelection(startOfWord(caretPosition), endOfWord(caretPosition)).toNormalizedRange();
758     if (!rangeSelection)
759         return;
760
761     unsigned location = 0;
762     unsigned length = 0;
763     TextIterator::getLocationAndLengthFromRange(m_currentFocusElement.get(), rangeSelection.get(), location, length);
764
765     if (location != notFound && length) {
766         spellCheckingOptionRequest.startTextPosition = location;
767         spellCheckingOptionRequest.endTextPosition = location + length;
768     }
769
770     InputLog(LogLevelInfo, "InputHandler::requestSpellingCheckingOptions caretRect topLeft=(%d,%d), bottomRight=(%d,%d), startTextPosition=%d, endTextPosition=%d"
771                             , caretRect.minXMinYCorner().x(), caretRect.minXMinYCorner().y(), caretRect.maxXMaxYCorner().x(), caretRect.maxXMaxYCorner().y()
772                             , spellCheckingOptionRequest.startTextPosition, spellCheckingOptionRequest.endTextPosition);
773
774     m_webPage->m_client->requestSpellingCheckingOptions(spellCheckingOptionRequest, caretRect, screenOffset);
775 }
776
777 void InputHandler::setElementUnfocused(bool refocusOccuring)
778 {
779     if (isActiveTextEdit()) {
780         FocusLog(LogLevelInfo, "InputHandler::setElementUnfocused");
781
782         // Pass any text into the field to IMF to learn.
783         learnText();
784
785         // End any composition that is in progress.
786         finishComposition();
787
788         // Only hide the keyboard if we aren't refocusing on a new input field.
789         if (!refocusOccuring)
790             notifyClientOfKeyboardVisibilityChange(false, true /* triggeredByFocusChange */);
791
792         m_webPage->m_client->inputFocusLost();
793
794         // If the frame selection isn't focused, focus it.
795         if (!m_currentFocusElement->document()->frame()->selection()->isFocused())
796             m_currentFocusElement->document()->frame()->selection()->setFocused(true);
797     }
798
799     // Clear the node details.
800     m_currentFocusElement = 0;
801     m_currentFocusElementType = TextEdit;
802 }
803
804 bool InputHandler::isInputModeEnabled() const
805 {
806     // Input mode is enabled when set, or when dump render tree or always show keyboard setting is enabled.
807     return m_inputModeEnabled || m_webPage->m_dumpRenderTree || Platform::Settings::instance()->alwaysShowKeyboardOnFocus();
808 }
809
810 void InputHandler::setInputModeEnabled(bool active)
811 {
812     FocusLog(LogLevelInfo, "InputHandler::setInputModeEnabled '%s', override is '%s'"
813              , active ? "true" : "false"
814              , m_webPage->m_dumpRenderTree || Platform::Settings::instance()->alwaysShowKeyboardOnFocus() ? "true" : "false");
815
816     m_inputModeEnabled = active;
817
818     // If the frame selection isn't focused, focus it.
819     if (isInputModeEnabled() && isActiveTextEdit() && !m_currentFocusElement->document()->frame()->selection()->isFocused())
820         m_currentFocusElement->document()->frame()->selection()->setFocused(true);
821 }
822
823 void InputHandler::setElementFocused(Element* element)
824 {
825     ASSERT(DOMSupport::isTextBasedContentEditableElement(element));
826     ASSERT(element && element->document() && element->document()->frame());
827
828 #ifdef ENABLE_SPELLING_LOG
829     BlackBerry::Platform::StopWatch timer;
830     timer.start();
831 #endif
832
833     if (!element || !(element->document()))
834         return;
835
836     Frame* frame = element->document()->frame();
837     if (!frame)
838         return;
839
840     if (frame->selection()->isFocused() != isInputModeEnabled())
841         frame->selection()->setFocused(isInputModeEnabled());
842
843     // Clear the existing focus node details.
844     setElementUnfocused(true /*refocusOccuring*/);
845
846     // Mark this element as active and add to frame set.
847     m_currentFocusElement = element;
848     m_currentFocusElementType = TextEdit;
849
850     // Send details to the client about this element.
851     BlackBerryInputType type = elementType(element);
852     m_currentFocusElementTextEditMask = inputStyle(type, element);
853
854     VirtualKeyboardType keyboardType = keyboardTypeAttribute(element);
855     if (keyboardType == VKBTypeNotSet)
856         keyboardType = convertInputTypeToVKBType(type);
857
858     VirtualKeyboardEnterKeyType enterKeyType = keyboardEnterKeyTypeAttribute(element);
859
860     if (enterKeyType == VKBEnterKeyNotSet && type != InputTypeTextArea) {
861         if (element->isFormControlElement()) {
862             const HTMLFormControlElement* formElement = static_cast<const HTMLFormControlElement*>(element);
863             if (formElement->form() && formElement->form()->defaultButton())
864                 enterKeyType = VKBEnterKeySubmit;
865         }
866     }
867
868     FocusLog(LogLevelInfo, "InputHandler::setElementFocused, Type=%d, Style=%d, Keyboard Type=%d, Enter Key=%d", type, m_currentFocusElementTextEditMask, keyboardType, enterKeyType);
869     m_webPage->m_client->inputFocusGained(m_currentFocusElementTextEditMask, keyboardType, enterKeyType);
870
871     handleInputLocaleChanged(m_webPage->m_webSettings->isWritingDirectionRTL());
872
873     if (!m_delayKeyboardVisibilityChange)
874         notifyClientOfKeyboardVisibilityChange(true, true /* triggeredByFocusChange */);
875
876 #ifdef ENABLE_SPELLING_LOG
877     SpellingLog(LogLevelInfo, "InputHandler::setElementFocused Focusing the field took %f seconds.", timer.elapsed());
878 #endif
879
880     // Check if the field should be spellchecked.
881     if (!shouldSpellCheckElement(element))
882         return;
883
884     // Spellcheck the field in its entirety.
885     VisibleSelection focusedBlock = DOMSupport::visibleSelectionForInputElement(element);
886     spellCheckBlock(focusedBlock, TextCheckingProcessBatch);
887
888 #ifdef ENABLE_SPELLING_LOG
889     SpellingLog(LogLevelInfo, "InputHandler::setElementFocused Spellchecking the field increased the total time to focus to %f seconds.", timer.elapsed());
890 #endif
891 }
892
893 bool InputHandler::shouldSpellCheckElement(const Element* element) const
894 {
895     DOMSupport::AttributeState spellCheckAttr = DOMSupport::elementSupportsSpellCheck(element);
896
897     // Explicitly set to off.
898     if (spellCheckAttr == DOMSupport::Off)
899         return false;
900
901     // Undefined and part of a set of cases which we do not wish to check. This includes user names and email addresses, so we are piggybacking on NoAutocomplete cases.
902     if (spellCheckAttr == DOMSupport::Default && (m_currentFocusElementTextEditMask & NO_AUTO_TEXT))
903         return false;
904
905     return true;
906 }
907
908 void InputHandler::spellCheckBlock(VisibleSelection& visibleSelection, TextCheckingProcessType textCheckingProcessType)
909 {
910     if (!isActiveTextEdit())
911         return;
912
913     RefPtr<Range> rangeForSpellChecking = visibleSelection.toNormalizedRange();
914     if (!rangeForSpellChecking || !rangeForSpellChecking->text() || !rangeForSpellChecking->text().length())
915         return;
916
917     SpellChecker* spellChecker = getSpellChecker();
918     if (!spellChecker) {
919         SpellingLog(LogLevelInfo, "InputHandler::spellCheckBlock Failed to spellcheck the current focused element.");
920         return;
921     }
922
923     // If we have a batch request, try to send off the entire block.
924     if (textCheckingProcessType == TextCheckingProcessBatch) {
925         // If total block text is under the limited amount, send the entire chunk.
926         if (rangeForSpellChecking->text().length() < MaxSpellCheckingStringLength) {
927             spellChecker->requestCheckingFor(SpellCheckRequest::create(TextCheckingTypeSpelling, TextCheckingProcessBatch, rangeForSpellChecking, rangeForSpellChecking));
928             return;
929         }
930     }
931
932     // Since we couldn't check the entire block at once, set up starting and ending markers to fire incrementally.
933     VisiblePosition startPos = visibleSelection.visibleStart();
934     VisiblePosition startOfCurrentLine = startOfLine(startPos);
935     VisiblePosition endOfCurrentLine = endOfLine(startOfCurrentLine);
936
937     while (!isEndOfBlock(startOfCurrentLine)) {
938         // Create a selection with the start and end points of the line, and convert to Range to create a SpellCheckRequest.
939         rangeForSpellChecking = VisibleSelection(startOfCurrentLine, endOfCurrentLine).toNormalizedRange();
940
941         if (rangeForSpellChecking->text().length() < MaxSpellCheckingStringLength) {
942             startOfCurrentLine = nextLinePosition(startOfCurrentLine, startOfCurrentLine.lineDirectionPointForBlockDirectionNavigation());
943             endOfCurrentLine = endOfLine(startOfCurrentLine);
944         } else {
945             // Iterate through words from the start of the line to the end.
946             rangeForSpellChecking = getRangeForSpellCheckWithFineGranularity(startOfCurrentLine, endOfCurrentLine);
947             if (!rangeForSpellChecking) {
948                 SpellingLog(LogLevelWarn, "InputHandler::spellCheckBlock Failed to set text range for spellchecking");
949                 return;
950             }
951             startOfCurrentLine = VisiblePosition(rangeForSpellChecking->endPosition());
952             endOfCurrentLine = endOfLine(startOfCurrentLine);
953             rangeForSpellChecking = DOMSupport::trimWhitespaceFromRange(VisiblePosition(rangeForSpellChecking->startPosition()), VisiblePosition(rangeForSpellChecking->endPosition()));
954         }
955
956         SpellingLog(LogLevelInfo, "InputHandler::spellCheckBlock Substring text is '%s', of size %d", rangeForSpellChecking->text().latin1().data(), rangeForSpellChecking->text().length());
957
958         // Call spellcheck with substring.
959         spellChecker->requestCheckingFor(SpellCheckRequest::create(TextCheckingTypeSpelling, TextCheckingProcessBatch, rangeForSpellChecking, rangeForSpellChecking));
960     }
961 }
962
963 PassRefPtr<Range> InputHandler::getRangeForSpellCheckWithFineGranularity(VisiblePosition startPosition, VisiblePosition endPosition)
964 {
965     VisiblePosition endOfCurrentWord = endOfWord(startPosition);
966
967     // Keep iterating until one of our cases is hit, or we've incremented the starting position right to the end.
968     while (startPosition != endPosition) {
969         // Check the text length within this range.
970         if (VisibleSelection(startPosition, endOfCurrentWord).toNormalizedRange()->text().length() >= MaxSpellCheckingStringLength) {
971             // If this is not the first word, return a Range with end boundary set to the previous word.
972             if (startOfWord(endOfCurrentWord, LeftWordIfOnBoundary) != startPosition && !DOMSupport::isEmptyRangeOrAllSpaces(startPosition, endOfCurrentWord))
973                 return VisibleSelection(startPosition, endOfWord(previousWordPosition(endOfCurrentWord), LeftWordIfOnBoundary)).toNormalizedRange();
974
975             // Our first word has gone over the character limit. Increment the starting position past an uncheckable word.
976             startPosition = endOfCurrentWord;
977             endOfCurrentWord = endOfWord(nextWordPosition(endOfCurrentWord));
978         } else if (endOfCurrentWord == endPosition) {
979             // Return the last segment if the end of our word lies at the end of the range.
980             return VisibleSelection(startPosition, endPosition).toNormalizedRange();
981         } else {
982             // Increment the current word.
983             endOfCurrentWord = endOfWord(nextWordPosition(endOfCurrentWord));
984         }
985     }
986     return 0;
987 }
988
989 bool InputHandler::openDatePopup(HTMLInputElement* element, BlackBerryInputType type)
990 {
991     if (!element || element->disabled() || element->readOnly() || !DOMSupport::isDateTimeInputField(element))
992         return false;
993
994     if (isActiveTextEdit())
995         clearCurrentFocusElement();
996
997     switch (type) {
998     case BlackBerry::Platform::InputTypeDate:
999     case BlackBerry::Platform::InputTypeTime:
1000     case BlackBerry::Platform::InputTypeDateTime:
1001     case BlackBerry::Platform::InputTypeDateTimeLocal:
1002     case BlackBerry::Platform::InputTypeMonth: {
1003         // Date input have button appearance, we hide caret when they get clicked.
1004         element->document()->frame()->selection()->setCaretVisible(false);
1005
1006         // Check if popup already exists, close it if does.
1007         m_webPage->m_page->chrome()->client()->closePagePopup(0);
1008         WTF::String value = element->value();
1009         WTF::String min = element->getAttribute(HTMLNames::minAttr).string();
1010         WTF::String max = element->getAttribute(HTMLNames::maxAttr).string();
1011         double step = element->getAttribute(HTMLNames::stepAttr).toDouble();
1012
1013         DatePickerClient* client = new DatePickerClient(type, value, min, max, step,  m_webPage, element);
1014         return m_webPage->m_page->chrome()->client()->openPagePopup(client,  WebCore::IntRect());
1015         }
1016     default: // Other types not supported
1017         return false;
1018     }
1019 }
1020
1021 bool InputHandler::openColorPopup(HTMLInputElement* element)
1022 {
1023     if (!element || element->disabled() || element->readOnly() || !DOMSupport::isColorInputField(element))
1024         return false;
1025
1026     if (isActiveTextEdit())
1027         clearCurrentFocusElement();
1028
1029     m_currentFocusElement = element;
1030     m_currentFocusElementType = TextPopup;
1031
1032     // Check if popup already exists, close it if does.
1033     m_webPage->m_page->chrome()->client()->closePagePopup(0);
1034
1035     ColorPickerClient* client = new ColorPickerClient(element->value(), m_webPage, element);
1036     return m_webPage->m_page->chrome()->client()->openPagePopup(client,  WebCore::IntRect());
1037 }
1038
1039 void InputHandler::setInputValue(const WTF::String& value)
1040 {
1041     if (!isActiveTextPopup())
1042         return;
1043
1044     HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(m_currentFocusElement.get());
1045     inputElement->setValue(value);
1046     clearCurrentFocusElement();
1047 }
1048
1049 void InputHandler::nodeTextChanged(const Node* node)
1050 {
1051     if (processingChange() || !node || node != m_currentFocusElement || m_receivedBackspaceKeyDown)
1052         return;
1053
1054     InputLog(LogLevelInfo, "InputHandler::nodeTextChanged");
1055
1056     m_webPage->m_client->inputTextChanged();
1057
1058     // Remove the attributed text markers as the previous call triggered an end to
1059     // the composition.
1060     removeAttributedTextMarker();
1061 }
1062
1063 WebCore::IntRect InputHandler::boundingBoxForInputField()
1064 {
1065     if (!isActiveTextEdit())
1066         return WebCore::IntRect();
1067
1068     if (!m_currentFocusElement->renderer())
1069         return WebCore::IntRect();
1070
1071     // type="search" can have a 'X', so take the inner block bounding box to not include it.
1072     if (HTMLInputElement* element = m_currentFocusElement->toInputElement())
1073         if (element->isSearchField())
1074             return element->innerBlockElement()->renderer()->absoluteBoundingBoxRect();
1075
1076     return m_currentFocusElement->renderer()->absoluteBoundingBoxRect();
1077 }
1078
1079 void InputHandler::ensureFocusTextElementVisible(CaretScrollType scrollType)
1080 {
1081     if (!isActiveTextEdit() || !isInputModeEnabled() || !m_currentFocusElement->document())
1082         return;
1083
1084     if (!(Platform::Settings::instance()->allowedScrollAdjustmentForInputFields() & scrollType))
1085         return;
1086
1087     // Fixed position elements cannot be scrolled into view.
1088     if (DOMSupport::isFixedPositionOrHasFixedPositionAncestor(m_currentFocusElement->renderer()))
1089         return;
1090
1091     Frame* elementFrame = m_currentFocusElement->document()->frame();
1092     if (!elementFrame)
1093         return;
1094
1095     Frame* mainFrame = m_webPage->mainFrame();
1096     if (!mainFrame)
1097         return;
1098
1099     FrameView* mainFrameView = mainFrame->view();
1100     if (!mainFrameView)
1101         return;
1102
1103     WebCore::IntRect selectionFocusRect;
1104     switch (elementFrame->selection()->selectionType()) {
1105     case VisibleSelection::CaretSelection:
1106         selectionFocusRect = elementFrame->selection()->absoluteCaretBounds();
1107         break;
1108     case VisibleSelection::RangeSelection: {
1109         Position selectionPosition;
1110         if (m_webPage->m_selectionHandler->lastUpdatedEndPointIsValid())
1111             selectionPosition = elementFrame->selection()->end();
1112         else
1113             selectionPosition = elementFrame->selection()->start();
1114         selectionFocusRect = VisiblePosition(selectionPosition).absoluteCaretBounds();
1115         break;
1116     }
1117     case VisibleSelection::NoSelection:
1118         return;
1119     }
1120
1121     int fontHeight = selectionFocusRect.height();
1122
1123     m_webPage->suspendBackingStore();
1124
1125     // If the text is too small, zoom in to make it a minimum size.
1126     // The minimum size being defined as 3 mm is a good value based on my observations.
1127     static const int s_minimumTextHeightInPixels = Graphics::Screen::primaryScreen()->heightInMMToPixels(3);
1128
1129     double zoomScaleRequired;
1130     if (m_webPage->isUserScalable() && fontHeight && fontHeight * m_webPage->currentScale() < s_minimumTextHeightInPixels && !isRunningDrt())
1131         zoomScaleRequired = static_cast<double>(s_minimumTextHeightInPixels) / fontHeight;
1132     else
1133         zoomScaleRequired = m_webPage->currentScale(); // Don't scale.
1134
1135     // The scroll location we should go to given the zoom required, could be adjusted later.
1136     WebCore::FloatPoint offset(selectionFocusRect.location().x() - m_webPage->scrollPosition().x(), selectionFocusRect.location().y() - m_webPage->scrollPosition().y());
1137     double inverseScale = zoomScaleRequired / m_webPage->currentScale();
1138     WebCore::IntPoint destinationScrollLocation = WebCore::IntPoint(max(0, static_cast<int>(roundf(selectionFocusRect.location().x() - offset.x() / inverseScale))),
1139                                                                     max(0, static_cast<int>(roundf(selectionFocusRect.location().y() - offset.y() / inverseScale))));
1140
1141     if (elementFrame != mainFrame) { // Element is in a subframe.
1142         // Remove any scroll offset within the subframe to get the point relative to the main frame.
1143         selectionFocusRect.move(-elementFrame->view()->scrollPosition().x(), -elementFrame->view()->scrollPosition().y());
1144
1145         // Adjust the selection rect based on the frame offset in relation to the main frame if it's a subframe.
1146         if (elementFrame->ownerRenderer()) {
1147             WebCore::IntPoint frameOffset = elementFrame->ownerRenderer()->absoluteContentBox().location();
1148             selectionFocusRect.move(frameOffset.x(), frameOffset.y());
1149         }
1150     }
1151
1152     Position start = elementFrame->selection()->start();
1153     if (start.anchorNode() && start.anchorNode()->renderer()) {
1154         if (RenderLayer* layer = start.anchorNode()->renderer()->enclosingLayer()) {
1155             // Screen rect after the required zoom.
1156             WebCore::IntRect actualScreenRect = WebCore::IntRect(destinationScrollLocation.x(), destinationScrollLocation.y(), m_webPage->actualVisibleSize().width() / inverseScale, m_webPage->actualVisibleSize().height() / inverseScale);
1157
1158             ScrollAlignment horizontalScrollAlignment = ScrollAlignment::alignToEdgeIfNeeded;
1159             ScrollAlignment verticalScrollAlignment = ScrollAlignment::alignToEdgeIfNeeded;
1160
1161             if (scrollType != EdgeIfNeeded) {
1162                 // Align the selection rect if possible so that we show the field's
1163                 // outline if the caret is at the edge of the field.
1164                 if (RenderObject* focusedRenderer = m_currentFocusElement->renderer()) {
1165                     WebCore::IntRect nodeOutlineBounds = focusedRenderer->absoluteOutlineBounds();
1166                     WebCore::IntRect caretAtEdgeRect = rectForCaret(0);
1167                     int paddingX = abs(caretAtEdgeRect.x() - nodeOutlineBounds.x());
1168                     int paddingY = abs(caretAtEdgeRect.y() - nodeOutlineBounds.y());
1169
1170                     if (selectionFocusRect.x() - paddingX == nodeOutlineBounds.x())
1171                         selectionFocusRect.setX(nodeOutlineBounds.x());
1172                     else if (selectionFocusRect.maxX() + paddingX == nodeOutlineBounds.maxX())
1173                         selectionFocusRect.setX(nodeOutlineBounds.maxX() - selectionFocusRect.width());
1174                     if (selectionFocusRect.y() - paddingY == nodeOutlineBounds.y())
1175                         selectionFocusRect.setY(nodeOutlineBounds.y() - selectionFocusRect.height());
1176                     else if (selectionFocusRect.maxY() + paddingY == nodeOutlineBounds.maxY())
1177                         selectionFocusRect.setY(nodeOutlineBounds.maxY() - selectionFocusRect.height());
1178
1179                     // If the editing point is on the left hand side of the screen when the node's
1180                     // rect is edge aligned, edge align the node rect.
1181                     if (selectionFocusRect.x() - caretAtEdgeRect.x() < actualScreenRect.width() / 2)
1182                         selectionFocusRect.setX(nodeOutlineBounds.x());
1183                     else
1184                         horizontalScrollAlignment = ScrollAlignment::alignCenterIfNeeded;
1185
1186                 }
1187                 verticalScrollAlignment = (scrollType == CenterAlways) ? ScrollAlignment::alignCenterAlways : ScrollAlignment::alignCenterIfNeeded;
1188             }
1189
1190             // Pad the rect to improve the visual appearance.
1191             // Convert the padding back from transformed to ensure a consistent padding regardless of
1192             // zoom level as controls do not zoom.
1193             static const int s_focusRectPaddingSize = Graphics::Screen::primaryScreen()->heightInMMToPixels(3);
1194             selectionFocusRect.inflate(m_webPage->mapFromTransformed(WebCore::IntSize(0, s_focusRectPaddingSize)).height());
1195
1196             WebCore::IntRect revealRect(layer->getRectToExpose(actualScreenRect, selectionFocusRect,
1197                                                                  horizontalScrollAlignment,
1198                                                                  verticalScrollAlignment));
1199
1200             mainFrameView->setConstrainsScrollingToContentEdge(false);
1201             // In order to adjust the scroll position to ensure the focused input field is visible,
1202             // we allow overscrolling. However this overscroll has to be strictly allowed towards the
1203             // bottom of the page on the y axis only, where the virtual keyboard pops up from.
1204             destinationScrollLocation = revealRect.location();
1205             destinationScrollLocation.clampNegativeToZero();
1206             WebCore::IntPoint maximumScrollPosition = WebCore::IntPoint(mainFrameView->contentsWidth() - actualScreenRect.width(), mainFrameView->contentsHeight() - actualScreenRect.height());
1207             destinationScrollLocation = destinationScrollLocation.shrunkTo(maximumScrollPosition);
1208         }
1209     }
1210
1211     if (destinationScrollLocation != mainFrameView->scrollPosition() || zoomScaleRequired != m_webPage->currentScale()) {
1212         mainFrameView->setConstrainsScrollingToContentEdge(true);
1213
1214         InputLog(LogLevelInfo, "InputHandler::ensureFocusTextElementVisible zooming in to %f and scrolling to point %d, %d", zoomScaleRequired, destinationScrollLocation.x(), destinationScrollLocation.y());
1215
1216         // Animate to given scroll position & zoom level
1217         m_webPage->m_finalBlockPoint = WebCore::FloatPoint(destinationScrollLocation);
1218         m_webPage->m_blockZoomFinalScale = zoomScaleRequired;
1219         m_webPage->m_shouldReflowBlock = false;
1220         m_webPage->m_userPerformedManualZoom = true;
1221         m_webPage->m_userPerformedManualScroll = true;
1222         m_webPage->client()->animateBlockZoom(zoomScaleRequired, m_webPage->m_finalBlockPoint);
1223     }
1224     m_webPage->resumeBackingStore();
1225 }
1226
1227 void InputHandler::ensureFocusPluginElementVisible()
1228 {
1229     if (!isActivePlugin() || !m_currentFocusElement->document())
1230         return;
1231
1232     Frame* elementFrame = m_currentFocusElement->document()->frame();
1233     if (!elementFrame)
1234         return;
1235
1236     Frame* mainFrame = m_webPage->mainFrame();
1237     if (!mainFrame)
1238         return;
1239
1240     FrameView* mainFrameView = mainFrame->view();
1241     if (!mainFrameView)
1242         return;
1243
1244     WebCore::IntRect selectionFocusRect;
1245
1246     RenderWidget* renderWidget = static_cast<RenderWidget*>(m_currentFocusElement->renderer());
1247     if (renderWidget) {
1248         PluginView* pluginView = static_cast<PluginView*>(renderWidget->widget());
1249
1250         if (pluginView)
1251             selectionFocusRect = pluginView->ensureVisibleRect();
1252     }
1253
1254     if (selectionFocusRect.isEmpty())
1255         return;
1256
1257     // FIXME: We may need to scroll the subframe (recursively) in the future. Revisit this...
1258     if (elementFrame != mainFrame) { // Element is in a subframe.
1259         // Remove any scroll offset within the subframe to get the point relative to the main frame.
1260         selectionFocusRect.move(-elementFrame->view()->scrollPosition().x(), -elementFrame->view()->scrollPosition().y());
1261
1262         // Adjust the selection rect based on the frame offset in relation to the main frame if it's a subframe.
1263         if (elementFrame->ownerRenderer()) {
1264             WebCore::IntPoint frameOffset = elementFrame->ownerRenderer()->absoluteContentBox().location();
1265             selectionFocusRect.move(frameOffset.x(), frameOffset.y());
1266         }
1267     }
1268
1269     WebCore::IntRect actualScreenRect = WebCore::IntRect(mainFrameView->scrollPosition(), m_webPage->actualVisibleSize());
1270     if (actualScreenRect.contains(selectionFocusRect))
1271         return;
1272
1273     // Calculate a point such that the center of the requested rectangle
1274     // is at the center of the screen. FIXME: If the element was partially on screen
1275     // we might want to just bring the offscreen portion into view, someone needs
1276     // to decide if that's the behavior we want or not.
1277     WebCore::IntPoint pos(selectionFocusRect.center().x() - actualScreenRect.width() / 2,
1278                  selectionFocusRect.center().y() - actualScreenRect.height() / 2);
1279
1280     mainFrameView->setScrollPosition(pos);
1281 }
1282
1283 void InputHandler::ensureFocusElementVisible(bool centerInView)
1284 {
1285     if (isActivePlugin())
1286         ensureFocusPluginElementVisible();
1287     else
1288         ensureFocusTextElementVisible(centerInView ? CenterAlways : CenterIfNeeded);
1289 }
1290
1291 void InputHandler::frameUnloaded(const Frame* frame)
1292 {
1293     if (!isActiveTextEdit())
1294         return;
1295
1296     if (m_currentFocusElement->document()->frame() != frame)
1297         return;
1298
1299     FocusLog(LogLevelInfo, "InputHandler::frameUnloaded");
1300
1301     setElementUnfocused(false /*refocusOccuring*/);
1302 }
1303
1304 void InputHandler::setDelayKeyboardVisibilityChange(bool value)
1305 {
1306     m_delayKeyboardVisibilityChange = value;
1307     m_pendingKeyboardVisibilityChange = NoChange;
1308 }
1309
1310 void InputHandler::processPendingKeyboardVisibilityChange()
1311 {
1312     if (!m_delayKeyboardVisibilityChange) {
1313         ASSERT(m_pendingKeyboardVisibilityChange == NoChange);
1314         return;
1315     }
1316
1317     m_delayKeyboardVisibilityChange = false;
1318
1319     if (m_pendingKeyboardVisibilityChange == NoChange)
1320         return;
1321
1322     notifyClientOfKeyboardVisibilityChange(m_pendingKeyboardVisibilityChange == Visible);
1323     m_pendingKeyboardVisibilityChange = NoChange;
1324 }
1325
1326 void InputHandler::notifyClientOfKeyboardVisibilityChange(bool visible, bool triggeredByFocusChange)
1327 {
1328     // If we aren't ready for input, keyboard changes should be ignored.
1329     if (!isInputModeEnabled() && visible)
1330         return;
1331
1332     // If we are processing a change assume the keyboard is visbile to avoid
1333     // flooding the VKB with show requests.
1334     if (!triggeredByFocusChange && processingChange() && visible)
1335         return;
1336
1337     if (!m_delayKeyboardVisibilityChange) {
1338         m_webPage->showVirtualKeyboard(visible);
1339         return;
1340     }
1341
1342     m_pendingKeyboardVisibilityChange = visible ? Visible : NotVisible;
1343 }
1344
1345 bool InputHandler::selectionAtStartOfElement()
1346 {
1347     if (!isActiveTextEdit())
1348         return false;
1349
1350     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1351
1352     if (!selectionStart())
1353         return true;
1354
1355     return false;
1356 }
1357
1358 bool InputHandler::selectionAtEndOfElement()
1359 {
1360     if (!isActiveTextEdit())
1361         return false;
1362
1363     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1364
1365     return selectionStart() == static_cast<int>(elementText().length());
1366 }
1367
1368 int InputHandler::selectionStart() const
1369 {
1370     return selectionPosition(true);
1371 }
1372
1373 int InputHandler::selectionEnd() const
1374 {
1375     return selectionPosition(false);
1376 }
1377
1378 int InputHandler::selectionPosition(bool start) const
1379 {
1380     if (!m_currentFocusElement->document() || !m_currentFocusElement->document()->frame())
1381         return 0;
1382
1383     if (HTMLTextFormControlElement* controlElement = DOMSupport::toTextControlElement(m_currentFocusElement.get()))
1384         return start ? controlElement->selectionStart() : controlElement->selectionEnd();
1385
1386     FrameSelection caretSelection;
1387     caretSelection.setSelection(m_currentFocusElement->document()->frame()->selection()->selection());
1388     RefPtr<Range> rangeSelection = caretSelection.selection().toNormalizedRange();
1389     if (!rangeSelection)
1390         return 0;
1391
1392     int selectionPointInNode = start ? rangeSelection->startOffset() : rangeSelection->endOffset();
1393     Node* containerNode = start ? rangeSelection->startContainer() : rangeSelection->endContainer();
1394
1395     ExceptionCode ec;
1396     RefPtr<Range> rangeForNode = rangeOfContents(m_currentFocusElement.get());
1397     rangeForNode->setEnd(containerNode, selectionPointInNode, ec);
1398     ASSERT(!ec);
1399
1400     return TextIterator::rangeLength(rangeForNode.get());
1401 }
1402
1403 void InputHandler::selectionChanged()
1404 {
1405     // This method can get called during WebPage shutdown process.
1406     // If that is the case, just bail out since the client is not
1407     // in a safe state of trust to request anything else from it.
1408     if (!m_webPage->m_mainFrame)
1409         return;
1410
1411     if (!isActiveTextEdit())
1412         return;
1413
1414     if (processingChange())
1415         return;
1416
1417     // Scroll the field if necessary. This must be done even if we are processing
1418     // a change as the text change may have moved the caret. IMF doesn't require
1419     // the update, but the user needs to see the caret.
1420     ensureFocusTextElementVisible(EdgeIfNeeded);
1421
1422     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1423
1424     if (m_receivedBackspaceKeyDown)
1425         return;
1426
1427     int newSelectionStart = selectionStart();
1428     int newSelectionEnd = selectionEnd();
1429
1430     InputLog(LogLevelInfo, "InputHandler::selectionChanged selectionStart=%u, selectionEnd=%u", newSelectionStart, newSelectionEnd);
1431
1432     m_webPage->m_client->inputSelectionChanged(newSelectionStart, newSelectionEnd);
1433
1434     // Remove the attributed text markers as the previous call triggered an end to
1435     // the composition.
1436     removeAttributedTextMarker();
1437 }
1438
1439 bool InputHandler::setCursorPosition(int location)
1440 {
1441     return setSelection(location, location);
1442 }
1443
1444 bool InputHandler::setSelection(int start, int end, bool changeIsPartOfComposition)
1445 {
1446     if (!isActiveTextEdit())
1447         return false;
1448
1449     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1450
1451     ProcessingChangeGuard guard(this);
1452
1453     VisibleSelection newSelection = DOMSupport::visibleSelectionForRangeInputElement(m_currentFocusElement.get(), start, end);
1454     m_currentFocusElement->document()->frame()->selection()->setSelection(newSelection, changeIsPartOfComposition ? 0 : FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
1455
1456     InputLog(LogLevelInfo, "InputHandler::setSelection selectionStart=%u, selectionEnd=%u", start, end);
1457
1458     return start == selectionStart() && end == selectionEnd();
1459 }
1460
1461 WebCore::IntRect InputHandler::rectForCaret(int index)
1462 {
1463     if (!isActiveTextEdit())
1464         return WebCore::IntRect();
1465
1466     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1467
1468     if (index < 0 || index > static_cast<int>(elementText().length())) {
1469         // Invalid request.
1470         return WebCore::IntRect();
1471     }
1472
1473     FrameSelection caretSelection;
1474     caretSelection.setSelection(DOMSupport::visibleSelectionForRangeInputElement(m_currentFocusElement.get(), index, index).visibleStart());
1475     caretSelection.modify(FrameSelection::AlterationExtend, DirectionForward, CharacterGranularity);
1476     return caretSelection.selection().visibleStart().absoluteCaretBounds();
1477 }
1478
1479 void InputHandler::cancelSelection()
1480 {
1481     if (!isActiveTextEdit())
1482         return;
1483
1484     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1485
1486     int selectionStartPosition = selectionStart();
1487     ProcessingChangeGuard guard(this);
1488     setCursorPosition(selectionStartPosition);
1489 }
1490
1491 bool InputHandler::handleKeyboardInput(const Platform::KeyboardEvent& keyboardEvent, bool changeIsPartOfComposition)
1492 {
1493     InputLog(LogLevelInfo, "InputHandler::handleKeyboardInput received character=%lc, type=%d", keyboardEvent.character(), keyboardEvent.type());
1494
1495     // Clearing the m_receivedBackspaceKeyDown state on any KeyboardEvent.
1496     m_receivedBackspaceKeyDown = false;
1497
1498     // Enable input mode if we are processing a key event.
1499     setInputModeEnabled();
1500
1501     Platform::KeyboardEvent::Type type = keyboardEvent.type();
1502     /*
1503      * IMF sends us an unadultered KeyUp for all key presses. This key event should be allowed to be processed at all times.
1504      * We bypass the check because the state of composition has no implication on this key event.
1505      * In order to ensure we allow the correct key event through, we keep track of key down events with m_expectedKeyUpChar.
1506     */
1507     if (type == Platform::KeyboardEvent::KeyUp) {
1508         // When IMF auto-capitalizes a KeyDown, say the first letter of a new sentence, our KeyUp will still be in lowercase.
1509         if (m_expectedKeyUpChar == keyboardEvent.character() || (isASCIIUpper(m_expectedKeyUpChar) && m_expectedKeyUpChar == toASCIIUpper(keyboardEvent.character()))) {
1510             m_expectedKeyUpChar = 0;
1511             changeIsPartOfComposition = true;
1512         }
1513     }
1514
1515     // If we aren't specifically part of a composition, fail, IMF should never send key input
1516     // while composing text. If IMF has failed, we should have already finished the
1517     // composition manually. There is a caveat for KeyUp which is explained above.
1518     if (!changeIsPartOfComposition && compositionActive())
1519         return false;
1520
1521     ProcessingChangeGuard guard(this);
1522
1523     unsigned adjustedModifiers = keyboardEvent.modifiers();
1524     if (WTF::isASCIIUpper(keyboardEvent.character()))
1525         adjustedModifiers |= KEYMOD_SHIFT;
1526
1527     ASSERT(m_webPage->m_page->focusController());
1528     bool keyboardEventHandled = false;
1529     if (Frame* focusedFrame = m_webPage->m_page->focusController()->focusedFrame()) {
1530         bool isKeyChar = type == Platform::KeyboardEvent::KeyChar;
1531
1532         // If this is a KeyChar type then we handle it as a keydown followed by a key up.
1533         if (isKeyChar)
1534             type = Platform::KeyboardEvent::KeyDown;
1535         else if (type == Platform::KeyboardEvent::KeyDown) {
1536             m_expectedKeyUpChar = keyboardEvent.character();
1537
1538             // If we receive the KeyDown of a Backspace, set this flag to prevent sending unnecessary selection and caret changes to IMF.
1539             if (keyboardEvent.character() == KEYCODE_BACKSPACE)
1540                 m_receivedBackspaceKeyDown = true;
1541         }
1542
1543         Platform::KeyboardEvent adjustedKeyboardEvent(keyboardEvent.character(), type, adjustedModifiers);
1544         keyboardEventHandled = focusedFrame->eventHandler()->keyEvent(PlatformKeyboardEvent(adjustedKeyboardEvent));
1545
1546         m_receivedBackspaceKeyDown = false;
1547
1548         if (isKeyChar) {
1549             type = Platform::KeyboardEvent::KeyUp;
1550             adjustedKeyboardEvent = Platform::KeyboardEvent(keyboardEvent.character(), type, adjustedModifiers);
1551             keyboardEventHandled = focusedFrame->eventHandler()->keyEvent(PlatformKeyboardEvent(adjustedKeyboardEvent)) || keyboardEventHandled;
1552         }
1553
1554         if (!changeIsPartOfComposition && type == Platform::KeyboardEvent::KeyUp)
1555             ensureFocusTextElementVisible(EdgeIfNeeded);
1556     }
1557     return keyboardEventHandled;
1558 }
1559
1560 bool InputHandler::deleteSelection()
1561 {
1562     if (!isActiveTextEdit())
1563         return false;
1564
1565     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1566     Frame* frame = m_currentFocusElement->document()->frame();
1567
1568     if (frame->selection()->selectionType() != VisibleSelection::RangeSelection)
1569         return false;
1570
1571     ASSERT(frame->editor());
1572     return handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_BACKSPACE, Platform::KeyboardEvent::KeyDown, 0), false /* changeIsPartOfComposition */);
1573 }
1574
1575 void InputHandler::insertText(const WTF::String& string)
1576 {
1577     if (!isActiveTextEdit())
1578         return;
1579
1580     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame() && m_currentFocusElement->document()->frame()->editor());
1581     Editor* editor = m_currentFocusElement->document()->frame()->editor();
1582     editor->command("InsertText").execute(string);
1583 }
1584
1585 void InputHandler::clearField()
1586 {
1587     if (!isActiveTextEdit())
1588         return;
1589
1590     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame() && m_currentFocusElement->document()->frame()->editor());
1591     Editor* editor = m_currentFocusElement->document()->frame()->editor();
1592
1593     editor->command("SelectAll").execute();
1594     editor->command("DeleteBackward").execute();
1595 }
1596
1597 bool InputHandler::executeTextEditCommand(const WTF::String& commandName)
1598 {
1599     ASSERT(m_webPage->focusedOrMainFrame() && m_webPage->focusedOrMainFrame()->editor());
1600     Editor* editor = m_webPage->focusedOrMainFrame()->editor();
1601
1602     return editor->command(commandName).execute();
1603 }
1604
1605 void InputHandler::cut()
1606 {
1607     executeTextEditCommand("Cut");
1608 }
1609
1610 void InputHandler::copy()
1611 {
1612     executeTextEditCommand("Copy");
1613 }
1614
1615 void InputHandler::paste()
1616 {
1617     executeTextEditCommand("Paste");
1618 }
1619
1620 void InputHandler::selectAll()
1621 {
1622     executeTextEditCommand("SelectAll");
1623 }
1624
1625 void InputHandler::addAttributedTextMarker(int start, int end, const AttributeTextStyle& style)
1626 {
1627     if ((end - start) < 1 || end > static_cast<int>(elementText().length()))
1628         return;
1629
1630     RefPtr<Range> markerRange = DOMSupport::visibleSelectionForRangeInputElement(m_currentFocusElement.get(), start, end).toNormalizedRange();
1631     m_currentFocusElement->document()->markers()->addMarker(markerRange.get(), DocumentMarker::AttributeText, WTF::String("Input Marker"), style);
1632 }
1633
1634 void InputHandler::removeAttributedTextMarker()
1635 {
1636     // Remove all attribute text markers.
1637     if (m_currentFocusElement && m_currentFocusElement->document())
1638         m_currentFocusElement->document()->markers()->removeMarkers(DocumentMarker::AttributeText);
1639
1640     m_composingTextStart = 0;
1641     m_composingTextEnd = 0;
1642 }
1643
1644 void InputHandler::handleInputLocaleChanged(bool isRTL)
1645 {
1646     if (!isActiveTextEdit())
1647         return;
1648
1649     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
1650     RenderObject* renderer = m_currentFocusElement->renderer();
1651     if (!renderer)
1652         return;
1653
1654     Editor* editor = m_currentFocusElement->document()->frame()->editor();
1655     ASSERT(editor);
1656     if ((renderer->style()->direction() == RTL) != isRTL)
1657         editor->setBaseWritingDirection(isRTL ? RightToLeftWritingDirection : LeftToRightWritingDirection);
1658 }
1659
1660 void InputHandler::clearCurrentFocusElement()
1661 {
1662     if (m_currentFocusElement)
1663         m_currentFocusElement->blur();
1664 }
1665
1666 bool InputHandler::willOpenPopupForNode(Node* node)
1667 {
1668     // This method must be kept synchronized with InputHandler::didNodeOpenPopup.
1669     if (!node)
1670         return false;
1671
1672     ASSERT(!node->isInShadowTree());
1673
1674     if (node->hasTagName(HTMLNames::selectTag) || node->hasTagName(HTMLNames::optionTag)) {
1675         // We open list popups for options and selects.
1676         return true;
1677     }
1678
1679     if (node->isElementNode()) {
1680         Element* element = static_cast<Element*>(node);
1681         if (DOMSupport::isPopupInputField(element))
1682             return true;
1683     }
1684
1685     return false;
1686 }
1687
1688 bool InputHandler::didNodeOpenPopup(Node* node)
1689 {
1690     // This method must be kept synchronized with InputHandler::willOpenPopupForNode.
1691     if (!node)
1692         return false;
1693
1694     ASSERT(!node->isInShadowTree());
1695
1696     if (node->hasTagName(HTMLNames::selectTag))
1697         return openSelectPopup(static_cast<HTMLSelectElement*>(node));
1698
1699     if (node->hasTagName(HTMLNames::optionTag)) {
1700         HTMLOptionElement* optionElement = static_cast<HTMLOptionElement*>(node);
1701         return openSelectPopup(optionElement->ownerSelectElement());
1702     }
1703
1704     if (HTMLInputElement* element = node->toInputElement()) {
1705         if (DOMSupport::isDateTimeInputField(element))
1706             return openDatePopup(element, elementType(element));
1707
1708         if (DOMSupport::isColorInputField(element))
1709             return openColorPopup(element);
1710     }
1711     return false;
1712 }
1713
1714 bool InputHandler::openSelectPopup(HTMLSelectElement* select)
1715 {
1716     if (!select || select->disabled())
1717         return false;
1718
1719     // If there's no view, do nothing and return.
1720     if (!select->document()->view())
1721         return false;
1722
1723     if (isActiveTextEdit())
1724         clearCurrentFocusElement();
1725
1726     m_currentFocusElement = select;
1727     m_currentFocusElementType = SelectPopup;
1728
1729     const WTF::Vector<HTMLElement*>& listItems = select->listItems();
1730     int size = listItems.size();
1731
1732     bool multiple = select->multiple();
1733     ScopeArray<BlackBerry::Platform::String> labels;
1734     labels.reset(new BlackBerry::Platform::String[size]);
1735
1736     // Check if popup already exists, close it if does.
1737     m_webPage->m_page->chrome()->client()->closePagePopup(0);
1738
1739     bool* enableds = 0;
1740     int* itemTypes = 0;
1741     bool* selecteds = 0;
1742
1743     if (size) {
1744         enableds = new bool[size];
1745         itemTypes = new int[size];
1746         selecteds = new bool[size];
1747         for (int i = 0; i < size; i++) {
1748             if (listItems[i]->hasTagName(HTMLNames::optionTag)) {
1749                 HTMLOptionElement* option = static_cast<HTMLOptionElement*>(listItems[i]);
1750                 labels[i] = option->textIndentedToRespectGroupLabel();
1751                 enableds[i] = option->disabled() ? 0 : 1;
1752                 selecteds[i] = option->selected();
1753                 itemTypes[i] = option->parentNode() && option->parentNode()->hasTagName(HTMLNames::optgroupTag) ? TypeOptionInGroup : TypeOption;
1754             } else if (listItems[i]->hasTagName(HTMLNames::optgroupTag)) {
1755                 HTMLOptGroupElement* optGroup = static_cast<HTMLOptGroupElement*>(listItems[i]);
1756                 labels[i] = optGroup->groupLabelText();
1757                 enableds[i] = optGroup->disabled() ? 0 : 1;
1758                 selecteds[i] = false;
1759                 itemTypes[i] = TypeGroup;
1760             } else if (listItems[i]->hasTagName(HTMLNames::hrTag)) {
1761                 enableds[i] = false;
1762                 selecteds[i] = false;
1763                 itemTypes[i] = TypeSeparator;
1764             }
1765         }
1766     }
1767
1768     SelectPopupClient* selectClient = new SelectPopupClient(multiple, size, labels, enableds, itemTypes, selecteds, m_webPage, select);
1769     WebCore::IntRect elementRectInRootView = select->document()->view()->contentsToRootView(enclosingIntRect(select->getRect()));
1770     // Fail to create HTML popup, use the old path
1771     if (!m_webPage->m_page->chrome()->client()->openPagePopup(selectClient, elementRectInRootView))
1772         m_webPage->m_client->openPopupList(multiple, size, labels, enableds, itemTypes, selecteds);
1773     delete[] enableds;
1774     delete[] itemTypes;
1775     delete[] selecteds;
1776     return true;
1777 }
1778
1779 void InputHandler::setPopupListIndex(int index)
1780 {
1781     if (index == -2) // Abandon
1782         return clearCurrentFocusElement();
1783
1784     if (!isActiveSelectPopup())
1785         return clearCurrentFocusElement();
1786
1787     RenderObject* renderer = m_currentFocusElement->renderer();
1788     if (renderer && renderer->isMenuList()) {
1789         RenderMenuList* renderMenu = toRenderMenuList(renderer);
1790         renderMenu->hidePopup();
1791     }
1792
1793     HTMLSelectElement* selectElement = static_cast<HTMLSelectElement*>(m_currentFocusElement.get());
1794     int optionIndex = selectElement->listToOptionIndex(index);
1795     selectElement->optionSelectedByUser(optionIndex, true /* deselect = true */, true /* fireOnChangeNow = false */);
1796     clearCurrentFocusElement();
1797 }
1798
1799 void InputHandler::setPopupListIndexes(int size, const bool* selecteds)
1800 {
1801     if (!isActiveSelectPopup())
1802         return clearCurrentFocusElement();
1803
1804     if (size < 0)
1805         return;
1806
1807     HTMLSelectElement* selectElement = static_cast<HTMLSelectElement*>(m_currentFocusElement.get());
1808     const WTF::Vector<HTMLElement*>& items = selectElement->listItems();
1809     if (items.size() != static_cast<unsigned int>(size))
1810         return;
1811
1812     HTMLOptionElement* option;
1813     for (int i = 0; i < size; i++) {
1814         if (items[i]->hasTagName(HTMLNames::optionTag)) {
1815             option = static_cast<HTMLOptionElement*>(items[i]);
1816             option->setSelectedState(selecteds[i]);
1817         }
1818     }
1819
1820     // Force repaint because we do not send mouse events to the select element
1821     // and the element doesn't automatically repaint itself.
1822     selectElement->dispatchFormControlChangeEvent();
1823     selectElement->renderer()->repaint();
1824     clearCurrentFocusElement();
1825 }
1826
1827 bool InputHandler::setBatchEditingActive(bool active)
1828 {
1829     if (!isActiveTextEdit())
1830         return false;
1831
1832     ASSERT(m_currentFocusElement->document());
1833     ASSERT(m_currentFocusElement->document()->frame());
1834
1835     // FIXME switch this to m_currentFocusElement->document()->frame() when we have separate
1836     // backingstore for each frame.
1837     BackingStoreClient* backingStoreClient = m_webPage->backingStoreClient();
1838     ASSERT(backingStoreClient);
1839
1840     // Enable / Disable the backingstore to prevent visual updates.
1841     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
1842     if (!active) {
1843         backingStoreClient->backingStore()->resumeBackingStoreUpdates();
1844         backingStoreClient->backingStore()->resumeScreenUpdates(BackingStore::RenderAndBlit);
1845     } else {
1846         backingStoreClient->backingStore()->suspendBackingStoreUpdates();
1847         backingStoreClient->backingStore()->suspendScreenUpdates();
1848     }
1849
1850     return true;
1851 }
1852
1853 int InputHandler::caretPosition() const
1854 {
1855     if (!isActiveTextEdit())
1856         return -1;
1857
1858     // NOTE: This function is expected to return the start of the selection if
1859     // a selection is applied.
1860     return selectionStart();
1861 }
1862
1863 int relativeLeftOffset(int caretPosition, int leftOffset)
1864 {
1865     ASSERT(caretPosition >= 0);
1866
1867     return std::max(0, caretPosition - leftOffset);
1868 }
1869
1870 int relativeRightOffset(int caretPosition, unsigned totalLengthOfText, int rightOffset)
1871 {
1872     ASSERT(caretPosition >= 0);
1873     ASSERT(totalLengthOfText < INT_MAX);
1874
1875     return std::min(caretPosition + rightOffset, static_cast<int>(totalLengthOfText));
1876 }
1877
1878 bool InputHandler::deleteTextRelativeToCursor(int leftOffset, int rightOffset)
1879 {
1880     if (!isActiveTextEdit() || compositionActive())
1881         return false;
1882
1883     ProcessingChangeGuard guard(this);
1884
1885     InputLog(LogLevelInfo, "InputHandler::deleteTextRelativeToCursor left %d right %d", leftOffset, rightOffset);
1886
1887     int caretOffset = caretPosition();
1888     int start = relativeLeftOffset(caretOffset, leftOffset);
1889     int end = relativeRightOffset(caretOffset, elementText().length(), rightOffset);
1890
1891     // If we have backspace in a single character, send this to webkit as a KeyboardEvent. Otherwise, call deleteText.
1892     if (leftOffset == 1 && !rightOffset) {
1893         if (!handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_BACKSPACE, Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */))
1894             return false;
1895     } else if (!deleteText(start, end))
1896         return false;
1897
1898     // Scroll the field if necessary. The automatic update is suppressed
1899     // by the processing change guard.
1900     ensureFocusTextElementVisible(EdgeIfNeeded);
1901
1902     return true;
1903 }
1904
1905 bool InputHandler::deleteText(int start, int end)
1906 {
1907     if (!isActiveTextEdit())
1908         return false;
1909
1910     ProcessingChangeGuard guard(this);
1911
1912     if (end - start == 1)
1913         return handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_BACKSPACE, Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */);
1914
1915     if (!setSelection(start, end, true /*changeIsPartOfComposition*/))
1916         return false;
1917
1918     InputLog(LogLevelInfo, "InputHandler::deleteText start %d end %d", start, end);
1919
1920     return deleteSelection();
1921 }
1922
1923 spannable_string_t* InputHandler::spannableTextInRange(int start, int end, int32_t flags)
1924 {
1925     if (!isActiveTextEdit())
1926         return 0;
1927
1928     if (start == end)
1929         return 0;
1930
1931     ASSERT(end > start);
1932     int length = end - start;
1933
1934     WTF::String textString = elementText().substring(start, length);
1935
1936     spannable_string_t* pst = (spannable_string_t*)fastMalloc(sizeof(spannable_string_t));
1937
1938     // Don't use fastMalloc in case the string is unreasonably long. fastMalloc will
1939     // crash immediately on failure.
1940     pst->str = (wchar_t*)malloc(sizeof(wchar_t) * (length + 1));
1941     if (!pst->str) {
1942         logAlways(LogLevelCritical, "InputHandler::spannableTextInRange Cannot allocate memory for string.");
1943         free(pst);
1944         return 0;
1945     }
1946
1947     int stringLength = 0;
1948     if (!convertStringToWchar(textString, pst->str, length + 1, &stringLength)) {
1949         logAlways(LogLevelCritical, "InputHandler::spannableTextInRange failed to convert string.");
1950         free(pst->str);
1951         free(pst);
1952         return 0;
1953     }
1954
1955     pst->length = stringLength;
1956     pst->spans_count = 0;
1957     pst->spans = 0;
1958
1959     return pst;
1960 }
1961
1962 spannable_string_t* InputHandler::selectedText(int32_t flags)
1963 {
1964     if (!isActiveTextEdit())
1965         return 0;
1966
1967     return spannableTextInRange(selectionStart(), selectionEnd(), flags);
1968 }
1969
1970 spannable_string_t* InputHandler::textBeforeCursor(int32_t length, int32_t flags)
1971 {
1972     if (!isActiveTextEdit())
1973         return 0;
1974
1975     int caretOffset = caretPosition();
1976     int start = relativeLeftOffset(caretOffset, length);
1977     int end = caretOffset;
1978
1979     return spannableTextInRange(start, end, flags);
1980 }
1981
1982 spannable_string_t* InputHandler::textAfterCursor(int32_t length, int32_t flags)
1983 {
1984     if (!isActiveTextEdit())
1985         return 0;
1986
1987     int caretOffset = caretPosition();
1988     int start = caretOffset;
1989     int end = relativeRightOffset(caretOffset, elementText().length(), length);
1990
1991     return spannableTextInRange(start, end, flags);
1992 }
1993
1994 extracted_text_t* InputHandler::extractedTextRequest(extracted_text_request_t* request, int32_t flags)
1995 {
1996     if (!isActiveTextEdit())
1997         return 0;
1998
1999     extracted_text_t* extractedText = (extracted_text_t *)fastMalloc(sizeof(extracted_text_t));
2000
2001     // 'flags' indicates whether the text is being monitored. This is not currently used.
2002
2003     // FIXME add smart limiting based on the hint sizes. Currently return all text.
2004
2005     extractedText->text = spannableTextInRange(0, elementText().length(), flags);
2006
2007     // FIXME confirm these should be 0 on this requested. Text changes will likely require
2008     // the end be the length.
2009     extractedText->partial_start_offset = 0;
2010     extractedText->partial_end_offset = 0;
2011     extractedText->start_offset = 0;
2012
2013     // Adjust selection values relative to the start offset, which may be a subset
2014     // of the text in the field.
2015     extractedText->selection_start = selectionStart() - extractedText->start_offset;
2016     extractedText->selection_end = selectionEnd() - extractedText->start_offset;
2017
2018     // selectionActive is not limited to inside the extracted text.
2019     bool selectionActive = extractedText->selection_start != extractedText->selection_end;
2020     bool singleLine = m_currentFocusElement->hasTagName(HTMLNames::inputTag);
2021
2022     // FIXME flags has two values in doc, enum not in header yet.
2023     extractedText->flags = selectionActive & singleLine;
2024
2025     return extractedText;
2026 }
2027
2028 static void addCompositionTextStyleToAttributeTextStyle(AttributeTextStyle& style)
2029 {
2030     style.setUnderline(AttributeTextStyle::StandardUnderline);
2031 }
2032
2033 static void addActiveTextStyleToAttributeTextStyle(AttributeTextStyle& style)
2034 {
2035     style.setBackgroundColor(Color("blue"));
2036     style.setTextColor(Color("white"));
2037 }
2038
2039 static AttributeTextStyle compositionTextStyle()
2040 {
2041     AttributeTextStyle style;
2042     addCompositionTextStyleToAttributeTextStyle(style);
2043     return style;
2044 }
2045
2046 static AttributeTextStyle textStyleFromMask(int64_t mask)
2047 {
2048     AttributeTextStyle style;
2049     if (mask & COMPOSED_TEXT_ATTRIB)
2050         addCompositionTextStyleToAttributeTextStyle(style);
2051
2052     if (mask & ACTIVE_REGION_ATTRIB)
2053         addActiveTextStyleToAttributeTextStyle(style);
2054
2055     return style;
2056 }
2057
2058 bool InputHandler::removeComposedText()
2059 {
2060     if (compositionActive()) {
2061         if (!deleteText(m_composingTextStart, m_composingTextEnd)) {
2062             // Could not remove the existing composition region.
2063             return false;
2064         }
2065         removeAttributedTextMarker();
2066     }
2067
2068     return true;
2069 }
2070
2071 int32_t InputHandler::setComposingRegion(int32_t start, int32_t end)
2072 {
2073     if (!isActiveTextEdit())
2074         return -1;
2075
2076     if (!removeComposedText()) {
2077         // Could not remove the existing composition region.
2078         return -1;
2079     }
2080
2081     m_composingTextStart = start;
2082     m_composingTextEnd = end;
2083
2084     if (compositionActive())
2085         addAttributedTextMarker(start, end, compositionTextStyle());
2086
2087     InputLog(LogLevelInfo, "InputHandler::setComposingRegion start %d end %d", start, end);
2088
2089     return 0;
2090 }
2091
2092 int32_t InputHandler::finishComposition()
2093 {
2094     if (!isActiveTextEdit())
2095         return -1;
2096
2097     // FIXME if no composition is active, should we return failure -1?
2098     if (!compositionActive())
2099         return 0;
2100
2101     // Remove all markers.
2102     removeAttributedTextMarker();
2103
2104     InputLog(LogLevelInfo, "InputHandler::finishComposition completed");
2105
2106     return 0;
2107 }
2108
2109 span_t* InputHandler::firstSpanInString(spannable_string_t* spannableString, SpannableStringAttribute attrib)
2110 {
2111     span_t* span = spannableString->spans;
2112     for (unsigned int i = 0; i < spannableString->spans_count; i++) {
2113         if (span->attributes_mask & attrib)
2114             return span;
2115         span++;
2116     }
2117
2118     return 0;
2119 }
2120
2121 bool InputHandler::isTrailingSingleCharacter(span_t* span, unsigned stringLength, unsigned composingTextLength)
2122 {
2123     // Make sure the new string is one character larger than the old.
2124     if (composingTextLength != stringLength - 1)
2125         return false;
2126
2127     if (!span)
2128         return false;
2129
2130     // Has only 1 character changed?
2131     if (span->start == span->end) {
2132         // Is this character the last character in the string?
2133         if (span->start == stringLength - 1)
2134             return true;
2135     }
2136     // Return after the first changed_attrib is found.
2137     return false;
2138 }
2139
2140 bool InputHandler::setText(spannable_string_t* spannableString)
2141 {
2142     if (!isActiveTextEdit() || !spannableString)
2143         return false;
2144
2145     ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
2146     Frame* frame = m_currentFocusElement->document()->frame();
2147
2148     Editor* editor = frame->editor();
2149     ASSERT(editor);
2150
2151     // Disable selectionHandler's active selection as we will be resetting and these
2152     // changes should not be handled as notification event.
2153     m_webPage->m_selectionHandler->setSelectionActive(false);
2154
2155     WTF::String textToInsert = convertSpannableStringToString(spannableString);
2156     int textLength = textToInsert.length();
2157
2158     InputLog(LogLevelInfo, "InputHandler::setText spannableString is '%s', of length %d", textToInsert.latin1().data(), textLength);
2159
2160     span_t* changedSpan = firstSpanInString(spannableString, CHANGED_ATTRIB);
2161     int composingTextStart = m_composingTextStart;
2162     int composingTextEnd = m_composingTextEnd;
2163     int composingTextLength = compositionLength();
2164     removeAttributedTextMarker();
2165
2166     if (isTrailingSingleCharacter(changedSpan, textLength, composingTextLength)) {
2167         // If the text is unconverted, do not allow JS processing as it is not a "real"
2168         // character in the field.
2169         if (firstSpanInString(spannableString, UNCONVERTED_TEXT_ATTRIB)) {
2170             InputLog(LogLevelInfo, "InputHandler::setText Single trailing character detected.  Text is unconverted.");
2171             return editor->command("InsertText").execute(textToInsert.right(1));
2172         }
2173         InputLog(LogLevelInfo, "InputHandler::setText Single trailing character detected.");
2174         return handleKeyboardInput(Platform::KeyboardEvent(textToInsert[textLength - 1], Platform::KeyboardEvent::KeyDown, 0), false /* changeIsPartOfComposition */);
2175     }
2176
2177     // If no spans have changed, treat it as a delete operation.
2178     if (!changedSpan) {
2179         // If the composition length is the same as our string length, then we don't need to do anything.
2180         if (composingTextLength == textLength) {
2181             InputLog(LogLevelInfo, "InputHandler::setText No spans have changed. New text is the same length as the old. Nothing to do.");
2182             return true;
2183         }
2184
2185         if (composingTextLength - textLength == 1) {
2186             InputLog(LogLevelInfo, "InputHandler::setText No spans have changed. New text is one character shorter than the old. Treating as 'delete'.");
2187             return handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_BACKSPACE, Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */);
2188         }
2189     }
2190
2191     if (composingTextLength && !setSelection(composingTextStart, composingTextEnd, true /* changeIsPartOfComposition */))
2192         return false;
2193
2194     // If there is no text to add just delete.
2195     if (!textLength) {
2196         if (selectionActive())
2197             return handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_BACKSPACE, Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */);
2198
2199         // Nothing to do.
2200         return true;
2201     }
2202
2203     // Triggering an insert of the text with a space character trailing
2204     // causes new text to adopt the previous text style.
2205     // Remove it and apply it as a keypress later.
2206     // Upstream Webkit bug created https://bugs.webkit.org/show_bug.cgi?id=70823
2207     bool requiresSpaceKeyPress = false;
2208     if (textLength > 0 && textToInsert[textLength - 1] == KEYCODE_SPACE) {
2209         requiresSpaceKeyPress = true;
2210         textLength--;
2211         textToInsert.remove(textLength, 1);
2212     }
2213
2214     InputLog(LogLevelInfo, "InputHandler::setText Request being processed. Text before processing: '%s'", elementText().latin1().data());
2215
2216     if (textLength == 1 && !spannableString->spans_count) {
2217         // Handle single key non-attributed entry as key press rather than insert to allow
2218         // triggering of javascript events.
2219         InputLog(LogLevelInfo, "InputHandler::setText Single character entry treated as key-press in the absense of spans.");
2220         return handleKeyboardInput(Platform::KeyboardEvent(textToInsert[0], Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */);
2221     }
2222
2223     // Perform the text change as a single command if there is one.
2224     if (!textToInsert.isEmpty() && !editor->command("InsertText").execute(textToInsert)) {
2225         InputLog(LogLevelWarn, "InputHandler::setText Failed to insert text '%s'", textToInsert.latin1().data());
2226         return false;
2227     }
2228
2229     if (requiresSpaceKeyPress)
2230         handleKeyboardInput(Platform::KeyboardEvent(KEYCODE_SPACE, Platform::KeyboardEvent::KeyDown, 0), true /* changeIsPartOfComposition */);
2231
2232     InputLog(LogLevelInfo, "InputHandler::setText Request being processed. Text after processing '%s'", elementText().latin1().data());
2233
2234     return true;
2235 }
2236
2237 bool InputHandler::setTextAttributes(int insertionPoint, spannable_string_t* spannableString)
2238 {
2239     // Apply the attributes to the field.
2240     span_t* span = spannableString->spans;
2241     for (unsigned int i = 0; i < spannableString->spans_count; i++) {
2242         unsigned int startPosition = insertionPoint + span->start;
2243         // The end point includes the character that it is before. Ie, 0, 0
2244         // applies to the first character as the end point includes the character
2245         // at the position. This means the endPosition is always +1.
2246         unsigned int endPosition = insertionPoint + span->end + 1;
2247         if (endPosition < startPosition || endPosition > elementText().length())
2248             return false;
2249
2250         if (!span->attributes_mask)
2251             continue; // Nothing to do.
2252
2253         // MISSPELLED_WORD_ATTRIB is present as an option, but it is not currently
2254         // used by IMF. When they add support for on the fly spell checking we can
2255         // use it to apply spelling markers and disable continuous spell checking.
2256
2257         InputLog(LogLevelInfo, "InputHandler::setTextAttributes adding marker %d to %d - %llu", startPosition, endPosition, span->attributes_mask);
2258         addAttributedTextMarker(startPosition, endPosition, textStyleFromMask(span->attributes_mask));
2259
2260         span++;
2261     }
2262
2263     InputLog(LogLevelInfo, "InputHandler::setTextAttributes attribute count %d", spannableString->spans_count);
2264
2265     return true;
2266 }
2267
2268 bool InputHandler::setRelativeCursorPosition(int insertionPoint, int relativeCursorPosition)
2269 {
2270     if (!isActiveTextEdit())
2271         return false;
2272
2273     // 1 place cursor at end of insertion text.
2274     if (relativeCursorPosition == 1) {
2275         m_currentFocusElement->document()->frame()->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
2276         return true;
2277     }
2278
2279     int cursorPosition = 0;
2280     if (relativeCursorPosition <= 0) {
2281         // Zero = insertionPoint
2282         // Negative value, move the cursor the requested number of characters before
2283         // the start of the inserted text.
2284         cursorPosition = insertionPoint + relativeCursorPosition;
2285     } else {
2286         // Positive value, move the cursor the requested number of characters after
2287         // the end of the inserted text minus 1.
2288         cursorPosition = caretPosition() + relativeCursorPosition - 1;
2289     }
2290
2291     if (cursorPosition < 0 || cursorPosition > (int)elementText().length())
2292         return false;
2293
2294     InputLog(LogLevelInfo, "InputHandler::setRelativeCursorPosition cursor position %d", cursorPosition);
2295
2296     return setCursorPosition(cursorPosition);
2297 }
2298
2299 bool InputHandler::setSpannableTextAndRelativeCursor(spannable_string_t* spannableString, int relativeCursorPosition, bool markTextAsComposing)
2300 {
2301     InputLog(LogLevelInfo, "InputHandler::setSpannableTextAndRelativeCursor(%d, %d, %d)", spannableString->length, relativeCursorPosition, markTextAsComposing);
2302     int insertionPoint = compositionActive() ? m_composingTextStart : selectionStart();
2303
2304     ProcessingChangeGuard guard(this);
2305
2306     if (!setText(spannableString))
2307         return false;
2308
2309     if (!setTextAttributes(insertionPoint, spannableString))
2310         return false;
2311
2312     if (!setRelativeCursorPosition(insertionPoint, relativeCursorPosition))
2313         return false;
2314
2315     if (markTextAsComposing) {
2316         m_composingTextStart = insertionPoint;
2317         m_composingTextEnd = insertionPoint + spannableString->length;
2318     }
2319
2320     // Scroll the field if necessary. The automatic update is suppressed
2321     // by the processing change guard.
2322     ensureFocusTextElementVisible(EdgeIfNeeded);
2323
2324     return true;
2325 }
2326
2327 int32_t InputHandler::setComposingText(spannable_string_t* spannableString, int32_t relativeCursorPosition)
2328 {
2329     if (!isActiveTextEdit())
2330         return -1;
2331
2332     if (!spannableString)
2333         return -1;
2334
2335     InputLog(LogLevelInfo, "InputHandler::setComposingText at relativeCursorPosition: %d", relativeCursorPosition);
2336
2337     // Enable input mode if we are processing a key event.
2338     setInputModeEnabled();
2339
2340     return setSpannableTextAndRelativeCursor(spannableString, relativeCursorPosition, true /* markTextAsComposing */) ? 0 : -1;
2341 }
2342
2343 int32_t InputHandler::commitText(spannable_string_t* spannableString, int32_t relativeCursorPosition)
2344 {
2345     if (!isActiveTextEdit())
2346         return -1;
2347
2348     if (!spannableString)
2349         return -1;
2350
2351     InputLog(LogLevelInfo, "InputHandler::commitText");
2352
2353     return setSpannableTextAndRelativeCursor(spannableString, relativeCursorPosition, false /* markTextAsComposing */) ? 0 : -1;
2354 }
2355
2356 }
2357 }