1 /*
   2  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "awt_Toolkit.h"
  27 #include "awt_TextArea.h"
  28 #include "awt_TextComponent.h"
  29 #include "awt_Canvas.h"
  30 #include "awt_Window.h"
  31 #include "awt_Frame.h"
  32 
  33 /* IMPORTANT! Read the README.JNI file for notes on JNI converted AWT code.
  34  */
  35 
  36 /***********************************************************************/
  37 // Struct for _ReplaceText() method
  38 struct ReplaceTextStruct {
  39   jobject textComponent;
  40   jstring text;
  41   int start, end;
  42 };
  43 
  44 /************************************************************************
  45  * AwtTextArea fields
  46  */
  47 
  48 jfieldID AwtTextArea::scrollbarVisibilityID;
  49 
  50 /************************************************************************
  51  * AwtTextArea methods
  52  */
  53 
  54 AwtTextArea::AwtTextArea() {
  55     m_bCanUndo        = FALSE;
  56     m_lHDeltaAccum    = 0;
  57     m_lVDeltaAccum    = 0;
  58 }
  59 
  60 AwtTextArea::~AwtTextArea()
  61 {
  62 }
  63 
  64 void AwtTextArea::Dispose()
  65 {
  66     AwtTextComponent::Dispose();
  67 }
  68 
  69 /* Create a new AwtTextArea object and window.   */
  70 AwtTextArea* AwtTextArea::Create(jobject peer, jobject parent)
  71 {
  72     return (AwtTextArea*) AwtTextComponent::Create(peer, parent, true);
  73 }
  74 
  75 void AwtTextArea::EditSetSel(CHARRANGE &cr) {
  76     SendMessage(EM_EXSETSEL, 0, reinterpret_cast<LPARAM>(&cr));
  77     // 6417581: force expected drawing
  78     if (IS_WINVISTA && cr.cpMin == cr.cpMax) {
  79         ::InvalidateRect(GetHWnd(), NULL, TRUE);
  80     }
  81 }
  82 
  83 /* Count how many '\n's are there in jStr */
  84 size_t AwtTextArea::CountNewLines(JNIEnv *env, jstring jStr, size_t maxlen)
  85 {
  86     size_t nNewlines = 0;
  87 
  88     if (jStr == NULL) {
  89         return nNewlines;
  90     }
  91     /*
  92      * Fix for BugTraq Id 4260109.
  93      * Don't use TO_WSTRING since it allocates memory on the stack
  94      * causing stack overflow when the text is very long.
  95      */
  96     size_t length = env->GetStringLength(jStr) + 1;
  97     WCHAR *string = new WCHAR[length];
  98     env->GetStringRegion(jStr, 0, static_cast<jsize>(length - 1), reinterpret_cast<jchar*>(string));
  99     string[length-1] = '\0';
 100     for (size_t i = 0; i < maxlen && i < length - 1; i++) {
 101         if (string[i] == L'\n') {
 102             nNewlines++;
 103         }
 104     }
 105     delete[] string;
 106     return nNewlines;
 107 }
 108 
 109 BOOL AwtTextArea::InheritsNativeMouseWheelBehavior() {return true;}
 110 
 111 
 112 LRESULT
 113 AwtTextArea::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
 114 
 115     LRESULT retValue = 0;
 116     MsgRouting mr = mrDoDefault;
 117 
 118     switch (message) {
 119     case EM_SETCHARFORMAT:
 120     case WM_SETFONT:
 121         SetIgnoreEnChange(TRUE);
 122         break;
 123     }
 124 
 125     retValue = AwtTextComponent::WindowProc(message, wParam, lParam);
 126 
 127     switch (message) {
 128     case EM_SETCHARFORMAT:
 129     case WM_SETFONT:
 130         SetIgnoreEnChange(FALSE);
 131         break;
 132     }
 133 
 134     return retValue;
 135 }
 136 
 137 MsgRouting
 138 AwtTextArea::WmNcHitTest(UINT x, UINT y, LRESULT& retVal)
 139 {
 140     if (::IsWindow(AwtWindow::GetModalBlocker(AwtComponent::GetTopLevelParentForWindow(GetHWnd())))) {
 141         retVal = HTCLIENT;
 142         return mrConsume;
 143     }
 144     return AwtTextComponent::WmNcHitTest(x, y, retVal);
 145 }
 146 
 147 
 148 MsgRouting
 149 AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic)
 150 {
 151     /*
 152      * RichEdit 1.0 control starts internal message loop if the
 153      * left mouse button is pressed while the cursor is not over
 154      * the current selection or the current selection is empty.
 155      * Because of this we don't receive WM_MOUSEMOVE messages
 156      * while the left mouse button is pressed. To work around
 157      * this behavior we process the relevant mouse messages
 158      * by ourselves.
 159      * By consuming WM_MOUSEMOVE messages we also don't give
 160      * the RichEdit control a chance to recognize a drag gesture
 161      * and initiate its own drag-n-drop operation.
 162      *
 163      * The workaround also allows us to implement synthetic focus mechanism.
 164      *
 165      */
 166     if (IsFocusingMouseMessage(msg)) {
 167         CHARRANGE cr;
 168 
 169         LONG lCurPos = EditGetCharFromPos(msg->pt);
 170 
 171         EditGetSel(cr);
 172         /*
 173          * NOTE: Plain EDIT control always clears selection on mouse
 174          * button press. We are clearing the current selection only if
 175          * the mouse pointer is not over the selected region.
 176          * In this case we sacrifice backward compatibility
 177          * to allow dnd of the current selection.
 178          */
 179         if (lCurPos < cr.cpMin || cr.cpMax <= lCurPos) {
 180             if (msg->message == WM_LBUTTONDBLCLK) {
 181                 SetStartSelectionPos(static_cast<LONG>(SendMessage(
 182                     EM_FINDWORDBREAK, WB_MOVEWORDLEFT, lCurPos)));
 183                 SetEndSelectionPos(static_cast<LONG>(SendMessage(
 184                     EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, lCurPos)));
 185             } else {
 186                 SetStartSelectionPos(lCurPos);
 187                 SetEndSelectionPos(lCurPos);
 188             }
 189             cr.cpMin = GetStartSelectionPos();
 190             cr.cpMax = GetEndSelectionPos();
 191             EditSetSel(cr);
 192         }
 193 
 194         delete msg;
 195         return mrConsume;
 196     } else if (msg->message == WM_LBUTTONUP) {
 197 
 198         /*
 199          * If the left mouse button is pressed on the selected region
 200          * we don't clear the current selection. We clear it on button
 201          * release instead. This is to allow dnd of the current selection.
 202          */
 203         if (GetStartSelectionPos() == -1 && GetEndSelectionPos() == -1) {
 204             CHARRANGE cr;
 205 
 206             LONG lCurPos = EditGetCharFromPos(msg->pt);
 207 
 208             cr.cpMin = lCurPos;
 209             cr.cpMax = lCurPos;
 210             EditSetSel(cr);
 211         }
 212 
 213         /*
 214          * Cleanup the state variables when left mouse button is released.
 215          * These state variables are designed to reflect the selection state
 216          * while the left mouse button is pressed and be set to -1 otherwise.
 217          */
 218         SetStartSelectionPos(-1);
 219         SetEndSelectionPos(-1);
 220         SetLastSelectionPos(-1);
 221 
 222         delete msg;
 223         return mrConsume;
 224     } else if (msg->message == WM_MOUSEMOVE && (msg->wParam & MK_LBUTTON)) {
 225 
 226         /*
 227          * We consume WM_MOUSEMOVE while the left mouse button is pressed,
 228          * so we have to simulate selection autoscrolling when mouse is moved
 229          * outside of the client area.
 230          */
 231         POINT p;
 232         p.x = msg->pt.x;
 233         p.y = msg->pt.y;
 234         LONG lCurPos = EditGetCharFromPos(p);
 235 
 236         if (GetStartSelectionPos() != -1 &&
 237             GetEndSelectionPos() != -1 &&
 238             lCurPos != GetLastSelectionPos()) {
 239 
 240             CHARRANGE cr;
 241 
 242             SetLastSelectionPos(lCurPos);
 243 
 244             cr.cpMin = GetStartSelectionPos();
 245             cr.cpMax = GetLastSelectionPos();
 246 
 247             EditSetSel(cr);
 248         }
 249         delete msg;
 250         return mrConsume;
 251     } else if (msg->message == WM_MOUSEWHEEL) {
 252         // 4417236: If there is an old version of RichEd32.dll which
 253         // does not provide the mouse wheel scrolling we have to
 254         // interpret WM_MOUSEWHEEL as a sequence of scroll messages.
 255         // kdm@sparc.spb.su
 256         UINT platfScrollLines = 3;
 257         // Retrieve a number of scroll lines.
 258         ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0,
 259                                &platfScrollLines, 0);
 260 
 261         if (platfScrollLines > 0) {
 262             HWND hWnd = GetHWnd();
 263             LONG styles = ::GetWindowLong(hWnd, GWL_STYLE);
 264 
 265             RECT rect;
 266             // rect.left and rect.top are zero.
 267             // rect.right and rect.bottom contain the width and height
 268             VERIFY(::GetClientRect(hWnd, &rect));
 269 
 270             // calculate a number of visible lines
 271             TEXTMETRIC tm;
 272             HDC hDC = ::GetDC(hWnd);
 273             DASSERT(hDC != NULL);
 274             VERIFY(::GetTextMetrics(hDC, &tm));
 275             VERIFY(::ReleaseDC(hWnd, hDC));
 276             LONG visibleLines = rect.bottom / tm.tmHeight + 1;
 277 
 278             LONG lineCount = static_cast<LONG>(::SendMessage(hWnd,
 279                 EM_GETLINECOUNT, 0, 0));
 280             BOOL sb_vert_disabled = (styles & WS_VSCROLL) == 0
 281               || (lineCount <= visibleLines);
 282 
 283             LONG *delta_accum = &m_lVDeltaAccum;
 284             UINT wm_msg = WM_VSCROLL;
 285             int sb_type = SB_VERT;
 286 
 287             if (sb_vert_disabled && (styles & WS_HSCROLL)) {
 288                 delta_accum = &m_lHDeltaAccum;
 289                 wm_msg = WM_HSCROLL;
 290                 sb_type = SB_HORZ;
 291             }
 292 
 293             int delta = (short) HIWORD(msg->wParam);
 294             *delta_accum += delta;
 295             if (abs(*delta_accum) >= WHEEL_DELTA) {
 296                 if (platfScrollLines == WHEEL_PAGESCROLL) {
 297                     // Synthesize a page down or a page up message.
 298                     ::SendMessage(hWnd, wm_msg,
 299                                   (delta > 0) ? SB_PAGEUP : SB_PAGEDOWN, 0);
 300                     *delta_accum = 0;
 301                 } else {
 302                     // We provide a friendly behavior of text scrolling.
 303                     // During of scrolling the text can be out of the client
 304                     // area's boundary. Here we try to prevent this behavior.
 305                     SCROLLINFO si;
 306                     ::ZeroMemory(&si, sizeof(si));
 307                     si.cbSize = sizeof(SCROLLINFO);
 308                     si.fMask = SIF_POS | SIF_RANGE | SIF_PAGE;
 309                     int actualScrollLines =
 310                         abs((int)(platfScrollLines * (*delta_accum / WHEEL_DELTA)));
 311                     for (int i = 0; i < actualScrollLines; i++) {
 312                         if (::GetScrollInfo(hWnd, sb_type, &si)) {
 313                             if ((wm_msg == WM_VSCROLL)
 314                                 && ((*delta_accum < 0
 315                                      && si.nPos >= (si.nMax - (int) si.nPage))
 316                                     || (*delta_accum > 0
 317                                         && si.nPos <= si.nMin))) {
 318                                 break;
 319                             }
 320                         }
 321                         // Here we don't send EM_LINESCROLL or EM_SCROLL
 322                         // messages to rich edit because it doesn't
 323                         // provide horizontal scrolling.
 324                         // So it's only possible to scroll by 1 line
 325                         // at a time to prevent scrolling when the
 326                         // scrollbar thumb reaches its boundary position.
 327                         ::SendMessage(hWnd, wm_msg,
 328                             (*delta_accum>0) ? SB_LINEUP : SB_LINEDOWN, 0);
 329                     }
 330                     *delta_accum %= WHEEL_DELTA;
 331                 }
 332             } else {
 333                 *delta_accum = 0;
 334             }
 335         }
 336         delete msg;
 337         return mrConsume;
 338         // 4417236: end of fix
 339     }
 340 
 341     return AwtTextComponent::HandleEvent(msg, synthetic);
 342 }
 343 
 344 
 345 /* Fix for 4776535, 4648702
 346  * If width is 0 or 1 Windows hides the horizontal scroll bar even
 347  * if the WS_HSCROLL style is set. It is a bug in Windows.
 348  * As a workaround we should set an initial width to 2.
 349  * kdm@sparc.spb.su
 350  */
 351 void AwtTextArea::Reshape(int x, int y, int w, int h)
 352 {
 353     if (w < 2) {
 354         w = 2;
 355     }
 356     AwtTextComponent::Reshape(x, y, w, h);
 357 }
 358 
 359 LONG AwtTextArea::getJavaSelPos(LONG orgPos)
 360 {
 361     long wlen;
 362     long pos = orgPos;
 363     long cur = 0;
 364     long retval = 0;
 365     LPTSTR wbuf;
 366 
 367     if ((wlen = GetTextLength()) == 0)
 368         return 0;
 369     wbuf = new TCHAR[wlen + 1];
 370     GetText(wbuf, wlen + 1);
 371     if (m_isLFonly == TRUE) {
 372         wlen = RemoveCR(wbuf);
 373     }
 374 
 375     while (cur < pos && cur < wlen) {
 376         if (wbuf[cur] == _T('\r') && wbuf[cur + 1] == _T('\n')) {
 377             pos++;
 378         }
 379         cur++;
 380         retval++;
 381     }
 382     delete[] wbuf;
 383     return retval;
 384 }
 385 
 386 LONG AwtTextArea::getWin32SelPos(LONG orgPos)
 387 {
 388     if (GetTextLength() == 0)
 389        return 0;
 390     return orgPos;
 391 }
 392 
 393 void AwtTextArea::SetSelRange(LONG start, LONG end)
 394 {
 395     CHARRANGE cr;
 396     cr.cpMin = getWin32SelPos(start);
 397     cr.cpMax = getWin32SelPos(end);
 398     EditSetSel(cr);
 399 }
 400 
 401 
 402 void AwtTextArea::_ReplaceText(void *param)
 403 {
 404     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 405 
 406     ReplaceTextStruct *rts = (ReplaceTextStruct *)param;
 407 
 408     jobject textComponent = rts->textComponent;
 409     jstring text = rts->text;
 410     jint start = rts->start;
 411     jint end = rts->end;
 412 
 413     AwtTextComponent *c = NULL;
 414 
 415     PDATA pData;
 416     JNI_CHECK_PEER_GOTO(textComponent, done);
 417     JNI_CHECK_NULL_GOTO(text, "null string", done);
 418 
 419     c = (AwtTextComponent *)pData;
 420     if (::IsWindow(c->GetHWnd()))
 421     {
 422       jsize length = env->GetStringLength(text) + 1;
 423       // Bugid 4141477 - Can't use TO_WSTRING here because it uses alloca
 424       // WCHAR* buffer = TO_WSTRING(text);
 425       TCHAR *buffer = new TCHAR[length];
 426       env->GetStringRegion(text, 0, length-1, reinterpret_cast<jchar*>(buffer));
 427       buffer[length-1] = '\0';
 428 
 429       c->CheckLineSeparator(buffer);
 430       c->RemoveCR(buffer);
 431       // Fix for 5003402: added restoring/hiding selection to enable automatic scrolling
 432       c->SendMessage(EM_HIDESELECTION, FALSE, TRUE);
 433       c->SendMessage(EM_SETSEL, start, end);
 434       c->SendMessage(EM_REPLACESEL, FALSE, (LPARAM)buffer);
 435       c->SendMessage(EM_HIDESELECTION, TRUE, TRUE);
 436 
 437       delete[] buffer;
 438     }
 439 
 440 done:
 441     env->DeleteGlobalRef(textComponent);
 442     env->DeleteGlobalRef(text);
 443 
 444     delete rts;
 445 }
 446 
 447 
 448 /************************************************************************
 449  * TextArea native methods
 450  */
 451 
 452 extern "C" {
 453 
 454 /*
 455  * Class:     java_awt_TextArea
 456  * Method:    initIDs
 457  * Signature: ()V
 458  */
 459 JNIEXPORT void JNICALL
 460 Java_java_awt_TextArea_initIDs(JNIEnv *env, jclass cls)
 461 {
 462     TRY;
 463 
 464     AwtTextArea::scrollbarVisibilityID =
 465         env->GetFieldID(cls, "scrollbarVisibility", "I");
 466 
 467     DASSERT(AwtTextArea::scrollbarVisibilityID != NULL);
 468 
 469     CATCH_BAD_ALLOC;
 470 }
 471 
 472 } /* extern "C" */
 473 
 474 
 475 /************************************************************************
 476  * WTextAreaPeer native methods
 477  */
 478 
 479 extern "C" {
 480 
 481 /*
 482  * Class:     sun_awt_windows_WTextAreaPeer
 483  * Method:    create
 484  * Signature: (Lsun/awt/windows/WComponentPeer;)V
 485  */
 486 JNIEXPORT void JNICALL
 487 Java_sun_awt_windows_WTextAreaPeer_create(JNIEnv *env, jobject self,
 488                                           jobject parent)
 489 {
 490     TRY;
 491 
 492     PDATA pData;
 493     JNI_CHECK_PEER_RETURN(parent);
 494     AwtToolkit::CreateComponent(self, parent,
 495                                 (AwtToolkit::ComponentFactory)
 496                                 AwtTextArea::Create);
 497     JNI_CHECK_PEER_CREATION_RETURN(self);
 498 
 499     CATCH_BAD_ALLOC;
 500 }
 501 
 502 /*
 503  * Class:     sun_awt_windows_WTextAreaPeer
 504  * Method:    replaceRange
 505  * Signature: (Ljava/lang/String;II)V
 506  */
 507 JNIEXPORT void JNICALL
 508 Java_sun_awt_windows_WTextAreaPeer_replaceRange(JNIEnv *env, jobject self,
 509                                                jstring text,
 510                                                jint start, jint end)
 511 {
 512     TRY;
 513 
 514     jobject selfGlobalRef = env->NewGlobalRef(self);
 515     jstring textGlobalRef = (jstring)env->NewGlobalRef(text);
 516 
 517     ReplaceTextStruct *rts = new ReplaceTextStruct;
 518     rts->textComponent = selfGlobalRef;
 519     rts->text = textGlobalRef;
 520     rts->start = start;
 521     rts->end = end;
 522 
 523     AwtToolkit::GetInstance().SyncCall(AwtTextArea::_ReplaceText, rts);
 524     // global refs and rts are deleted in _ReplaceText()
 525 
 526     CATCH_BAD_ALLOC;
 527 }
 528 } /* extern "C" */