applied backgroundcolors.patch
[TortoiseGit.git] / ext / scintilla / win32 / ScintillaWin.cxx
blobd2dfc34300f5798a8c226a37989207d86ac027d8
1 // Scintilla source code edit control
2 /** @file ScintillaWin.cxx
3 ** Windows specific subclass of ScintillaBase.
4 **/
5 // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
8 #include <new>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <stdio.h>
12 #include <ctype.h>
13 #include <assert.h>
14 #include <limits.h>
16 #include <string>
17 #include <vector>
18 #include <map>
20 #undef _WIN32_WINNT
21 #define _WIN32_WINNT 0x0500
22 #include <windows.h>
23 #include <commctrl.h>
24 #include <richedit.h>
25 #include <windowsx.h>
27 #if defined(_MSC_VER) && (_MSC_VER > 1200)
28 #define USE_D2D 1
29 #endif
31 #if defined(USE_D2D)
32 #include <d2d1.h>
33 #include <dwrite.h>
34 #endif
36 #include "Platform.h"
38 #include "ILexer.h"
39 #include "Scintilla.h"
41 #ifdef SCI_LEXER
42 #include "SciLexer.h"
43 #include "LexerModule.h"
44 #endif
45 #include "SplitVector.h"
46 #include "Partitioning.h"
47 #include "RunStyles.h"
48 #include "ContractionState.h"
49 #include "CellBuffer.h"
50 #include "CallTip.h"
51 #include "KeyMap.h"
52 #include "Indicator.h"
53 #include "XPM.h"
54 #include "LineMarker.h"
55 #include "Style.h"
56 #include "AutoComplete.h"
57 #include "ViewStyle.h"
58 #include "CharClassify.h"
59 #include "Decoration.h"
60 #include "Document.h"
61 #include "Selection.h"
62 #include "PositionCache.h"
63 #include "Editor.h"
64 #include "ScintillaBase.h"
65 #include "UniConversion.h"
66 #include "PlatWin.h"
68 #ifdef SCI_LEXER
69 #include "ExternalLexer.h"
70 #endif
72 #ifndef SPI_GETWHEELSCROLLLINES
73 #define SPI_GETWHEELSCROLLLINES 104
74 #endif
76 #ifndef WM_UNICHAR
77 #define WM_UNICHAR 0x0109
78 #endif
80 #ifndef UNICODE_NOCHAR
81 #define UNICODE_NOCHAR 0xFFFF
82 #endif
84 #ifndef WM_IME_STARTCOMPOSITION
85 #include <imm.h>
86 #endif
88 #include <commctrl.h>
89 #ifndef __DMC__
90 #include <zmouse.h>
91 #endif
92 #include <ole2.h>
94 #ifndef MK_ALT
95 #define MK_ALT 32
96 #endif
98 #define SC_WIN_IDLE 5001
100 typedef BOOL (WINAPI *TrackMouseEventSig)(LPTRACKMOUSEEVENT);
102 // GCC has trouble with the standard COM ABI so do it the old C way with explicit vtables.
104 const TCHAR scintillaClassName[] = TEXT("Scintilla");
105 const TCHAR callClassName[] = TEXT("CallTip");
107 #ifdef SCI_NAMESPACE
108 using namespace Scintilla;
109 #endif
111 // Take care of 32/64 bit pointers
112 #ifdef GetWindowLongPtr
113 static void *PointerFromWindow(HWND hWnd) {
114 return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
116 static void SetWindowPointer(HWND hWnd, void *ptr) {
117 ::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
119 static void SetWindowID(HWND hWnd, int identifier) {
120 ::SetWindowLongPtr(hWnd, GWLP_ID, identifier);
122 #else
123 static void *PointerFromWindow(HWND hWnd) {
124 return reinterpret_cast<void *>(::GetWindowLong(hWnd, 0));
126 static void SetWindowPointer(HWND hWnd, void *ptr) {
127 ::SetWindowLong(hWnd, 0, reinterpret_cast<LONG>(ptr));
129 static void SetWindowID(HWND hWnd, int identifier) {
130 ::SetWindowLong(hWnd, GWL_ID, identifier);
132 #endif
134 class ScintillaWin; // Forward declaration for COM interface subobjects
136 typedef void VFunction(void);
140 class FormatEnumerator {
141 public:
142 VFunction **vtbl;
143 int ref;
144 int pos;
145 CLIPFORMAT formats[2];
146 int formatsLen;
147 FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_);
152 class DropSource {
153 public:
154 VFunction **vtbl;
155 ScintillaWin *sci;
156 DropSource();
161 class DataObject {
162 public:
163 VFunction **vtbl;
164 ScintillaWin *sci;
165 DataObject();
170 class DropTarget {
171 public:
172 VFunction **vtbl;
173 ScintillaWin *sci;
174 DropTarget();
179 class ScintillaWin :
180 public ScintillaBase {
182 bool lastKeyDownConsumed;
184 bool capturedMouse;
185 bool trackedMouseLeave;
186 TrackMouseEventSig TrackMouseEventFn;
188 unsigned int linesPerScroll; ///< Intellimouse support
189 int wheelDelta; ///< Wheel delta from roll
191 HRGN hRgnUpdate;
193 bool hasOKText;
195 CLIPFORMAT cfColumnSelect;
196 CLIPFORMAT cfLineSelect;
198 HRESULT hrOle;
199 DropSource ds;
200 DataObject dob;
201 DropTarget dt;
203 static HINSTANCE hInstance;
205 #if defined(USE_D2D)
206 ID2D1HwndRenderTarget *pRenderTarget;
207 bool renderTargetValid;
208 #endif
210 ScintillaWin(HWND hwnd);
211 ScintillaWin(const ScintillaWin &);
212 virtual ~ScintillaWin();
213 ScintillaWin &operator=(const ScintillaWin &);
215 virtual void Initialise();
216 virtual void Finalise();
217 void EnsureRenderTarget();
218 void DropRenderTarget();
219 HWND MainHWND();
221 static sptr_t DirectFunction(
222 ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam);
223 static sptr_t PASCAL SWndProc(
224 HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
225 static sptr_t PASCAL CTWndProc(
226 HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
228 enum { invalidTimerID, standardTimerID, idleTimerID };
230 virtual bool DragThreshold(Point ptStart, Point ptNow);
231 virtual void StartDrag();
232 sptr_t WndPaint(uptr_t wParam);
233 sptr_t HandleComposition(uptr_t wParam, sptr_t lParam);
234 UINT CodePageOfDocument();
235 virtual bool ValidCodePage(int codePage) const;
236 virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
237 virtual bool SetIdle(bool on);
238 virtual void SetTicking(bool on);
239 virtual void SetMouseCapture(bool on);
240 virtual bool HaveMouseCapture();
241 virtual void SetTrackMouseLeaveEvent(bool on);
242 virtual bool PaintContains(PRectangle rc);
243 virtual void ScrollText(int linesToMove);
244 virtual void UpdateSystemCaret();
245 virtual void SetVerticalScrollPos();
246 virtual void SetHorizontalScrollPos();
247 virtual bool ModifyScrollBars(int nMax, int nPage);
248 virtual void NotifyChange();
249 virtual void NotifyFocus(bool focus);
250 virtual void SetCtrlID(int identifier);
251 virtual int GetCtrlID();
252 virtual void NotifyParent(SCNotification scn);
253 virtual void NotifyParent(SCNotification * scn);
254 virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt);
255 virtual CaseFolder *CaseFolderForEncoding();
256 virtual std::string CaseMapString(const std::string &s, int caseMapping);
257 virtual void Copy();
258 virtual void CopyAllowLine();
259 virtual bool CanPaste();
260 virtual void Paste();
261 virtual void CreateCallTipWindow(PRectangle rc);
262 virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
263 virtual void ClaimSelection();
265 // DBCS
266 void ImeStartComposition();
267 void ImeEndComposition();
269 void AddCharBytes(char b0, char b1);
271 void GetIntelliMouseParameters();
272 virtual void CopyToClipboard(const SelectionText &selectedText);
273 void ScrollMessage(WPARAM wParam);
274 void HorizontalScrollMessage(WPARAM wParam);
275 void FullPaint();
276 void FullPaintDC(HDC dc);
277 bool IsCompatibleDC(HDC dc);
278 DWORD EffectFromState(DWORD grfKeyState);
280 virtual int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw);
281 virtual bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi);
282 void ChangeScrollPos(int barType, int pos);
284 void InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine);
286 public:
287 // Public for benefit of Scintilla_DirectFunction
288 virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
290 /// Implement IUnknown
291 STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv);
292 STDMETHODIMP_(ULONG)AddRef();
293 STDMETHODIMP_(ULONG)Release();
295 /// Implement IDropTarget
296 STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
297 POINTL pt, PDWORD pdwEffect);
298 STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect);
299 STDMETHODIMP DragLeave();
300 STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
301 POINTL pt, PDWORD pdwEffect);
303 /// Implement important part of IDataObject
304 STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM);
306 static bool Register(HINSTANCE hInstance_);
307 static bool Unregister();
309 friend class DropSource;
310 friend class DataObject;
311 friend class DropTarget;
312 bool DragIsRectangularOK(CLIPFORMAT fmt) {
313 return drag.rectangular && (fmt == cfColumnSelect);
316 private:
317 // For use in creating a system caret
318 bool HasCaretSizeChanged();
319 BOOL CreateSystemCaret();
320 BOOL DestroySystemCaret();
321 HBITMAP sysCaretBitmap;
322 int sysCaretWidth;
323 int sysCaretHeight;
324 bool keysAlwaysUnicode;
327 HINSTANCE ScintillaWin::hInstance = 0;
329 ScintillaWin::ScintillaWin(HWND hwnd) {
331 lastKeyDownConsumed = false;
333 capturedMouse = false;
334 trackedMouseLeave = false;
335 TrackMouseEventFn = 0;
337 linesPerScroll = 0;
338 wheelDelta = 0; // Wheel delta from roll
340 hRgnUpdate = 0;
342 hasOKText = false;
344 // There does not seem to be a real standard for indicating that the clipboard
345 // contains a rectangular selection, so copy Developer Studio.
346 cfColumnSelect = static_cast<CLIPFORMAT>(
347 ::RegisterClipboardFormat(TEXT("MSDEVColumnSelect")));
349 // Likewise for line-copy (copies a full line when no text is selected)
350 cfLineSelect = static_cast<CLIPFORMAT>(
351 ::RegisterClipboardFormat(TEXT("MSDEVLineSelect")));
353 hrOle = E_FAIL;
355 wMain = hwnd;
357 dob.sci = this;
358 ds.sci = this;
359 dt.sci = this;
361 sysCaretBitmap = 0;
362 sysCaretWidth = 0;
363 sysCaretHeight = 0;
365 #if defined(USE_D2D)
366 pRenderTarget = 0;
367 renderTargetValid = true;
368 #endif
370 keysAlwaysUnicode = false;
372 caret.period = ::GetCaretBlinkTime();
373 if (caret.period < 0)
374 caret.period = 0;
376 Initialise();
379 ScintillaWin::~ScintillaWin() {}
381 void ScintillaWin::Initialise() {
382 // Initialize COM. If the app has already done this it will have
383 // no effect. If the app hasnt, we really shouldnt ask them to call
384 // it just so this internal feature works.
385 hrOle = ::OleInitialize(NULL);
387 // Find TrackMouseEvent which is available on Windows > 95
388 HMODULE user32 = ::GetModuleHandle(TEXT("user32.dll"));
389 TrackMouseEventFn = (TrackMouseEventSig)::GetProcAddress(user32, "TrackMouseEvent");
390 if (TrackMouseEventFn == NULL) {
391 // Windows 95 has an emulation in comctl32.dll:_TrackMouseEvent
392 HMODULE commctrl32 = ::LoadLibrary(TEXT("comctl32.dll"));
393 if (commctrl32 != NULL) {
394 TrackMouseEventFn = (TrackMouseEventSig)
395 ::GetProcAddress(commctrl32, "_TrackMouseEvent");
400 void ScintillaWin::Finalise() {
401 ScintillaBase::Finalise();
402 SetTicking(false);
403 SetIdle(false);
404 DropRenderTarget();
405 ::RevokeDragDrop(MainHWND());
406 if (SUCCEEDED(hrOle)) {
407 ::OleUninitialize();
411 void ScintillaWin::EnsureRenderTarget() {
412 #if defined(USE_D2D)
413 if (!renderTargetValid) {
414 DropRenderTarget();
415 renderTargetValid = true;
417 if (pD2DFactory && !pRenderTarget) {
418 RECT rc;
419 HWND hw = MainHWND();
420 GetClientRect(hw, &rc);
422 D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
424 // Create a Direct2D render target.
425 #if 1
426 pD2DFactory->CreateHwndRenderTarget(
427 D2D1::RenderTargetProperties(),
428 D2D1::HwndRenderTargetProperties(hw, size),
429 &pRenderTarget);
430 #else
431 pD2DFactory->CreateHwndRenderTarget(
432 D2D1::RenderTargetProperties(
433 D2D1_RENDER_TARGET_TYPE_DEFAULT ,
434 D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
435 96.0f, 96.0f, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_DEFAULT),
436 D2D1::HwndRenderTargetProperties(hw, size),
437 &pRenderTarget);
438 #endif
439 // Pixmaps were created to be compatible with previous render target so
440 // need to be recreated.
441 DropGraphics(false);
443 #endif
446 void ScintillaWin::DropRenderTarget() {
447 #if defined(USE_D2D)
448 if (pRenderTarget) {
449 pRenderTarget->Release();
450 pRenderTarget = 0;
452 #endif
455 HWND ScintillaWin::MainHWND() {
456 return reinterpret_cast<HWND>(wMain.GetID());
459 bool ScintillaWin::DragThreshold(Point ptStart, Point ptNow) {
460 int xMove = abs(ptStart.x - ptNow.x);
461 int yMove = abs(ptStart.y - ptNow.y);
462 return (xMove > ::GetSystemMetrics(SM_CXDRAG)) ||
463 (yMove > ::GetSystemMetrics(SM_CYDRAG));
466 void ScintillaWin::StartDrag() {
467 inDragDrop = ddDragging;
468 DWORD dwEffect = 0;
469 dropWentOutside = true;
470 IDataObject *pDataObject = reinterpret_cast<IDataObject *>(&dob);
471 IDropSource *pDropSource = reinterpret_cast<IDropSource *>(&ds);
472 //Platform::DebugPrintf("About to DoDragDrop %x %x\n", pDataObject, pDropSource);
473 HRESULT hr = ::DoDragDrop(
474 pDataObject,
475 pDropSource,
476 DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
477 //Platform::DebugPrintf("DoDragDrop = %x\n", hr);
478 if (SUCCEEDED(hr)) {
479 if ((hr == DRAGDROP_S_DROP) && (dwEffect == DROPEFFECT_MOVE) && dropWentOutside) {
480 // Remove dragged out text
481 ClearSelection();
484 inDragDrop = ddNone;
485 SetDragPosition(SelectionPosition(invalidPosition));
488 // Avoid warnings everywhere for old style casts by concentrating them here
489 static WORD LoWord(DWORD l) {
490 return LOWORD(l);
493 static WORD HiWord(DWORD l) {
494 return HIWORD(l);
497 static int InputCodePage() {
498 HKL inputLocale = ::GetKeyboardLayout(0);
499 LANGID inputLang = LOWORD(inputLocale);
500 char sCodePage[10];
501 int res = ::GetLocaleInfoA(MAKELCID(inputLang, SORT_DEFAULT),
502 LOCALE_IDEFAULTANSICODEPAGE, sCodePage, sizeof(sCodePage));
503 if (!res)
504 return 0;
505 return atoi(sCodePage);
508 #ifndef VK_OEM_2
509 static const int VK_OEM_2=0xbf;
510 static const int VK_OEM_3=0xc0;
511 static const int VK_OEM_4=0xdb;
512 static const int VK_OEM_5=0xdc;
513 static const int VK_OEM_6=0xdd;
514 #endif
516 /** Map the key codes to their equivalent SCK_ form. */
517 static int KeyTranslate(int keyIn) {
518 //PLATFORM_ASSERT(!keyIn);
519 switch (keyIn) {
520 case VK_DOWN: return SCK_DOWN;
521 case VK_UP: return SCK_UP;
522 case VK_LEFT: return SCK_LEFT;
523 case VK_RIGHT: return SCK_RIGHT;
524 case VK_HOME: return SCK_HOME;
525 case VK_END: return SCK_END;
526 case VK_PRIOR: return SCK_PRIOR;
527 case VK_NEXT: return SCK_NEXT;
528 case VK_DELETE: return SCK_DELETE;
529 case VK_INSERT: return SCK_INSERT;
530 case VK_ESCAPE: return SCK_ESCAPE;
531 case VK_BACK: return SCK_BACK;
532 case VK_TAB: return SCK_TAB;
533 case VK_RETURN: return SCK_RETURN;
534 case VK_ADD: return SCK_ADD;
535 case VK_SUBTRACT: return SCK_SUBTRACT;
536 case VK_DIVIDE: return SCK_DIVIDE;
537 case VK_LWIN: return SCK_WIN;
538 case VK_RWIN: return SCK_RWIN;
539 case VK_APPS: return SCK_MENU;
540 case VK_OEM_2: return '/';
541 case VK_OEM_3: return '`';
542 case VK_OEM_4: return '[';
543 case VK_OEM_5: return '\\';
544 case VK_OEM_6: return ']';
545 default: return keyIn;
549 LRESULT ScintillaWin::WndPaint(uptr_t wParam) {
550 //ElapsedTime et;
552 // Redirect assertions to debug output and save current state
553 bool assertsPopup = Platform::ShowAssertionPopUps(false);
554 paintState = painting;
555 PAINTSTRUCT ps;
556 PAINTSTRUCT *pps;
558 bool IsOcxCtrl = (wParam != 0); // if wParam != 0, it contains
559 // a PAINSTRUCT* from the OCX
560 // Removed since this interferes with reporting other assertions as it occurs repeatedly
561 //PLATFORM_ASSERT(hRgnUpdate == NULL);
562 hRgnUpdate = ::CreateRectRgn(0, 0, 0, 0);
563 if (IsOcxCtrl) {
564 pps = reinterpret_cast<PAINTSTRUCT*>(wParam);
565 } else {
566 ::GetUpdateRgn(MainHWND(), hRgnUpdate, FALSE);
567 pps = &ps;
568 ::BeginPaint(MainHWND(), pps);
570 if (technology == SC_TECHNOLOGY_DEFAULT) {
571 AutoSurface surfaceWindow(pps->hdc, this);
572 if (surfaceWindow) {
573 rcPaint = PRectangle(pps->rcPaint.left, pps->rcPaint.top, pps->rcPaint.right, pps->rcPaint.bottom);
574 PRectangle rcClient = GetClientRectangle();
575 paintingAllText = rcPaint.Contains(rcClient);
576 Paint(surfaceWindow, rcPaint);
577 surfaceWindow->Release();
579 } else {
580 #if defined(USE_D2D)
581 EnsureRenderTarget();
582 AutoSurface surfaceWindow(pRenderTarget, this);
583 if (surfaceWindow) {
584 pRenderTarget->BeginDraw();
585 rcPaint = PRectangle(pps->rcPaint.left, pps->rcPaint.top, pps->rcPaint.right, pps->rcPaint.bottom);
586 PRectangle rcClient = GetClientRectangle();
587 paintingAllText = rcPaint.Contains(rcClient);
588 if (paintingAllText) {
589 //Platform::DebugPrintf("Performing full text paint\n");
590 } else {
591 //Platform::DebugPrintf("Performing partial paint %d .. %d\n", rcPaint.top, rcPaint.bottom);
593 Paint(surfaceWindow, rcPaint);
594 surfaceWindow->Release();
595 HRESULT hr = pRenderTarget->EndDraw();
596 if (hr == D2DERR_RECREATE_TARGET) {
597 DropRenderTarget();
600 #endif
602 if (hRgnUpdate) {
603 ::DeleteRgn(hRgnUpdate);
604 hRgnUpdate = 0;
607 if (!IsOcxCtrl)
608 ::EndPaint(MainHWND(), pps);
609 if (paintState == paintAbandoned) {
610 // Painting area was insufficient to cover new styling or brace highlight positions
611 FullPaint();
613 paintState = notPainting;
615 // Restore debug output state
616 Platform::ShowAssertionPopUps(assertsPopup);
618 //Platform::DebugPrintf("Paint took %g\n", et.Duration());
619 return 0l;
622 sptr_t ScintillaWin::HandleComposition(uptr_t wParam, sptr_t lParam) {
623 #ifdef __DMC__
624 // Digital Mars compiler does not include Imm library
625 return 0;
626 #else
627 if (lParam & GCS_RESULTSTR) {
628 HIMC hIMC = ::ImmGetContext(MainHWND());
629 if (hIMC) {
630 const int maxLenInputIME = 200;
631 wchar_t wcs[maxLenInputIME];
632 LONG bytes = ::ImmGetCompositionStringW(hIMC,
633 GCS_RESULTSTR, wcs, (maxLenInputIME-1)*2);
634 int wides = bytes / 2;
635 if (IsUnicodeMode()) {
636 char utfval[maxLenInputIME * 3];
637 unsigned int len = UTF8Length(wcs, wides);
638 UTF8FromUTF16(wcs, wides, utfval, len);
639 utfval[len] = '\0';
640 AddCharUTF(utfval, len);
641 } else {
642 char dbcsval[maxLenInputIME * 2];
643 int size = ::WideCharToMultiByte(InputCodePage(),
644 0, wcs, wides, dbcsval, sizeof(dbcsval) - 1, 0, 0);
645 for (int i=0; i<size; i++) {
646 AddChar(dbcsval[i]);
649 // Set new position after converted
650 Point pos = PointMainCaret();
651 COMPOSITIONFORM CompForm;
652 CompForm.dwStyle = CFS_POINT;
653 CompForm.ptCurrentPos.x = pos.x;
654 CompForm.ptCurrentPos.y = pos.y;
655 ::ImmSetCompositionWindow(hIMC, &CompForm);
656 ::ImmReleaseContext(MainHWND(), hIMC);
658 return 0;
660 return ::DefWindowProc(MainHWND(), WM_IME_COMPOSITION, wParam, lParam);
661 #endif
664 // Translate message IDs from WM_* and EM_* to SCI_* so can partly emulate Windows Edit control
665 static unsigned int SciMessageFromEM(unsigned int iMessage) {
666 switch (iMessage) {
667 case EM_CANPASTE: return SCI_CANPASTE;
668 case EM_CANUNDO: return SCI_CANUNDO;
669 case EM_EMPTYUNDOBUFFER: return SCI_EMPTYUNDOBUFFER;
670 case EM_FINDTEXTEX: return SCI_FINDTEXT;
671 case EM_FORMATRANGE: return SCI_FORMATRANGE;
672 case EM_GETFIRSTVISIBLELINE: return SCI_GETFIRSTVISIBLELINE;
673 case EM_GETLINECOUNT: return SCI_GETLINECOUNT;
674 case EM_GETSELTEXT: return SCI_GETSELTEXT;
675 case EM_GETTEXTRANGE: return SCI_GETTEXTRANGE;
676 case EM_HIDESELECTION: return SCI_HIDESELECTION;
677 case EM_LINEINDEX: return SCI_POSITIONFROMLINE;
678 case EM_LINESCROLL: return SCI_LINESCROLL;
679 case EM_REPLACESEL: return SCI_REPLACESEL;
680 case EM_SCROLLCARET: return SCI_SCROLLCARET;
681 case EM_SETREADONLY: return SCI_SETREADONLY;
682 case WM_CLEAR: return SCI_CLEAR;
683 case WM_COPY: return SCI_COPY;
684 case WM_CUT: return SCI_CUT;
685 case WM_GETTEXT: return SCI_GETTEXT;
686 case WM_SETTEXT: return SCI_SETTEXT;
687 case WM_GETTEXTLENGTH: return SCI_GETTEXTLENGTH;
688 case WM_PASTE: return SCI_PASTE;
689 case WM_UNDO: return SCI_UNDO;
691 return iMessage;
694 static UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage) {
695 if (documentCodePage == SC_CP_UTF8) {
696 // The system calls here are a little slow so avoid if known case.
697 return SC_CP_UTF8;
699 CHARSETINFO ci = { 0, 0, { { 0, 0, 0, 0 }, { 0, 0 } } };
700 BOOL bci = ::TranslateCharsetInfo((DWORD*)characterSet,
701 &ci, TCI_SRCCHARSET);
703 UINT cp;
704 if (bci)
705 cp = ci.ciACP;
706 else
707 cp = documentCodePage;
709 CPINFO cpi;
710 if (!IsValidCodePage(cp) && !GetCPInfo(cp, &cpi))
711 cp = CP_ACP;
713 return cp;
716 UINT ScintillaWin::CodePageOfDocument() {
717 return CodePageFromCharSet(vs.styles[STYLE_DEFAULT].characterSet, pdoc->dbcsCodePage);
720 sptr_t ScintillaWin::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
721 try {
722 //Platform::DebugPrintf("S M:%x WP:%x L:%x\n", iMessage, wParam, lParam);
723 iMessage = SciMessageFromEM(iMessage);
724 switch (iMessage) {
726 case WM_CREATE:
727 ctrlID = ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
728 // Get Intellimouse scroll line parameters
729 GetIntelliMouseParameters();
730 ::RegisterDragDrop(MainHWND(), reinterpret_cast<IDropTarget *>(&dt));
731 break;
733 case WM_COMMAND:
734 Command(LoWord(wParam));
735 break;
737 case WM_PAINT:
738 return WndPaint(wParam);
740 case WM_PRINTCLIENT: {
741 HDC hdc = reinterpret_cast<HDC>(wParam);
742 if (!IsCompatibleDC(hdc)) {
743 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
745 FullPaintDC(hdc);
747 break;
749 case WM_VSCROLL:
750 ScrollMessage(wParam);
751 break;
753 case WM_HSCROLL:
754 HorizontalScrollMessage(wParam);
755 break;
757 case WM_SIZE: {
758 #if defined(USE_D2D)
759 if (paintState == notPainting) {
760 DropRenderTarget();
761 } else {
762 renderTargetValid = false;
764 #endif
765 //Platform::DebugPrintf("Scintilla WM_SIZE %d %d\n", LoWord(lParam), HiWord(lParam));
766 ChangeSize();
768 break;
770 case WM_MOUSEWHEEL:
771 // if autocomplete list active then send mousewheel message to it
772 if (ac.Active()) {
773 HWND hWnd = reinterpret_cast<HWND>(ac.lb->GetID());
774 ::SendMessage(hWnd, iMessage, wParam, lParam);
775 break;
778 // Don't handle datazoom.
779 // (A good idea for datazoom would be to "fold" or "unfold" details.
780 // i.e. if datazoomed out only class structures are visible, when datazooming in the control
781 // structures appear, then eventually the individual statements...)
782 if (wParam & MK_SHIFT) {
783 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
786 // Either SCROLL or ZOOM. We handle the wheel steppings calculation
787 wheelDelta -= static_cast<short>(HiWord(wParam));
788 if (abs(wheelDelta) >= WHEEL_DELTA && linesPerScroll > 0) {
789 int linesToScroll = linesPerScroll;
790 if (linesPerScroll == WHEEL_PAGESCROLL)
791 linesToScroll = LinesOnScreen() - 1;
792 if (linesToScroll == 0) {
793 linesToScroll = 1;
795 linesToScroll *= (wheelDelta / WHEEL_DELTA);
796 if (wheelDelta >= 0)
797 wheelDelta = wheelDelta % WHEEL_DELTA;
798 else
799 wheelDelta = - (-wheelDelta % WHEEL_DELTA);
801 if (wParam & MK_CONTROL) {
802 // Zoom! We play with the font sizes in the styles.
803 // Number of steps/line is ignored, we just care if sizing up or down
804 if (linesToScroll < 0) {
805 KeyCommand(SCI_ZOOMIN);
806 } else {
807 KeyCommand(SCI_ZOOMOUT);
809 } else {
810 // Scroll
811 ScrollTo(topLine + linesToScroll);
814 return 0;
816 case WM_TIMER:
817 if (wParam == standardTimerID && timer.ticking) {
818 Tick();
819 } else if (wParam == idleTimerID && idler.state) {
820 SendMessage(MainHWND(), SC_WIN_IDLE, 0, 1);
821 } else {
822 return 1;
824 break;
826 case SC_WIN_IDLE:
827 // wParam=dwTickCountInitial, or 0 to initialize. lParam=bSkipUserInputTest
828 if (idler.state) {
829 if (lParam || (WAIT_TIMEOUT == MsgWaitForMultipleObjects(0, 0, 0, 0, QS_INPUT|QS_HOTKEY))) {
830 if (Idle()) {
831 // User input was given priority above, but all events do get a turn. Other
832 // messages, notifications, etc. will get interleaved with the idle messages.
834 // However, some things like WM_PAINT are a lower priority, and will not fire
835 // when there's a message posted. So, several times a second, we stop and let
836 // the low priority events have a turn (after which the timer will fire again).
838 DWORD dwCurrent = GetTickCount();
839 DWORD dwStart = wParam ? wParam : dwCurrent;
840 const DWORD maxWorkTime = 50;
842 if (dwCurrent >= dwStart && dwCurrent > maxWorkTime && dwCurrent - maxWorkTime < dwStart)
843 PostMessage(MainHWND(), SC_WIN_IDLE, dwStart, 0);
844 } else {
845 SetIdle(false);
849 break;
851 case WM_GETMINMAXINFO:
852 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
854 case WM_LBUTTONDOWN: {
855 #ifndef __DMC__
856 // Digital Mars compiler does not include Imm library
857 // For IME, set the composition string as the result string.
858 HIMC hIMC = ::ImmGetContext(MainHWND());
859 ::ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
860 ::ImmReleaseContext(MainHWND(), hIMC);
861 #endif
863 //Platform::DebugPrintf("Buttdown %d %x %x %x %x %x\n",iMessage, wParam, lParam,
864 // Platform::IsKeyDown(VK_SHIFT),
865 // Platform::IsKeyDown(VK_CONTROL),
866 // Platform::IsKeyDown(VK_MENU));
867 ::SetFocus(MainHWND());
868 ButtonDown(Point::FromLong(lParam), ::GetMessageTime(),
869 (wParam & MK_SHIFT) != 0,
870 (wParam & MK_CONTROL) != 0,
871 Platform::IsKeyDown(VK_MENU));
873 break;
875 case WM_MOUSEMOVE:
876 SetTrackMouseLeaveEvent(true);
877 ButtonMove(Point::FromLong(lParam));
878 break;
880 case WM_MOUSELEAVE:
881 SetTrackMouseLeaveEvent(false);
882 MouseLeave();
883 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
885 case WM_LBUTTONUP:
886 ButtonUp(Point::FromLong(lParam),
887 ::GetMessageTime(),
888 (wParam & MK_CONTROL) != 0);
889 break;
891 case WM_RBUTTONDOWN:
892 ::SetFocus(MainHWND());
893 if (!PointInSelection(Point::FromLong(lParam))) {
894 CancelModes();
895 SetEmptySelection(PositionFromLocation(Point::FromLong(lParam)));
897 break;
899 case WM_SETCURSOR:
900 if (LoWord(lParam) == HTCLIENT) {
901 if (inDragDrop == ddDragging) {
902 DisplayCursor(Window::cursorUp);
903 } else {
904 // Display regular (drag) cursor over selection
905 POINT pt;
906 if (0 != ::GetCursorPos(&pt)) {
907 ::ScreenToClient(MainHWND(), &pt);
908 if (PointInSelMargin(Point(pt.x, pt.y))) {
909 DisplayCursor(GetMarginCursor(Point(pt.x, pt.y)));
910 } else if (PointInSelection(Point(pt.x, pt.y)) && !SelectionEmpty()) {
911 DisplayCursor(Window::cursorArrow);
912 } else if (PointIsHotspot(Point(pt.x, pt.y))) {
913 DisplayCursor(Window::cursorHand);
914 } else {
915 DisplayCursor(Window::cursorText);
919 return TRUE;
920 } else {
921 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
924 case WM_CHAR:
925 if (((wParam >= 128) || !iscntrl(wParam)) || !lastKeyDownConsumed) {
926 if (::IsWindowUnicode(MainHWND()) || keysAlwaysUnicode) {
927 wchar_t wcs[2] = {wParam, 0};
928 if (IsUnicodeMode()) {
929 // For a wide character version of the window:
930 char utfval[4];
931 unsigned int len = UTF8Length(wcs, 1);
932 UTF8FromUTF16(wcs, 1, utfval, len);
933 AddCharUTF(utfval, len);
934 } else {
935 UINT cpDest = CodePageOfDocument();
936 char inBufferCP[20];
937 int size = ::WideCharToMultiByte(cpDest,
938 0, wcs, 1, inBufferCP, sizeof(inBufferCP) - 1, 0, 0);
939 inBufferCP[size] = '\0';
940 AddCharUTF(inBufferCP, size);
942 } else {
943 if (IsUnicodeMode()) {
944 AddCharBytes('\0', LOBYTE(wParam));
945 } else {
946 AddChar(LOBYTE(wParam));
950 return 0;
952 case WM_UNICHAR:
953 if (wParam == UNICODE_NOCHAR) {
954 return IsUnicodeMode() ? 1 : 0;
955 } else if (lastKeyDownConsumed) {
956 return 1;
957 } else {
958 if (IsUnicodeMode()) {
959 char utfval[4];
960 wchar_t wcs[2] = {static_cast<wchar_t>(wParam), 0};
961 unsigned int len = UTF8Length(wcs, 1);
962 UTF8FromUTF16(wcs, 1, utfval, len);
963 AddCharUTF(utfval, len);
964 return 1;
965 } else {
966 return 0;
970 case WM_SYSKEYDOWN:
971 case WM_KEYDOWN: {
972 //Platform::DebugPrintf("S keydown %d %x %x %x %x\n",iMessage, wParam, lParam, ::IsKeyDown(VK_SHIFT), ::IsKeyDown(VK_CONTROL));
973 lastKeyDownConsumed = false;
974 int ret = KeyDown(KeyTranslate(wParam),
975 Platform::IsKeyDown(VK_SHIFT),
976 Platform::IsKeyDown(VK_CONTROL),
977 Platform::IsKeyDown(VK_MENU),
978 &lastKeyDownConsumed);
979 if (!ret && !lastKeyDownConsumed) {
980 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
982 break;
985 case WM_IME_KEYDOWN:
986 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
988 case WM_KEYUP:
989 //Platform::DebugPrintf("S keyup %d %x %x\n",iMessage, wParam, lParam);
990 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
992 case WM_SETTINGCHANGE:
993 //Platform::DebugPrintf("Setting Changed\n");
994 InvalidateStyleData();
995 // Get Intellimouse scroll line parameters
996 GetIntelliMouseParameters();
997 break;
999 case WM_GETDLGCODE:
1000 return DLGC_HASSETSEL | DLGC_WANTALLKEYS;
1002 case WM_KILLFOCUS: {
1003 HWND wOther = reinterpret_cast<HWND>(wParam);
1004 HWND wThis = MainHWND();
1005 HWND wCT = reinterpret_cast<HWND>(ct.wCallTip.GetID());
1006 if (!wParam ||
1007 !(::IsChild(wThis, wOther) || (wOther == wCT))) {
1008 SetFocusState(false);
1009 DestroySystemCaret();
1012 break;
1014 case WM_SETFOCUS:
1015 SetFocusState(true);
1016 DestroySystemCaret();
1017 CreateSystemCaret();
1018 break;
1020 case WM_SYSCOLORCHANGE:
1021 //Platform::DebugPrintf("Setting Changed\n");
1022 InvalidateStyleData();
1023 break;
1025 case WM_IME_STARTCOMPOSITION: // dbcs
1026 ImeStartComposition();
1027 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1029 case WM_IME_ENDCOMPOSITION: // dbcs
1030 ImeEndComposition();
1031 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1033 case WM_IME_COMPOSITION:
1034 return HandleComposition(wParam, lParam);
1036 case WM_IME_CHAR: {
1037 AddCharBytes(HIBYTE(wParam), LOBYTE(wParam));
1038 return 0;
1041 case WM_CONTEXTMENU:
1042 if (displayPopupMenu) {
1043 Point pt = Point::FromLong(lParam);
1044 if ((pt.x == -1) && (pt.y == -1)) {
1045 // Caused by keyboard so display menu near caret
1046 pt = PointMainCaret();
1047 POINT spt = {pt.x, pt.y};
1048 ::ClientToScreen(MainHWND(), &spt);
1049 pt = Point(spt.x, spt.y);
1051 ContextMenu(pt);
1052 return 0;
1054 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1056 case WM_INPUTLANGCHANGE:
1057 //::SetThreadLocale(LOWORD(lParam));
1058 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1060 case WM_INPUTLANGCHANGEREQUEST:
1061 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1063 case WM_ERASEBKGND:
1064 return 1; // Avoid any background erasure as whole window painted.
1066 case WM_CAPTURECHANGED:
1067 capturedMouse = false;
1068 return 0;
1070 // These are not handled in Scintilla and its faster to dispatch them here.
1071 // Also moves time out to here so profile doesn't count lots of empty message calls.
1073 case WM_MOVE:
1074 case WM_MOUSEACTIVATE:
1075 case WM_NCHITTEST:
1076 case WM_NCCALCSIZE:
1077 case WM_NCPAINT:
1078 case WM_NCMOUSEMOVE:
1079 case WM_NCLBUTTONDOWN:
1080 case WM_IME_SETCONTEXT:
1081 case WM_IME_NOTIFY:
1082 case WM_SYSCOMMAND:
1083 case WM_WINDOWPOSCHANGING:
1084 case WM_WINDOWPOSCHANGED:
1085 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1087 case EM_LINEFROMCHAR:
1088 if (static_cast<int>(wParam) < 0) {
1089 wParam = SelectionStart().Position();
1091 return pdoc->LineFromPosition(wParam);
1093 case EM_EXLINEFROMCHAR:
1094 return pdoc->LineFromPosition(lParam);
1096 case EM_GETSEL:
1097 if (wParam) {
1098 *reinterpret_cast<int *>(wParam) = SelectionStart().Position();
1100 if (lParam) {
1101 *reinterpret_cast<int *>(lParam) = SelectionEnd().Position();
1103 return MAKELONG(SelectionStart().Position(), SelectionEnd().Position());
1105 case EM_EXGETSEL: {
1106 if (lParam == 0) {
1107 return 0;
1109 Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
1110 pCR->cpMin = SelectionStart().Position();
1111 pCR->cpMax = SelectionEnd().Position();
1113 break;
1115 case EM_SETSEL: {
1116 int nStart = static_cast<int>(wParam);
1117 int nEnd = static_cast<int>(lParam);
1118 if (nStart == 0 && nEnd == -1) {
1119 nEnd = pdoc->Length();
1121 if (nStart == -1) {
1122 nStart = nEnd; // Remove selection
1124 if (nStart > nEnd) {
1125 SetSelection(nEnd, nStart);
1126 } else {
1127 SetSelection(nStart, nEnd);
1129 EnsureCaretVisible();
1131 break;
1133 case EM_EXSETSEL: {
1134 if (lParam == 0) {
1135 return 0;
1137 Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
1138 sel.selType = Selection::selStream;
1139 if (pCR->cpMin == 0 && pCR->cpMax == -1) {
1140 SetSelection(pCR->cpMin, pdoc->Length());
1141 } else {
1142 SetSelection(pCR->cpMin, pCR->cpMax);
1144 EnsureCaretVisible();
1145 return pdoc->LineFromPosition(SelectionStart().Position());
1148 case SCI_GETDIRECTFUNCTION:
1149 return reinterpret_cast<sptr_t>(DirectFunction);
1151 case SCI_GETDIRECTPOINTER:
1152 return reinterpret_cast<sptr_t>(this);
1154 case SCI_GRABFOCUS:
1155 ::SetFocus(MainHWND());
1156 break;
1158 case SCI_SETKEYSUNICODE:
1159 keysAlwaysUnicode = wParam != 0;
1160 break;
1162 case SCI_GETKEYSUNICODE:
1163 return keysAlwaysUnicode;
1165 case SCI_SETTECHNOLOGY:
1166 if ((wParam == SC_TECHNOLOGY_DEFAULT) || (wParam == SC_TECHNOLOGY_DIRECTWRITE)) {
1167 if (technology != static_cast<int>(wParam)) {
1168 if (static_cast<int>(wParam) == SC_TECHNOLOGY_DIRECTWRITE) {
1169 #if defined(USE_D2D)
1170 if (!LoadD2D())
1171 // Failed to load Direct2D or DirectWrite so no effect
1172 return 0;
1173 #else
1174 return 0;
1175 #endif
1177 technology = wParam;
1178 // Invalidate all cached information including layout.
1179 DropGraphics(true);
1180 InvalidateStyleRedraw();
1183 break;
1185 #ifdef SCI_LEXER
1186 case SCI_LOADLEXERLIBRARY:
1187 LexerManager::GetInstance()->Load(reinterpret_cast<const char *>(lParam));
1188 break;
1189 #endif
1191 default:
1192 return ScintillaBase::WndProc(iMessage, wParam, lParam);
1194 } catch (std::bad_alloc &) {
1195 errorStatus = SC_STATUS_BADALLOC;
1196 } catch (...) {
1197 errorStatus = SC_STATUS_FAILURE;
1199 return 0l;
1202 bool ScintillaWin::ValidCodePage(int codePage) const {
1203 return codePage == 0 || codePage == SC_CP_UTF8 ||
1204 codePage == 932 || codePage == 936 || codePage == 949 ||
1205 codePage == 950 || codePage == 1361;
1208 sptr_t ScintillaWin::DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
1209 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1212 void ScintillaWin::SetTicking(bool on) {
1213 if (timer.ticking != on) {
1214 timer.ticking = on;
1215 if (timer.ticking) {
1216 timer.tickerID = ::SetTimer(MainHWND(), standardTimerID, timer.tickSize, NULL)
1217 ? reinterpret_cast<TickerID>(standardTimerID) : 0;
1218 } else {
1219 ::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(timer.tickerID));
1220 timer.tickerID = 0;
1223 timer.ticksToWait = caret.period;
1226 bool ScintillaWin::SetIdle(bool on) {
1227 // On Win32 the Idler is implemented as a Timer on the Scintilla window. This
1228 // takes advantage of the fact that WM_TIMER messages are very low priority,
1229 // and are only posted when the message queue is empty, i.e. during idle time.
1230 if (idler.state != on) {
1231 if (on) {
1232 idler.idlerID = ::SetTimer(MainHWND(), idleTimerID, 10, NULL)
1233 ? reinterpret_cast<IdlerID>(idleTimerID) : 0;
1234 } else {
1235 ::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(idler.idlerID));
1236 idler.idlerID = 0;
1238 idler.state = idler.idlerID != 0;
1240 return idler.state;
1243 void ScintillaWin::SetMouseCapture(bool on) {
1244 if (mouseDownCaptures) {
1245 if (on) {
1246 ::SetCapture(MainHWND());
1247 } else {
1248 ::ReleaseCapture();
1251 capturedMouse = on;
1254 bool ScintillaWin::HaveMouseCapture() {
1255 // Cannot just see if GetCapture is this window as the scroll bar also sets capture for the window
1256 return capturedMouse;
1257 //return capturedMouse && (::GetCapture() == MainHWND());
1260 void ScintillaWin::SetTrackMouseLeaveEvent(bool on) {
1261 if (on && TrackMouseEventFn && !trackedMouseLeave) {
1262 TRACKMOUSEEVENT tme;
1263 tme.cbSize = sizeof(tme);
1264 tme.dwFlags = TME_LEAVE;
1265 tme.hwndTrack = MainHWND();
1266 TrackMouseEventFn(&tme);
1268 trackedMouseLeave = on;
1271 bool ScintillaWin::PaintContains(PRectangle rc) {
1272 bool contains = true;
1273 if ((paintState == painting) && (!rc.Empty())) {
1274 if (!rcPaint.Contains(rc)) {
1275 contains = false;
1276 } else {
1277 // In bounding rectangle so check more accurately using region
1278 HRGN hRgnRange = ::CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
1279 if (hRgnRange) {
1280 HRGN hRgnDest = ::CreateRectRgn(0, 0, 0, 0);
1281 if (hRgnDest) {
1282 int combination = ::CombineRgn(hRgnDest, hRgnRange, hRgnUpdate, RGN_DIFF);
1283 if (combination != NULLREGION) {
1284 contains = false;
1286 ::DeleteRgn(hRgnDest);
1288 ::DeleteRgn(hRgnRange);
1292 return contains;
1295 void ScintillaWin::ScrollText(int /* linesToMove */) {
1296 //Platform::DebugPrintf("ScintillaWin::ScrollText %d\n", linesToMove);
1297 //::ScrollWindow(MainHWND(), 0,
1298 // vs.lineHeight * linesToMove, 0, 0);
1299 //::UpdateWindow(MainHWND());
1300 Redraw();
1303 void ScintillaWin::UpdateSystemCaret() {
1304 if (hasFocus) {
1305 if (HasCaretSizeChanged()) {
1306 DestroySystemCaret();
1307 CreateSystemCaret();
1309 Point pos = PointMainCaret();
1310 ::SetCaretPos(pos.x, pos.y);
1314 int ScintillaWin::SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) {
1315 return ::SetScrollInfo(MainHWND(), nBar, lpsi, bRedraw);
1318 bool ScintillaWin::GetScrollInfo(int nBar, LPSCROLLINFO lpsi) {
1319 return ::GetScrollInfo(MainHWND(), nBar, lpsi) ? true : false;
1322 // Change the scroll position but avoid repaint if changing to same value
1323 void ScintillaWin::ChangeScrollPos(int barType, int pos) {
1324 SCROLLINFO sci = {
1325 sizeof(sci), 0, 0, 0, 0, 0, 0
1327 sci.fMask = SIF_POS;
1328 GetScrollInfo(barType, &sci);
1329 if (sci.nPos != pos) {
1330 DwellEnd(true);
1331 sci.nPos = pos;
1332 SetScrollInfo(barType, &sci, TRUE);
1336 void ScintillaWin::SetVerticalScrollPos() {
1337 ChangeScrollPos(SB_VERT, topLine);
1340 void ScintillaWin::SetHorizontalScrollPos() {
1341 ChangeScrollPos(SB_HORZ, xOffset);
1344 bool ScintillaWin::ModifyScrollBars(int nMax, int nPage) {
1345 bool modified = false;
1346 SCROLLINFO sci = {
1347 sizeof(sci), 0, 0, 0, 0, 0, 0
1349 sci.fMask = SIF_PAGE | SIF_RANGE;
1350 GetScrollInfo(SB_VERT, &sci);
1351 int vertEndPreferred = nMax;
1352 if (!verticalScrollBarVisible)
1353 nPage = vertEndPreferred + 1;
1354 if ((sci.nMin != 0) ||
1355 (sci.nMax != vertEndPreferred) ||
1356 (sci.nPage != static_cast<unsigned int>(nPage)) ||
1357 (sci.nPos != 0)) {
1358 sci.fMask = SIF_PAGE | SIF_RANGE;
1359 sci.nMin = 0;
1360 sci.nMax = vertEndPreferred;
1361 sci.nPage = nPage;
1362 sci.nPos = 0;
1363 sci.nTrackPos = 1;
1364 SetScrollInfo(SB_VERT, &sci, TRUE);
1365 modified = true;
1368 PRectangle rcText = GetTextRectangle();
1369 int horizEndPreferred = scrollWidth;
1370 if (horizEndPreferred < 0)
1371 horizEndPreferred = 0;
1372 unsigned int pageWidth = rcText.Width();
1373 if (!horizontalScrollBarVisible || (wrapState != eWrapNone))
1374 pageWidth = horizEndPreferred + 1;
1375 sci.fMask = SIF_PAGE | SIF_RANGE;
1376 GetScrollInfo(SB_HORZ, &sci);
1377 if ((sci.nMin != 0) ||
1378 (sci.nMax != horizEndPreferred) ||
1379 (sci.nPage != pageWidth) ||
1380 (sci.nPos != 0)) {
1381 sci.fMask = SIF_PAGE | SIF_RANGE;
1382 sci.nMin = 0;
1383 sci.nMax = horizEndPreferred;
1384 sci.nPage = pageWidth;
1385 sci.nPos = 0;
1386 sci.nTrackPos = 1;
1387 SetScrollInfo(SB_HORZ, &sci, TRUE);
1388 modified = true;
1389 if (scrollWidth < static_cast<int>(pageWidth)) {
1390 HorizontalScrollTo(0);
1393 return modified;
1396 void ScintillaWin::NotifyChange() {
1397 ::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
1398 MAKELONG(GetCtrlID(), SCEN_CHANGE),
1399 reinterpret_cast<LPARAM>(MainHWND()));
1402 void ScintillaWin::NotifyFocus(bool focus) {
1403 ::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
1404 MAKELONG(GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS),
1405 reinterpret_cast<LPARAM>(MainHWND()));
1408 void ScintillaWin::SetCtrlID(int identifier) {
1409 ::SetWindowID(reinterpret_cast<HWND>(wMain.GetID()), identifier);
1412 int ScintillaWin::GetCtrlID() {
1413 return ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
1416 void ScintillaWin::NotifyParent(SCNotification scn) {
1417 scn.nmhdr.hwndFrom = MainHWND();
1418 scn.nmhdr.idFrom = GetCtrlID();
1419 ::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
1420 GetCtrlID(), reinterpret_cast<LPARAM>(&scn));
1423 void ScintillaWin::NotifyParent(SCNotification * scn) {
1424 scn->nmhdr.hwndFrom = MainHWND();
1425 scn->nmhdr.idFrom = GetCtrlID();
1426 ::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
1427 GetCtrlID(), reinterpret_cast<LPARAM>(scn));
1430 void ScintillaWin::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) {
1431 //Platform::DebugPrintf("ScintillaWin Double click 0\n");
1432 ScintillaBase::NotifyDoubleClick(pt, shift, ctrl, alt);
1433 // Send myself a WM_LBUTTONDBLCLK, so the container can handle it too.
1434 ::SendMessage(MainHWND(),
1435 WM_LBUTTONDBLCLK,
1436 shift ? MK_SHIFT : 0,
1437 MAKELPARAM(pt.x, pt.y));
1440 class CaseFolderUTF8 : public CaseFolderTable {
1441 // Allocate the expandable storage here so that it does not need to be reallocated
1442 // for each call to Fold.
1443 std::vector<wchar_t> utf16Mixed;
1444 std::vector<wchar_t> utf16Folded;
1445 public:
1446 CaseFolderUTF8() {
1447 StandardASCII();
1449 virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
1450 if ((lenMixed == 1) && (sizeFolded > 0)) {
1451 folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
1452 return 1;
1453 } else {
1454 if (lenMixed > utf16Mixed.size()) {
1455 utf16Mixed.resize(lenMixed + 8);
1457 size_t nUtf16Mixed = ::MultiByteToWideChar(65001, 0, mixed,
1458 static_cast<int>(lenMixed),
1459 &utf16Mixed[0],
1460 static_cast<int>(utf16Mixed.size()));
1462 if (nUtf16Mixed == 0) {
1463 // Failed to convert -> bad UTF-8
1464 folded[0] = '\0';
1465 return 1;
1468 if (nUtf16Mixed * 4 > utf16Folded.size()) { // Maximum folding expansion factor of 4
1469 utf16Folded.resize(nUtf16Mixed * 4 + 8);
1471 int lenFlat = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
1472 LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
1473 &utf16Mixed[0],
1474 static_cast<int>(nUtf16Mixed),
1475 &utf16Folded[0],
1476 static_cast<int>(utf16Folded.size()));
1478 size_t lenOut = UTF8Length(&utf16Folded[0], lenFlat);
1479 if (lenOut < sizeFolded) {
1480 UTF8FromUTF16(&utf16Folded[0], lenFlat, folded, static_cast<int>(lenOut));
1481 return lenOut;
1482 } else {
1483 return 0;
1489 class CaseFolderDBCS : public CaseFolderTable {
1490 // Allocate the expandable storage here so that it does not need to be reallocated
1491 // for each call to Fold.
1492 std::vector<wchar_t> utf16Mixed;
1493 std::vector<wchar_t> utf16Folded;
1494 UINT cp;
1495 public:
1496 CaseFolderDBCS(UINT cp_) : cp(cp_) {
1497 StandardASCII();
1499 virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
1500 if ((lenMixed == 1) && (sizeFolded > 0)) {
1501 folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
1502 return 1;
1503 } else {
1504 if (lenMixed > utf16Mixed.size()) {
1505 utf16Mixed.resize(lenMixed + 8);
1507 size_t nUtf16Mixed = ::MultiByteToWideChar(cp, 0, mixed,
1508 static_cast<int>(lenMixed),
1509 &utf16Mixed[0],
1510 static_cast<int>(utf16Mixed.size()));
1512 if (nUtf16Mixed == 0) {
1513 // Failed to convert -> bad input
1514 folded[0] = '\0';
1515 return 1;
1518 if (nUtf16Mixed * 4 > utf16Folded.size()) { // Maximum folding expansion factor of 4
1519 utf16Folded.resize(nUtf16Mixed * 4 + 8);
1521 int lenFlat = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
1522 LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
1523 &utf16Mixed[0],
1524 static_cast<int>(nUtf16Mixed),
1525 &utf16Folded[0],
1526 static_cast<int>(utf16Folded.size()));
1528 size_t lenOut = ::WideCharToMultiByte(cp, 0,
1529 &utf16Folded[0], lenFlat,
1530 NULL, 0, NULL, 0);
1532 if (lenOut < sizeFolded) {
1533 ::WideCharToMultiByte(cp, 0,
1534 &utf16Folded[0], lenFlat,
1535 folded, static_cast<int>(lenOut), NULL, 0);
1536 return lenOut;
1537 } else {
1538 return 0;
1544 CaseFolder *ScintillaWin::CaseFolderForEncoding() {
1545 UINT cpDest = CodePageOfDocument();
1546 if (cpDest == SC_CP_UTF8) {
1547 return new CaseFolderUTF8();
1548 } else {
1549 if (pdoc->dbcsCodePage == 0) {
1550 CaseFolderTable *pcf = new CaseFolderTable();
1551 pcf->StandardASCII();
1552 // Only for single byte encodings
1553 UINT cpDoc = CodePageOfDocument();
1554 for (int i=0x80; i<0x100; i++) {
1555 char sCharacter[2] = "A";
1556 sCharacter[0] = static_cast<char>(i);
1557 wchar_t wCharacter[20];
1558 unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, sCharacter, 1,
1559 wCharacter, sizeof(wCharacter)/sizeof(wCharacter[0]));
1560 if (lengthUTF16 == 1) {
1561 wchar_t wLower[20];
1562 int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
1563 LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
1564 wCharacter, lengthUTF16, wLower, sizeof(wLower)/sizeof(wLower[0]));
1565 char sCharacterLowered[20];
1566 unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
1567 wLower, charsConverted,
1568 sCharacterLowered, sizeof(sCharacterLowered), NULL, 0);
1569 if ((lengthConverted == 1) && (sCharacter[0] != sCharacterLowered[0])) {
1570 pcf->SetTranslation(sCharacter[0], sCharacterLowered[0]);
1574 return pcf;
1575 } else {
1576 return new CaseFolderDBCS(cpDest);
1581 std::string ScintillaWin::CaseMapString(const std::string &s, int caseMapping) {
1582 if (s.size() == 0)
1583 return std::string();
1585 if (caseMapping == cmSame)
1586 return s;
1588 UINT cpDoc = CodePageOfDocument();
1590 unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, s.c_str(),
1591 static_cast<int>(s.size()), NULL, 0);
1592 if (lengthUTF16 == 0) // Failed to convert
1593 return s;
1595 DWORD mapFlags = LCMAP_LINGUISTIC_CASING |
1596 ((caseMapping == cmUpper) ? LCMAP_UPPERCASE : LCMAP_LOWERCASE);
1598 // Many conversions performed by search function are short so optimize this case.
1599 enum { shortSize=20 };
1601 if (s.size() > shortSize) {
1602 // Use dynamic allocations for long strings
1604 // Change text to UTF-16
1605 std::vector<wchar_t> vwcText(lengthUTF16);
1606 ::MultiByteToWideChar(cpDoc, 0, s.c_str(), static_cast<int>(s.size()), &vwcText[0], lengthUTF16);
1608 // Change case
1609 int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
1610 &vwcText[0], lengthUTF16, NULL, 0);
1611 std::vector<wchar_t> vwcConverted(charsConverted);
1612 ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
1613 &vwcText[0], lengthUTF16, &vwcConverted[0], charsConverted);
1615 // Change back to document encoding
1616 unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
1617 &vwcConverted[0], static_cast<int>(vwcConverted.size()),
1618 NULL, 0, NULL, 0);
1619 std::vector<char> vcConverted(lengthConverted);
1620 ::WideCharToMultiByte(cpDoc, 0,
1621 &vwcConverted[0], static_cast<int>(vwcConverted.size()),
1622 &vcConverted[0], static_cast<int>(vcConverted.size()), NULL, 0);
1624 return std::string(&vcConverted[0], vcConverted.size());
1626 } else {
1627 // Use static allocations for short strings as much faster
1628 // A factor of 15 for single character strings
1630 // Change text to UTF-16
1631 wchar_t vwcText[shortSize];
1632 ::MultiByteToWideChar(cpDoc, 0, s.c_str(), static_cast<int>(s.size()),
1633 vwcText, lengthUTF16);
1635 // Change case
1636 int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
1637 vwcText, lengthUTF16, NULL, 0);
1638 // Full mapping may produce up to 3 characters per input character
1639 wchar_t vwcConverted[shortSize*3];
1640 ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags, vwcText, lengthUTF16,
1641 vwcConverted, charsConverted);
1643 // Change back to document encoding
1644 unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
1645 vwcConverted, charsConverted,
1646 NULL, 0, NULL, 0);
1647 // Each UTF-16 code unit may need up to 3 bytes in UTF-8
1648 char vcConverted[shortSize * 3 * 3];
1649 ::WideCharToMultiByte(cpDoc, 0,
1650 vwcConverted, charsConverted,
1651 vcConverted, lengthConverted, NULL, 0);
1653 return std::string(vcConverted, lengthConverted);
1657 void ScintillaWin::Copy() {
1658 //Platform::DebugPrintf("Copy\n");
1659 if (!sel.Empty()) {
1660 SelectionText selectedText;
1661 CopySelectionRange(&selectedText);
1662 CopyToClipboard(selectedText);
1666 void ScintillaWin::CopyAllowLine() {
1667 SelectionText selectedText;
1668 CopySelectionRange(&selectedText, true);
1669 CopyToClipboard(selectedText);
1672 bool ScintillaWin::CanPaste() {
1673 if (!Editor::CanPaste())
1674 return false;
1675 if (::IsClipboardFormatAvailable(CF_TEXT))
1676 return true;
1677 if (IsUnicodeMode())
1678 return ::IsClipboardFormatAvailable(CF_UNICODETEXT) != 0;
1679 return false;
1682 class GlobalMemory {
1683 HGLOBAL hand;
1684 public:
1685 void *ptr;
1686 GlobalMemory() : hand(0), ptr(0) {
1688 GlobalMemory(HGLOBAL hand_) : hand(hand_), ptr(0) {
1689 if (hand) {
1690 ptr = ::GlobalLock(hand);
1693 ~GlobalMemory() {
1694 PLATFORM_ASSERT(!ptr);
1696 void Allocate(size_t bytes) {
1697 hand = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bytes);
1698 if (hand) {
1699 ptr = ::GlobalLock(hand);
1702 HGLOBAL Unlock() {
1703 PLATFORM_ASSERT(ptr);
1704 HGLOBAL handCopy = hand;
1705 ::GlobalUnlock(hand);
1706 ptr = 0;
1707 hand = 0;
1708 return handCopy;
1710 void SetClip(UINT uFormat) {
1711 ::SetClipboardData(uFormat, Unlock());
1713 operator bool() const {
1714 return ptr != 0;
1716 SIZE_T Size() {
1717 return ::GlobalSize(hand);
1721 void ScintillaWin::InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine) {
1722 if (isRectangular) {
1723 PasteRectangular(selStart, text, len);
1724 } else {
1725 char *convertedText = 0;
1726 if (convertPastes) {
1727 // Convert line endings of the paste into our local line-endings mode
1728 convertedText = Document::TransformLineEnds(&len, text, len, pdoc->eolMode);
1729 text = convertedText;
1731 if (isLine) {
1732 int insertPos = pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret()));
1733 pdoc->InsertString(insertPos, text, len);
1734 // add the newline if necessary
1735 if ((len > 0) && (text[len-1] != '\n' && text[len-1] != '\r')) {
1736 const char *endline = StringFromEOLMode(pdoc->eolMode);
1737 pdoc->InsertString(insertPos + len, endline, static_cast<int>(strlen(endline)));
1738 len += static_cast<int>(strlen(endline));
1740 if (sel.MainCaret() == insertPos) {
1741 SetEmptySelection(sel.MainCaret() + len);
1743 } else {
1744 InsertPaste(selStart, text, len);
1746 delete []convertedText;
1750 void ScintillaWin::Paste() {
1751 if (!::OpenClipboard(MainHWND()))
1752 return;
1753 UndoGroup ug(pdoc);
1754 bool isLine = SelectionEmpty() && (::IsClipboardFormatAvailable(cfLineSelect) != 0);
1755 ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
1756 SelectionPosition selStart = sel.IsRectangular() ?
1757 sel.Rectangular().Start() :
1758 sel.Range(sel.Main()).Start();
1759 bool isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
1761 // Always use CF_UNICODETEXT if available
1762 GlobalMemory memUSelection(::GetClipboardData(CF_UNICODETEXT));
1763 if (memUSelection) {
1764 wchar_t *uptr = static_cast<wchar_t *>(memUSelection.ptr);
1765 if (uptr) {
1766 unsigned int len;
1767 char *putf;
1768 // Default Scintilla behaviour in Unicode mode
1769 if (IsUnicodeMode()) {
1770 unsigned int bytes = memUSelection.Size();
1771 len = UTF8Length(uptr, bytes / 2);
1772 putf = new char[len + 1];
1773 UTF8FromUTF16(uptr, bytes / 2, putf, len);
1774 } else {
1775 // CF_UNICODETEXT available, but not in Unicode mode
1776 // Convert from Unicode to current Scintilla code page
1777 UINT cpDest = CodePageOfDocument();
1778 len = ::WideCharToMultiByte(cpDest, 0, uptr, -1,
1779 NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
1780 putf = new char[len + 1];
1781 ::WideCharToMultiByte(cpDest, 0, uptr, -1,
1782 putf, len + 1, NULL, NULL);
1785 InsertPasteText(putf, len, selStart, isRectangular, isLine);
1786 delete []putf;
1788 memUSelection.Unlock();
1789 } else {
1790 // CF_UNICODETEXT not available, paste ANSI text
1791 GlobalMemory memSelection(::GetClipboardData(CF_TEXT));
1792 if (memSelection) {
1793 char *ptr = static_cast<char *>(memSelection.ptr);
1794 if (ptr) {
1795 unsigned int bytes = memSelection.Size();
1796 unsigned int len = bytes;
1797 for (unsigned int i = 0; i < bytes; i++) {
1798 if ((len == bytes) && (0 == ptr[i]))
1799 len = i;
1802 // In Unicode mode, convert clipboard text to UTF-8
1803 if (IsUnicodeMode()) {
1804 wchar_t *uptr = new wchar_t[len+1];
1806 unsigned int ulen = ::MultiByteToWideChar(CP_ACP, 0,
1807 ptr, len, uptr, len+1);
1809 unsigned int mlen = UTF8Length(uptr, ulen);
1810 char *putf = new char[mlen + 1];
1811 if (putf) {
1812 // CP_UTF8 not available on Windows 95, so use UTF8FromUTF16()
1813 UTF8FromUTF16(uptr, ulen, putf, mlen);
1816 delete []uptr;
1818 if (putf) {
1819 InsertPasteText(putf, mlen, selStart, isRectangular, isLine);
1820 delete []putf;
1822 } else {
1823 InsertPasteText(ptr, len, selStart, isRectangular, isLine);
1826 memSelection.Unlock();
1829 ::CloseClipboard();
1830 Redraw();
1833 void ScintillaWin::CreateCallTipWindow(PRectangle) {
1834 if (!ct.wCallTip.Created()) {
1835 ct.wCallTip = ::CreateWindow(callClassName, TEXT("ACallTip"),
1836 WS_POPUP, 100, 100, 150, 20,
1837 MainHWND(), 0,
1838 GetWindowInstance(MainHWND()),
1839 this);
1840 ct.wDraw = ct.wCallTip;
1844 void ScintillaWin::AddToPopUp(const char *label, int cmd, bool enabled) {
1845 HMENU hmenuPopup = reinterpret_cast<HMENU>(popup.GetID());
1846 if (!label[0])
1847 ::AppendMenuA(hmenuPopup, MF_SEPARATOR, 0, "");
1848 else if (enabled)
1849 ::AppendMenuA(hmenuPopup, MF_STRING, cmd, label);
1850 else
1851 ::AppendMenuA(hmenuPopup, MF_STRING | MF_DISABLED | MF_GRAYED, cmd, label);
1854 void ScintillaWin::ClaimSelection() {
1855 // Windows does not have a primary selection
1858 /// Implement IUnknown
1860 STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe);
1861 STDMETHODIMP FormatEnumerator_QueryInterface(FormatEnumerator *fe, REFIID riid, PVOID *ppv) {
1862 //Platform::DebugPrintf("EFE QI");
1863 *ppv = NULL;
1864 if (riid == IID_IUnknown)
1865 *ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
1866 if (riid == IID_IEnumFORMATETC)
1867 *ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
1868 if (!*ppv)
1869 return E_NOINTERFACE;
1870 FormatEnumerator_AddRef(fe);
1871 return S_OK;
1873 STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe) {
1874 return ++fe->ref;
1876 STDMETHODIMP_(ULONG)FormatEnumerator_Release(FormatEnumerator *fe) {
1877 fe->ref--;
1878 if (fe->ref > 0)
1879 return fe->ref;
1880 delete fe;
1881 return 0;
1883 /// Implement IEnumFORMATETC
1884 STDMETHODIMP FormatEnumerator_Next(FormatEnumerator *fe, ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) {
1885 //Platform::DebugPrintf("EFE Next %d %d", fe->pos, celt);
1886 if (rgelt == NULL) return E_POINTER;
1887 // We only support one format, so this is simple.
1888 unsigned int putPos = 0;
1889 while ((fe->pos < fe->formatsLen) && (putPos < celt)) {
1890 rgelt->cfFormat = fe->formats[fe->pos];
1891 rgelt->ptd = 0;
1892 rgelt->dwAspect = DVASPECT_CONTENT;
1893 rgelt->lindex = -1;
1894 rgelt->tymed = TYMED_HGLOBAL;
1895 fe->pos++;
1896 putPos++;
1898 if (pceltFetched)
1899 *pceltFetched = putPos;
1900 return putPos ? S_OK : S_FALSE;
1902 STDMETHODIMP FormatEnumerator_Skip(FormatEnumerator *fe, ULONG celt) {
1903 fe->pos += celt;
1904 return S_OK;
1906 STDMETHODIMP FormatEnumerator_Reset(FormatEnumerator *fe) {
1907 fe->pos = 0;
1908 return S_OK;
1910 STDMETHODIMP FormatEnumerator_Clone(FormatEnumerator *fe, IEnumFORMATETC **ppenum) {
1911 FormatEnumerator *pfe;
1912 try {
1913 pfe = new FormatEnumerator(fe->pos, fe->formats, fe->formatsLen);
1914 } catch (...) {
1915 return E_OUTOFMEMORY;
1917 return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
1918 reinterpret_cast<void **>(ppenum));
1921 static VFunction *vtFormatEnumerator[] = {
1922 (VFunction *)(FormatEnumerator_QueryInterface),
1923 (VFunction *)(FormatEnumerator_AddRef),
1924 (VFunction *)(FormatEnumerator_Release),
1925 (VFunction *)(FormatEnumerator_Next),
1926 (VFunction *)(FormatEnumerator_Skip),
1927 (VFunction *)(FormatEnumerator_Reset),
1928 (VFunction *)(FormatEnumerator_Clone)
1931 FormatEnumerator::FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_) {
1932 vtbl = vtFormatEnumerator;
1933 ref = 0; // First QI adds first reference...
1934 pos = pos_;
1935 formatsLen = formatsLen_;
1936 for (int i=0; i<formatsLen; i++)
1937 formats[i] = formats_[i];
1940 /// Implement IUnknown
1941 STDMETHODIMP DropSource_QueryInterface(DropSource *ds, REFIID riid, PVOID *ppv) {
1942 return ds->sci->QueryInterface(riid, ppv);
1944 STDMETHODIMP_(ULONG)DropSource_AddRef(DropSource *ds) {
1945 return ds->sci->AddRef();
1947 STDMETHODIMP_(ULONG)DropSource_Release(DropSource *ds) {
1948 return ds->sci->Release();
1951 /// Implement IDropSource
1952 STDMETHODIMP DropSource_QueryContinueDrag(DropSource *, BOOL fEsc, DWORD grfKeyState) {
1953 if (fEsc)
1954 return DRAGDROP_S_CANCEL;
1955 if (!(grfKeyState & MK_LBUTTON))
1956 return DRAGDROP_S_DROP;
1957 return S_OK;
1960 STDMETHODIMP DropSource_GiveFeedback(DropSource *, DWORD) {
1961 return DRAGDROP_S_USEDEFAULTCURSORS;
1964 static VFunction *vtDropSource[] = {
1965 (VFunction *)(DropSource_QueryInterface),
1966 (VFunction *)(DropSource_AddRef),
1967 (VFunction *)(DropSource_Release),
1968 (VFunction *)(DropSource_QueryContinueDrag),
1969 (VFunction *)(DropSource_GiveFeedback)
1972 DropSource::DropSource() {
1973 vtbl = vtDropSource;
1974 sci = 0;
1977 /// Implement IUnkown
1978 STDMETHODIMP DataObject_QueryInterface(DataObject *pd, REFIID riid, PVOID *ppv) {
1979 //Platform::DebugPrintf("DO QI %x\n", pd);
1980 return pd->sci->QueryInterface(riid, ppv);
1982 STDMETHODIMP_(ULONG)DataObject_AddRef(DataObject *pd) {
1983 return pd->sci->AddRef();
1985 STDMETHODIMP_(ULONG)DataObject_Release(DataObject *pd) {
1986 return pd->sci->Release();
1988 /// Implement IDataObject
1989 STDMETHODIMP DataObject_GetData(DataObject *pd, FORMATETC *pFEIn, STGMEDIUM *pSTM) {
1990 return pd->sci->GetData(pFEIn, pSTM);
1993 STDMETHODIMP DataObject_GetDataHere(DataObject *, FORMATETC *, STGMEDIUM *) {
1994 //Platform::DebugPrintf("DOB GetDataHere\n");
1995 return E_NOTIMPL;
1998 STDMETHODIMP DataObject_QueryGetData(DataObject *pd, FORMATETC *pFE) {
1999 if (pd->sci->DragIsRectangularOK(pFE->cfFormat) &&
2000 pFE->ptd == 0 &&
2001 (pFE->dwAspect & DVASPECT_CONTENT) != 0 &&
2002 pFE->lindex == -1 &&
2003 (pFE->tymed & TYMED_HGLOBAL) != 0
2005 return S_OK;
2008 bool formatOK = (pFE->cfFormat == CF_TEXT) ||
2009 ((pFE->cfFormat == CF_UNICODETEXT) && pd->sci->IsUnicodeMode());
2010 if (!formatOK ||
2011 pFE->ptd != 0 ||
2012 (pFE->dwAspect & DVASPECT_CONTENT) == 0 ||
2013 pFE->lindex != -1 ||
2014 (pFE->tymed & TYMED_HGLOBAL) == 0
2016 //Platform::DebugPrintf("DOB QueryGetData No %x\n",pFE->cfFormat);
2017 //return DATA_E_FORMATETC;
2018 return S_FALSE;
2020 //Platform::DebugPrintf("DOB QueryGetData OK %x\n",pFE->cfFormat);
2021 return S_OK;
2024 STDMETHODIMP DataObject_GetCanonicalFormatEtc(DataObject *pd, FORMATETC *, FORMATETC *pFEOut) {
2025 //Platform::DebugPrintf("DOB GetCanon\n");
2026 if (pd->sci->IsUnicodeMode())
2027 pFEOut->cfFormat = CF_UNICODETEXT;
2028 else
2029 pFEOut->cfFormat = CF_TEXT;
2030 pFEOut->ptd = 0;
2031 pFEOut->dwAspect = DVASPECT_CONTENT;
2032 pFEOut->lindex = -1;
2033 pFEOut->tymed = TYMED_HGLOBAL;
2034 return S_OK;
2037 STDMETHODIMP DataObject_SetData(DataObject *, FORMATETC *, STGMEDIUM *, BOOL) {
2038 //Platform::DebugPrintf("DOB SetData\n");
2039 return E_FAIL;
2042 STDMETHODIMP DataObject_EnumFormatEtc(DataObject *pd, DWORD dwDirection, IEnumFORMATETC **ppEnum) {
2043 try {
2044 //Platform::DebugPrintf("DOB EnumFormatEtc %d\n", dwDirection);
2045 if (dwDirection != DATADIR_GET) {
2046 *ppEnum = 0;
2047 return E_FAIL;
2049 FormatEnumerator *pfe;
2050 if (pd->sci->IsUnicodeMode()) {
2051 CLIPFORMAT formats[] = {CF_UNICODETEXT, CF_TEXT};
2052 pfe = new FormatEnumerator(0, formats, 2);
2053 } else {
2054 CLIPFORMAT formats[] = {CF_TEXT};
2055 pfe = new FormatEnumerator(0, formats, 1);
2057 return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
2058 reinterpret_cast<void **>(ppEnum));
2059 } catch (std::bad_alloc &) {
2060 pd->sci->errorStatus = SC_STATUS_BADALLOC;
2061 return E_OUTOFMEMORY;
2062 } catch (...) {
2063 pd->sci->errorStatus = SC_STATUS_FAILURE;
2064 return E_FAIL;
2068 STDMETHODIMP DataObject_DAdvise(DataObject *, FORMATETC *, DWORD, IAdviseSink *, PDWORD) {
2069 //Platform::DebugPrintf("DOB DAdvise\n");
2070 return E_FAIL;
2073 STDMETHODIMP DataObject_DUnadvise(DataObject *, DWORD) {
2074 //Platform::DebugPrintf("DOB DUnadvise\n");
2075 return E_FAIL;
2078 STDMETHODIMP DataObject_EnumDAdvise(DataObject *, IEnumSTATDATA **) {
2079 //Platform::DebugPrintf("DOB EnumDAdvise\n");
2080 return E_FAIL;
2083 static VFunction *vtDataObject[] = {
2084 (VFunction *)(DataObject_QueryInterface),
2085 (VFunction *)(DataObject_AddRef),
2086 (VFunction *)(DataObject_Release),
2087 (VFunction *)(DataObject_GetData),
2088 (VFunction *)(DataObject_GetDataHere),
2089 (VFunction *)(DataObject_QueryGetData),
2090 (VFunction *)(DataObject_GetCanonicalFormatEtc),
2091 (VFunction *)(DataObject_SetData),
2092 (VFunction *)(DataObject_EnumFormatEtc),
2093 (VFunction *)(DataObject_DAdvise),
2094 (VFunction *)(DataObject_DUnadvise),
2095 (VFunction *)(DataObject_EnumDAdvise)
2098 DataObject::DataObject() {
2099 vtbl = vtDataObject;
2100 sci = 0;
2103 /// Implement IUnknown
2104 STDMETHODIMP DropTarget_QueryInterface(DropTarget *dt, REFIID riid, PVOID *ppv) {
2105 //Platform::DebugPrintf("DT QI %x\n", dt);
2106 return dt->sci->QueryInterface(riid, ppv);
2108 STDMETHODIMP_(ULONG)DropTarget_AddRef(DropTarget *dt) {
2109 return dt->sci->AddRef();
2111 STDMETHODIMP_(ULONG)DropTarget_Release(DropTarget *dt) {
2112 return dt->sci->Release();
2115 /// Implement IDropTarget by forwarding to Scintilla
2116 STDMETHODIMP DropTarget_DragEnter(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2117 POINTL pt, PDWORD pdwEffect) {
2118 try {
2119 return dt->sci->DragEnter(pIDataSource, grfKeyState, pt, pdwEffect);
2120 } catch (...) {
2121 dt->sci->errorStatus = SC_STATUS_FAILURE;
2123 return E_FAIL;
2125 STDMETHODIMP DropTarget_DragOver(DropTarget *dt, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
2126 try {
2127 return dt->sci->DragOver(grfKeyState, pt, pdwEffect);
2128 } catch (...) {
2129 dt->sci->errorStatus = SC_STATUS_FAILURE;
2131 return E_FAIL;
2133 STDMETHODIMP DropTarget_DragLeave(DropTarget *dt) {
2134 try {
2135 return dt->sci->DragLeave();
2136 } catch (...) {
2137 dt->sci->errorStatus = SC_STATUS_FAILURE;
2139 return E_FAIL;
2141 STDMETHODIMP DropTarget_Drop(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2142 POINTL pt, PDWORD pdwEffect) {
2143 try {
2144 return dt->sci->Drop(pIDataSource, grfKeyState, pt, pdwEffect);
2145 } catch (...) {
2146 dt->sci->errorStatus = SC_STATUS_FAILURE;
2148 return E_FAIL;
2151 static VFunction *vtDropTarget[] = {
2152 (VFunction *)(DropTarget_QueryInterface),
2153 (VFunction *)(DropTarget_AddRef),
2154 (VFunction *)(DropTarget_Release),
2155 (VFunction *)(DropTarget_DragEnter),
2156 (VFunction *)(DropTarget_DragOver),
2157 (VFunction *)(DropTarget_DragLeave),
2158 (VFunction *)(DropTarget_Drop)
2161 DropTarget::DropTarget() {
2162 vtbl = vtDropTarget;
2163 sci = 0;
2167 * DBCS: support Input Method Editor (IME).
2168 * Called when IME Window opened.
2170 void ScintillaWin::ImeStartComposition() {
2171 #ifndef __DMC__
2172 // Digital Mars compiler does not include Imm library
2173 if (caret.active) {
2174 // Move IME Window to current caret position
2175 HIMC hIMC = ::ImmGetContext(MainHWND());
2176 Point pos = PointMainCaret();
2177 COMPOSITIONFORM CompForm;
2178 CompForm.dwStyle = CFS_POINT;
2179 CompForm.ptCurrentPos.x = pos.x;
2180 CompForm.ptCurrentPos.y = pos.y;
2182 ::ImmSetCompositionWindow(hIMC, &CompForm);
2184 // Set font of IME window to same as surrounded text.
2185 if (stylesValid) {
2186 // Since the style creation code has been made platform independent,
2187 // The logfont for the IME is recreated here.
2188 int styleHere = (pdoc->StyleAt(sel.MainCaret())) & 31;
2189 LOGFONTA lf = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ""};
2190 int sizeZoomed = vs.styles[styleHere].size + vs.zoomLevel * SC_FONT_SIZE_MULTIPLIER;
2191 if (sizeZoomed <= 2 * SC_FONT_SIZE_MULTIPLIER) // Hangs if sizeZoomed <= 1
2192 sizeZoomed = 2 * SC_FONT_SIZE_MULTIPLIER;
2193 AutoSurface surface(this);
2194 int deviceHeight = sizeZoomed;
2195 if (surface) {
2196 deviceHeight = (sizeZoomed * surface->LogPixelsY()) / 72;
2198 // The negative is to allow for leading
2199 lf.lfHeight = -(abs(deviceHeight / SC_FONT_SIZE_MULTIPLIER));
2200 lf.lfWeight = vs.styles[styleHere].weight;
2201 lf.lfItalic = static_cast<BYTE>(vs.styles[styleHere].italic ? 1 : 0);
2202 lf.lfCharSet = DEFAULT_CHARSET;
2203 lf.lfFaceName[0] = '\0';
2204 if (vs.styles[styleHere].fontName)
2205 strcpy(lf.lfFaceName, vs.styles[styleHere].fontName);
2207 ::ImmSetCompositionFontA(hIMC, &lf);
2209 ::ImmReleaseContext(MainHWND(), hIMC);
2210 // Caret is displayed in IME window. So, caret in Scintilla is useless.
2211 DropCaret();
2213 #endif
2216 /** Called when IME Window closed. */
2217 void ScintillaWin::ImeEndComposition() {
2218 ShowCaretAtCurrentPosition();
2221 void ScintillaWin::AddCharBytes(char b0, char b1) {
2223 int inputCodePage = InputCodePage();
2224 if (inputCodePage && IsUnicodeMode()) {
2225 char utfval[4] = "\0\0\0";
2226 char ansiChars[3];
2227 wchar_t wcs[2];
2228 if (b0) { // Two bytes from IME
2229 ansiChars[0] = b0;
2230 ansiChars[1] = b1;
2231 ansiChars[2] = '\0';
2232 ::MultiByteToWideChar(inputCodePage, 0, ansiChars, 2, wcs, 1);
2233 } else {
2234 ansiChars[0] = b1;
2235 ansiChars[1] = '\0';
2236 ::MultiByteToWideChar(inputCodePage, 0, ansiChars, 1, wcs, 1);
2238 unsigned int len = UTF8Length(wcs, 1);
2239 UTF8FromUTF16(wcs, 1, utfval, len);
2240 utfval[len] = '\0';
2241 AddCharUTF(utfval, len ? len : 1);
2242 } else if (b0) {
2243 char dbcsChars[3];
2244 dbcsChars[0] = b0;
2245 dbcsChars[1] = b1;
2246 dbcsChars[2] = '\0';
2247 AddCharUTF(dbcsChars, 2, true);
2248 } else {
2249 AddChar(b1);
2253 void ScintillaWin::GetIntelliMouseParameters() {
2254 // This retrieves the number of lines per scroll as configured inthe Mouse Properties sheet in Control Panel
2255 ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
2258 void ScintillaWin::CopyToClipboard(const SelectionText &selectedText) {
2259 if (!::OpenClipboard(MainHWND()))
2260 return;
2261 ::EmptyClipboard();
2263 GlobalMemory uniText;
2265 // Default Scintilla behaviour in Unicode mode
2266 if (IsUnicodeMode()) {
2267 int uchars = UTF16Length(selectedText.s, selectedText.len);
2268 uniText.Allocate(2 * uchars);
2269 if (uniText) {
2270 UTF16FromUTF8(selectedText.s, selectedText.len, static_cast<wchar_t *>(uniText.ptr), uchars);
2272 } else {
2273 // Not Unicode mode
2274 // Convert to Unicode using the current Scintilla code page
2275 UINT cpSrc = CodePageFromCharSet(
2276 selectedText.characterSet, selectedText.codePage);
2277 int uLen = ::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len, 0, 0);
2278 uniText.Allocate(2 * uLen);
2279 if (uniText) {
2280 ::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len,
2281 static_cast<wchar_t *>(uniText.ptr), uLen);
2285 if (uniText) {
2286 if (!IsNT()) {
2287 // Copy ANSI text to clipboard on Windows 9x
2288 // Convert from Unicode text, so other ANSI programs can
2289 // paste the text
2290 // Windows NT, 2k, XP automatically generates CF_TEXT
2291 GlobalMemory ansiText;
2292 ansiText.Allocate(selectedText.len);
2293 if (ansiText) {
2294 ::WideCharToMultiByte(CP_ACP, 0, static_cast<wchar_t *>(uniText.ptr), -1,
2295 static_cast<char *>(ansiText.ptr), selectedText.len, NULL, NULL);
2296 ansiText.SetClip(CF_TEXT);
2299 uniText.SetClip(CF_UNICODETEXT);
2300 } else {
2301 // There was a failure - try to copy at least ANSI text
2302 GlobalMemory ansiText;
2303 ansiText.Allocate(selectedText.len);
2304 if (ansiText) {
2305 memcpy(static_cast<char *>(ansiText.ptr), selectedText.s, selectedText.len);
2306 ansiText.SetClip(CF_TEXT);
2310 if (selectedText.rectangular) {
2311 ::SetClipboardData(cfColumnSelect, 0);
2314 if (selectedText.lineCopy) {
2315 ::SetClipboardData(cfLineSelect, 0);
2318 ::CloseClipboard();
2321 void ScintillaWin::ScrollMessage(WPARAM wParam) {
2322 //DWORD dwStart = timeGetTime();
2323 //Platform::DebugPrintf("Scroll %x %d\n", wParam, lParam);
2325 SCROLLINFO sci;
2326 memset(&sci, 0, sizeof(sci));
2327 sci.cbSize = sizeof(sci);
2328 sci.fMask = SIF_ALL;
2330 GetScrollInfo(SB_VERT, &sci);
2332 //Platform::DebugPrintf("ScrollInfo %d mask=%x min=%d max=%d page=%d pos=%d track=%d\n", b,sci.fMask,
2333 //sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
2335 int topLineNew = topLine;
2336 switch (LoWord(wParam)) {
2337 case SB_LINEUP:
2338 topLineNew -= 1;
2339 break;
2340 case SB_LINEDOWN:
2341 topLineNew += 1;
2342 break;
2343 case SB_PAGEUP:
2344 topLineNew -= LinesToScroll(); break;
2345 case SB_PAGEDOWN: topLineNew += LinesToScroll(); break;
2346 case SB_TOP: topLineNew = 0; break;
2347 case SB_BOTTOM: topLineNew = MaxScrollPos(); break;
2348 case SB_THUMBPOSITION: topLineNew = sci.nTrackPos; break;
2349 case SB_THUMBTRACK: topLineNew = sci.nTrackPos; break;
2351 ScrollTo(topLineNew);
2354 void ScintillaWin::HorizontalScrollMessage(WPARAM wParam) {
2355 int xPos = xOffset;
2356 PRectangle rcText = GetTextRectangle();
2357 int pageWidth = rcText.Width() * 2 / 3;
2358 switch (LoWord(wParam)) {
2359 case SB_LINEUP:
2360 xPos -= 20;
2361 break;
2362 case SB_LINEDOWN: // May move past the logical end
2363 xPos += 20;
2364 break;
2365 case SB_PAGEUP:
2366 xPos -= pageWidth;
2367 break;
2368 case SB_PAGEDOWN:
2369 xPos += pageWidth;
2370 if (xPos > scrollWidth - rcText.Width()) { // Hit the end exactly
2371 xPos = scrollWidth - rcText.Width();
2373 break;
2374 case SB_TOP:
2375 xPos = 0;
2376 break;
2377 case SB_BOTTOM:
2378 xPos = scrollWidth;
2379 break;
2380 case SB_THUMBPOSITION:
2381 case SB_THUMBTRACK: {
2382 // Do NOT use wParam, its 16 bit and not enough for very long lines. Its still possible to overflow the 32 bit but you have to try harder =]
2383 SCROLLINFO si;
2384 si.cbSize = sizeof(si);
2385 si.fMask = SIF_TRACKPOS;
2386 if (GetScrollInfo(SB_HORZ, &si)) {
2387 xPos = si.nTrackPos;
2390 break;
2392 HorizontalScrollTo(xPos);
2396 * Redraw all of text area.
2397 * This paint will not be abandoned.
2399 void ScintillaWin::FullPaint() {
2400 if (technology == SC_TECHNOLOGY_DEFAULT) {
2401 HDC hdc = ::GetDC(MainHWND());
2402 FullPaintDC(hdc);
2403 ::ReleaseDC(MainHWND(), hdc);
2404 } else {
2405 FullPaintDC(0);
2410 * Redraw all of text area on the specified DC.
2411 * This paint will not be abandoned.
2413 void ScintillaWin::FullPaintDC(HDC hdc) {
2414 paintState = painting;
2415 rcPaint = GetClientRectangle();
2416 paintingAllText = true;
2417 if (technology == SC_TECHNOLOGY_DEFAULT) {
2418 AutoSurface surfaceWindow(hdc, this);
2419 if (surfaceWindow) {
2420 Paint(surfaceWindow, rcPaint);
2421 surfaceWindow->Release();
2423 } else {
2424 #if defined(USE_D2D)
2425 EnsureRenderTarget();
2426 AutoSurface surfaceWindow(pRenderTarget, this);
2427 if (surfaceWindow) {
2428 pRenderTarget->BeginDraw();
2429 Paint(surfaceWindow, rcPaint);
2430 surfaceWindow->Release();
2431 HRESULT hr = pRenderTarget->EndDraw();
2432 if (hr == D2DERR_RECREATE_TARGET) {
2433 DropRenderTarget();
2436 #endif
2438 paintState = notPainting;
2441 static bool CompareDevCap(HDC hdc, HDC hOtherDC, int nIndex) {
2442 return ::GetDeviceCaps(hdc, nIndex) == ::GetDeviceCaps(hOtherDC, nIndex);
2445 bool ScintillaWin::IsCompatibleDC(HDC hOtherDC) {
2446 HDC hdc = ::GetDC(MainHWND());
2447 bool isCompatible =
2448 CompareDevCap(hdc, hOtherDC, TECHNOLOGY) &&
2449 CompareDevCap(hdc, hOtherDC, LOGPIXELSY) &&
2450 CompareDevCap(hdc, hOtherDC, LOGPIXELSX) &&
2451 CompareDevCap(hdc, hOtherDC, BITSPIXEL) &&
2452 CompareDevCap(hdc, hOtherDC, PLANES);
2453 ::ReleaseDC(MainHWND(), hdc);
2454 return isCompatible;
2457 DWORD ScintillaWin::EffectFromState(DWORD grfKeyState) {
2458 // These are the Wordpad semantics.
2459 DWORD dwEffect;
2460 if (inDragDrop == ddDragging) // Internal defaults to move
2461 dwEffect = DROPEFFECT_MOVE;
2462 else
2463 dwEffect = DROPEFFECT_COPY;
2464 if (grfKeyState & MK_ALT)
2465 dwEffect = DROPEFFECT_MOVE;
2466 if (grfKeyState & MK_CONTROL)
2467 dwEffect = DROPEFFECT_COPY;
2468 return dwEffect;
2471 /// Implement IUnknown
2472 STDMETHODIMP ScintillaWin::QueryInterface(REFIID riid, PVOID *ppv) {
2473 *ppv = NULL;
2474 if (riid == IID_IUnknown)
2475 *ppv = reinterpret_cast<IDropTarget *>(&dt);
2476 if (riid == IID_IDropSource)
2477 *ppv = reinterpret_cast<IDropSource *>(&ds);
2478 if (riid == IID_IDropTarget)
2479 *ppv = reinterpret_cast<IDropTarget *>(&dt);
2480 if (riid == IID_IDataObject)
2481 *ppv = reinterpret_cast<IDataObject *>(&dob);
2482 if (!*ppv)
2483 return E_NOINTERFACE;
2484 return S_OK;
2487 STDMETHODIMP_(ULONG) ScintillaWin::AddRef() {
2488 return 1;
2491 STDMETHODIMP_(ULONG) ScintillaWin::Release() {
2492 return 1;
2495 /// Implement IDropTarget
2496 STDMETHODIMP ScintillaWin::DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2497 POINTL, PDWORD pdwEffect) {
2498 if (pIDataSource == NULL)
2499 return E_POINTER;
2500 FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
2501 HRESULT hrHasUText = pIDataSource->QueryGetData(&fmtu);
2502 hasOKText = (hrHasUText == S_OK);
2503 if (!hasOKText) {
2504 FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
2505 HRESULT hrHasText = pIDataSource->QueryGetData(&fmte);
2506 hasOKText = (hrHasText == S_OK);
2508 if (!hasOKText) {
2509 *pdwEffect = DROPEFFECT_NONE;
2510 return S_OK;
2513 *pdwEffect = EffectFromState(grfKeyState);
2514 return S_OK;
2517 STDMETHODIMP ScintillaWin::DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
2518 try {
2519 if (!hasOKText || pdoc->IsReadOnly()) {
2520 *pdwEffect = DROPEFFECT_NONE;
2521 return S_OK;
2524 *pdwEffect = EffectFromState(grfKeyState);
2526 // Update the cursor.
2527 POINT rpt = {pt.x, pt.y};
2528 ::ScreenToClient(MainHWND(), &rpt);
2529 SetDragPosition(SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace()));
2531 return S_OK;
2532 } catch (...) {
2533 errorStatus = SC_STATUS_FAILURE;
2535 return E_FAIL;
2538 STDMETHODIMP ScintillaWin::DragLeave() {
2539 try {
2540 SetDragPosition(SelectionPosition(invalidPosition));
2541 return S_OK;
2542 } catch (...) {
2543 errorStatus = SC_STATUS_FAILURE;
2545 return E_FAIL;
2548 STDMETHODIMP ScintillaWin::Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2549 POINTL pt, PDWORD pdwEffect) {
2550 try {
2551 *pdwEffect = EffectFromState(grfKeyState);
2553 if (pIDataSource == NULL)
2554 return E_POINTER;
2556 SetDragPosition(SelectionPosition(invalidPosition));
2558 STGMEDIUM medium = {0, {0}, 0};
2560 char *data = 0;
2561 bool dataAllocated = false;
2563 FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
2564 HRESULT hr = pIDataSource->GetData(&fmtu, &medium);
2565 if (SUCCEEDED(hr) && medium.hGlobal) {
2566 wchar_t *udata = static_cast<wchar_t *>(::GlobalLock(medium.hGlobal));
2567 if (IsUnicodeMode()) {
2568 int tlen = ::GlobalSize(medium.hGlobal);
2569 // Convert UTF-16 to UTF-8
2570 int dataLen = UTF8Length(udata, tlen/2);
2571 data = new char[dataLen+1];
2572 UTF8FromUTF16(udata, tlen/2, data, dataLen);
2573 dataAllocated = true;
2574 } else {
2575 // Convert UTF-16 to ANSI
2577 // Default Scintilla behavior in Unicode mode
2578 // CF_UNICODETEXT available, but not in Unicode mode
2579 // Convert from Unicode to current Scintilla code page
2580 UINT cpDest = CodePageOfDocument();
2581 int tlen = ::WideCharToMultiByte(cpDest, 0, udata, -1,
2582 NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
2583 data = new char[tlen + 1];
2584 memset(data, 0, (tlen+1));
2585 ::WideCharToMultiByte(cpDest, 0, udata, -1,
2586 data, tlen + 1, NULL, NULL);
2587 dataAllocated = true;
2591 if (!data) {
2592 FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
2593 hr = pIDataSource->GetData(&fmte, &medium);
2594 if (SUCCEEDED(hr) && medium.hGlobal) {
2595 data = static_cast<char *>(::GlobalLock(medium.hGlobal));
2599 if (data && convertPastes) {
2600 // Convert line endings of the drop into our local line-endings mode
2601 int len = static_cast<int>(strlen(data));
2602 char *convertedText = Document::TransformLineEnds(&len, data, len, pdoc->eolMode);
2603 if (dataAllocated)
2604 delete []data;
2605 data = convertedText;
2606 dataAllocated = true;
2609 if (!data) {
2610 //Platform::DebugPrintf("Bad data format: 0x%x\n", hres);
2611 return hr;
2614 FORMATETC fmtr = {cfColumnSelect, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
2615 HRESULT hrRectangular = pIDataSource->QueryGetData(&fmtr);
2617 POINT rpt = {pt.x, pt.y};
2618 ::ScreenToClient(MainHWND(), &rpt);
2619 SelectionPosition movePos = SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace());
2621 DropAt(movePos, data, *pdwEffect == DROPEFFECT_MOVE, hrRectangular == S_OK);
2623 ::GlobalUnlock(medium.hGlobal);
2625 // Free data
2626 if (medium.pUnkForRelease != NULL)
2627 medium.pUnkForRelease->Release();
2628 else
2629 ::GlobalFree(medium.hGlobal);
2631 if (dataAllocated)
2632 delete []data;
2634 return S_OK;
2635 } catch (...) {
2636 errorStatus = SC_STATUS_FAILURE;
2638 return E_FAIL;
2641 /// Implement important part of IDataObject
2642 STDMETHODIMP ScintillaWin::GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM) {
2643 bool formatOK = (pFEIn->cfFormat == CF_TEXT) ||
2644 ((pFEIn->cfFormat == CF_UNICODETEXT) && IsUnicodeMode());
2645 if (!formatOK ||
2646 pFEIn->ptd != 0 ||
2647 (pFEIn->dwAspect & DVASPECT_CONTENT) == 0 ||
2648 pFEIn->lindex != -1 ||
2649 (pFEIn->tymed & TYMED_HGLOBAL) == 0
2651 //Platform::DebugPrintf("DOB GetData No %d %x %x fmt=%x\n", lenDrag, pFEIn, pSTM, pFEIn->cfFormat);
2652 return DATA_E_FORMATETC;
2654 pSTM->tymed = TYMED_HGLOBAL;
2655 //Platform::DebugPrintf("DOB GetData OK %d %x %x\n", lenDrag, pFEIn, pSTM);
2657 GlobalMemory text;
2658 if (pFEIn->cfFormat == CF_UNICODETEXT) {
2659 int uchars = UTF16Length(drag.s, drag.len);
2660 text.Allocate(2 * uchars);
2661 if (text) {
2662 UTF16FromUTF8(drag.s, drag.len, static_cast<wchar_t *>(text.ptr), uchars);
2664 } else {
2665 text.Allocate(drag.len);
2666 if (text) {
2667 memcpy(static_cast<char *>(text.ptr), drag.s, drag.len);
2670 pSTM->hGlobal = text ? text.Unlock() : 0;
2671 pSTM->pUnkForRelease = 0;
2672 return S_OK;
2675 bool ScintillaWin::Register(HINSTANCE hInstance_) {
2677 hInstance = hInstance_;
2678 bool result;
2680 // Register the Scintilla class
2681 if (IsNT()) {
2683 // Register Scintilla as a wide character window
2684 WNDCLASSEXW wndclass;
2685 wndclass.cbSize = sizeof(wndclass);
2686 wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
2687 wndclass.lpfnWndProc = ScintillaWin::SWndProc;
2688 wndclass.cbClsExtra = 0;
2689 wndclass.cbWndExtra = sizeof(ScintillaWin *);
2690 wndclass.hInstance = hInstance;
2691 wndclass.hIcon = NULL;
2692 wndclass.hCursor = NULL;
2693 wndclass.hbrBackground = NULL;
2694 wndclass.lpszMenuName = NULL;
2695 wndclass.lpszClassName = L"Scintilla";
2696 wndclass.hIconSm = 0;
2697 result = ::RegisterClassExW(&wndclass) != 0;
2698 } else {
2700 // Register Scintilla as a normal character window
2701 WNDCLASSEX wndclass;
2702 wndclass.cbSize = sizeof(wndclass);
2703 wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
2704 wndclass.lpfnWndProc = ScintillaWin::SWndProc;
2705 wndclass.cbClsExtra = 0;
2706 wndclass.cbWndExtra = sizeof(ScintillaWin *);
2707 wndclass.hInstance = hInstance;
2708 wndclass.hIcon = NULL;
2709 wndclass.hCursor = NULL;
2710 wndclass.hbrBackground = NULL;
2711 wndclass.lpszMenuName = NULL;
2712 wndclass.lpszClassName = scintillaClassName;
2713 wndclass.hIconSm = 0;
2714 result = ::RegisterClassEx(&wndclass) != 0;
2717 if (result) {
2718 // Register the CallTip class
2719 WNDCLASSEX wndclassc;
2720 wndclassc.cbSize = sizeof(wndclassc);
2721 wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
2722 wndclassc.cbClsExtra = 0;
2723 wndclassc.cbWndExtra = sizeof(ScintillaWin *);
2724 wndclassc.hInstance = hInstance;
2725 wndclassc.hIcon = NULL;
2726 wndclassc.hbrBackground = NULL;
2727 wndclassc.lpszMenuName = NULL;
2728 wndclassc.lpfnWndProc = ScintillaWin::CTWndProc;
2729 wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
2730 wndclassc.lpszClassName = callClassName;
2731 wndclassc.hIconSm = 0;
2733 result = ::RegisterClassEx(&wndclassc) != 0;
2736 return result;
2739 bool ScintillaWin::Unregister() {
2740 bool result = ::UnregisterClass(scintillaClassName, hInstance) != 0;
2741 if (::UnregisterClass(callClassName, hInstance) == 0)
2742 result = false;
2743 return result;
2746 bool ScintillaWin::HasCaretSizeChanged() {
2747 if (
2748 ( (0 != vs.caretWidth) && (sysCaretWidth != vs.caretWidth) )
2749 || ((0 != vs.lineHeight) && (sysCaretHeight != vs.lineHeight))
2751 return true;
2753 return false;
2756 BOOL ScintillaWin::CreateSystemCaret() {
2757 sysCaretWidth = vs.caretWidth;
2758 if (0 == sysCaretWidth) {
2759 sysCaretWidth = 1;
2761 sysCaretHeight = vs.lineHeight;
2762 int bitmapSize = (((sysCaretWidth + 15) & ~15) >> 3) *
2763 sysCaretHeight;
2764 char *bits = new char[bitmapSize];
2765 memset(bits, 0, bitmapSize);
2766 sysCaretBitmap = ::CreateBitmap(sysCaretWidth, sysCaretHeight, 1,
2767 1, reinterpret_cast<BYTE *>(bits));
2768 delete []bits;
2769 BOOL retval = ::CreateCaret(
2770 MainHWND(), sysCaretBitmap,
2771 sysCaretWidth, sysCaretHeight);
2772 ::ShowCaret(MainHWND());
2773 return retval;
2776 BOOL ScintillaWin::DestroySystemCaret() {
2777 ::HideCaret(MainHWND());
2778 BOOL retval = ::DestroyCaret();
2779 if (sysCaretBitmap) {
2780 ::DeleteObject(sysCaretBitmap);
2781 sysCaretBitmap = 0;
2783 return retval;
2786 sptr_t PASCAL ScintillaWin::CTWndProc(
2787 HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
2788 // Find C++ object associated with window.
2789 ScintillaWin *sciThis = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
2790 try {
2791 // ctp will be zero if WM_CREATE not seen yet
2792 if (sciThis == 0) {
2793 if (iMessage == WM_CREATE) {
2794 // Associate CallTip object with window
2795 CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
2796 SetWindowPointer(hWnd, pCreate->lpCreateParams);
2797 return 0;
2798 } else {
2799 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2801 } else {
2802 if (iMessage == WM_NCDESTROY) {
2803 ::SetWindowLong(hWnd, 0, 0);
2804 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2805 } else if (iMessage == WM_PAINT) {
2806 PAINTSTRUCT ps;
2807 ::BeginPaint(hWnd, &ps);
2808 Surface *surfaceWindow = Surface::Allocate(sciThis->technology);
2809 if (surfaceWindow) {
2810 #if defined(USE_D2D)
2811 ID2D1HwndRenderTarget *pCTRenderTarget = 0;
2812 #endif
2813 RECT rc;
2814 GetClientRect(hWnd, &rc);
2815 // Create a Direct2D render target.
2816 if (sciThis->technology == SC_TECHNOLOGY_DEFAULT) {
2817 surfaceWindow->Init(ps.hdc, hWnd);
2818 } else {
2819 #if defined(USE_D2D)
2820 pD2DFactory->CreateHwndRenderTarget(
2821 D2D1::RenderTargetProperties(),
2822 D2D1::HwndRenderTargetProperties(hWnd, D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)),
2823 &pCTRenderTarget);
2824 surfaceWindow->Init(pCTRenderTarget, hWnd);
2825 pCTRenderTarget->BeginDraw();
2826 #endif
2828 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == sciThis->ct.codePage);
2829 surfaceWindow->SetDBCSMode(sciThis->ct.codePage);
2830 sciThis->ct.PaintCT(surfaceWindow);
2831 #if defined(USE_D2D)
2832 if (pCTRenderTarget)
2833 pCTRenderTarget->EndDraw();
2834 #endif
2835 surfaceWindow->Release();
2836 delete surfaceWindow;
2837 #if defined(USE_D2D)
2838 if (pCTRenderTarget)
2839 pCTRenderTarget->Release();
2840 #endif
2842 ::EndPaint(hWnd, &ps);
2843 return 0;
2844 } else if ((iMessage == WM_NCLBUTTONDOWN) || (iMessage == WM_NCLBUTTONDBLCLK)) {
2845 POINT pt;
2846 pt.x = static_cast<short>(LOWORD(lParam));
2847 pt.y = static_cast<short>(HIWORD(lParam));
2848 ScreenToClient(hWnd, &pt);
2849 sciThis->ct.MouseClick(Point(pt.x, pt.y));
2850 sciThis->CallTipClick();
2851 return 0;
2852 } else if (iMessage == WM_LBUTTONDOWN) {
2853 // This does not fire due to the hit test code
2854 sciThis->ct.MouseClick(Point::FromLong(lParam));
2855 sciThis->CallTipClick();
2856 return 0;
2857 } else if (iMessage == WM_SETCURSOR) {
2858 ::SetCursor(::LoadCursor(NULL, IDC_ARROW));
2859 return 0;
2860 } else if (iMessage == WM_NCHITTEST) {
2861 return HTCAPTION;
2862 } else {
2863 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2866 } catch (...) {
2867 sciThis->errorStatus = SC_STATUS_FAILURE;
2869 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2872 sptr_t ScintillaWin::DirectFunction(
2873 ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
2874 PLATFORM_ASSERT(::GetCurrentThreadId() == ::GetWindowThreadProcessId(sci->MainHWND(), NULL));
2875 return sci->WndProc(iMessage, wParam, lParam);
2878 extern "C"
2879 #ifndef STATIC_BUILD
2880 __declspec(dllexport)
2881 #endif
2882 sptr_t __stdcall Scintilla_DirectFunction(
2883 ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
2884 return sci->WndProc(iMessage, wParam, lParam);
2887 sptr_t PASCAL ScintillaWin::SWndProc(
2888 HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
2889 //Platform::DebugPrintf("S W:%x M:%x WP:%x L:%x\n", hWnd, iMessage, wParam, lParam);
2891 // Find C++ object associated with window.
2892 ScintillaWin *sci = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
2893 // sci will be zero if WM_CREATE not seen yet
2894 if (sci == 0) {
2895 try {
2896 if (iMessage == WM_CREATE) {
2897 // Create C++ object associated with window
2898 sci = new ScintillaWin(hWnd);
2899 SetWindowPointer(hWnd, sci);
2900 return sci->WndProc(iMessage, wParam, lParam);
2902 } catch (...) {
2904 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2905 } else {
2906 if (iMessage == WM_NCDESTROY) {
2907 try {
2908 sci->Finalise();
2909 delete sci;
2910 } catch (...) {
2912 ::SetWindowLong(hWnd, 0, 0);
2913 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2914 } else {
2915 return sci->WndProc(iMessage, wParam, lParam);
2920 // This function is externally visible so it can be called from container when building statically.
2921 // Must be called once only.
2922 int Scintilla_RegisterClasses(void *hInstance) {
2923 Platform_Initialise(hInstance);
2924 bool result = ScintillaWin::Register(reinterpret_cast<HINSTANCE>(hInstance));
2925 #ifdef SCI_LEXER
2926 Scintilla_LinkLexers();
2927 #endif
2928 return result;
2931 // This function is externally visible so it can be called from container when building statically.
2932 int Scintilla_ReleaseResources() {
2933 bool result = ScintillaWin::Unregister();
2934 Platform_Finalise();
2935 return result;
2938 #ifndef STATIC_BUILD
2939 extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID) {
2940 //Platform::DebugPrintf("Scintilla::DllMain %d %d\n", hInstance, dwReason);
2941 if (dwReason == DLL_PROCESS_ATTACH) {
2942 if (!Scintilla_RegisterClasses(hInstance))
2943 return FALSE;
2944 } else if (dwReason == DLL_PROCESS_DETACH) {
2945 Scintilla_ReleaseResources();
2947 return TRUE;
2949 #endif