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