Applied backgroundcolors.patch
[TortoiseGit.git] / ext / scintilla / win32 / ScintillaWin.cxx
blobe5347d16d2f23199380ae647c289ea93e9b81946
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 <stdlib.h>
9 #include <string.h>
10 #include <stdio.h>
11 #include <assert.h>
12 #include <ctype.h>
13 #include <limits.h>
15 #include <cmath>
16 #include <stdexcept>
17 #include <new>
18 #include <string>
19 #include <vector>
20 #include <map>
21 #include <algorithm>
23 #undef _WIN32_WINNT
24 #define _WIN32_WINNT 0x0500
25 #undef WINVER
26 #define WINVER 0x0500
27 #include <windows.h>
28 #include <commctrl.h>
29 #include <richedit.h>
30 #include <windowsx.h>
31 #include <zmouse.h>
32 #include <ole2.h>
34 #if defined(NTDDI_WIN7) && !defined(DISABLE_D2D)
35 #define USE_D2D 1
36 #endif
38 #if defined(USE_D2D)
39 #include <d2d1.h>
40 #include <dwrite.h>
41 #endif
43 #include "Platform.h"
45 #include "ILexer.h"
46 #include "Scintilla.h"
48 #ifdef SCI_LEXER
49 #include "SciLexer.h"
50 #endif
51 #include "StringCopy.h"
52 #ifdef SCI_LEXER
53 #include "LexerModule.h"
54 #endif
55 #include "Position.h"
56 #include "SplitVector.h"
57 #include "Partitioning.h"
58 #include "RunStyles.h"
59 #include "ContractionState.h"
60 #include "CellBuffer.h"
61 #include "CallTip.h"
62 #include "KeyMap.h"
63 #include "Indicator.h"
64 #include "XPM.h"
65 #include "LineMarker.h"
66 #include "Style.h"
67 #include "ViewStyle.h"
68 #include "CharClassify.h"
69 #include "Decoration.h"
70 #include "CaseFolder.h"
71 #include "Document.h"
72 #include "CaseConvert.h"
73 #include "UniConversion.h"
74 #include "Selection.h"
75 #include "PositionCache.h"
76 #include "EditModel.h"
77 #include "MarginView.h"
78 #include "EditView.h"
79 #include "Editor.h"
81 #include "AutoComplete.h"
82 #include "ScintillaBase.h"
84 #ifdef SCI_LEXER
85 #include "ExternalLexer.h"
86 #endif
88 #include "PlatWin.h"
89 #include "HanjaDic.h"
91 #ifndef SPI_GETWHEELSCROLLLINES
92 #define SPI_GETWHEELSCROLLLINES 104
93 #endif
95 #ifndef WM_UNICHAR
96 #define WM_UNICHAR 0x0109
97 #endif
99 #ifndef UNICODE_NOCHAR
100 #define UNICODE_NOCHAR 0xFFFF
101 #endif
103 #ifndef IS_HIGH_SURROGATE
104 #define IS_HIGH_SURROGATE(x) ((x) >= SURROGATE_LEAD_FIRST && (x) <= SURROGATE_LEAD_LAST)
105 #endif
107 #ifndef IS_LOW_SURROGATE
108 #define IS_LOW_SURROGATE(x) ((x) >= SURROGATE_TRAIL_FIRST && (x) <= SURROGATE_TRAIL_LAST)
109 #endif
111 #ifndef MK_ALT
112 #define MK_ALT 32
113 #endif
115 #define SC_WIN_IDLE 5001
117 #define SC_INDICATOR_INPUT INDIC_IME
118 #define SC_INDICATOR_TARGET INDIC_IME+1
119 #define SC_INDICATOR_CONVERTED INDIC_IME+2
120 #define SC_INDICATOR_UNKNOWN INDIC_IME_MAX
122 #ifndef SCS_CAP_SETRECONVERTSTRING
123 #define SCS_CAP_SETRECONVERTSTRING 0x00000004
124 #define SCS_QUERYRECONVERTSTRING 0x00020000
125 #define SCS_SETRECONVERTSTRING 0x00010000
126 #endif
128 typedef BOOL (WINAPI *TrackMouseEventSig)(LPTRACKMOUSEEVENT);
129 typedef UINT_PTR (WINAPI *SetCoalescableTimerSig)(HWND hwnd, UINT_PTR nIDEvent,
130 UINT uElapse, TIMERPROC lpTimerFunc, ULONG uToleranceDelay);
132 // GCC has trouble with the standard COM ABI so do it the old C way with explicit vtables.
134 const TCHAR callClassName[] = TEXT("CallTip");
136 #ifdef SCI_NAMESPACE
137 using namespace Scintilla;
138 #endif
140 static void *PointerFromWindow(HWND hWnd) {
141 return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
144 static void SetWindowPointer(HWND hWnd, void *ptr) {
145 ::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
148 static void SetWindowID(HWND hWnd, int identifier) {
149 ::SetWindowLongPtr(hWnd, GWLP_ID, identifier);
152 static Point PointFromPOINT(POINT pt) {
153 return Point::FromInts(pt.x, pt.y);
156 class ScintillaWin; // Forward declaration for COM interface subobjects
158 typedef void VFunction(void);
160 static HMODULE commctrl32 = 0;
164 class FormatEnumerator {
165 public:
166 VFunction **vtbl;
167 int ref;
168 unsigned int pos;
169 std::vector<CLIPFORMAT> formats;
170 FormatEnumerator(int pos_, CLIPFORMAT formats_[], size_t formatsLen_);
175 class DropSource {
176 public:
177 VFunction **vtbl;
178 ScintillaWin *sci;
179 DropSource();
184 class DataObject {
185 public:
186 VFunction **vtbl;
187 ScintillaWin *sci;
188 DataObject();
193 class DropTarget {
194 public:
195 VFunction **vtbl;
196 ScintillaWin *sci;
197 DropTarget();
200 namespace {
202 class IMContext {
203 HWND hwnd;
204 public:
205 HIMC hIMC;
206 IMContext(HWND hwnd_) :
207 hwnd(hwnd_), hIMC(::ImmGetContext(hwnd_)) {
209 ~IMContext() {
210 if (hIMC)
211 ::ImmReleaseContext(hwnd, hIMC);
214 unsigned int GetImeCaretPos() {
215 return ImmGetCompositionStringW(hIMC, GCS_CURSORPOS, NULL, 0);
218 std::vector<BYTE> GetImeAttributes() {
219 int attrLen = ::ImmGetCompositionStringW(hIMC, GCS_COMPATTR, NULL, 0);
220 std::vector<BYTE> attr(attrLen, 0);
221 ::ImmGetCompositionStringW(hIMC, GCS_COMPATTR, &attr[0], static_cast<DWORD>(attr.size()));
222 return attr;
225 std::wstring GetCompositionString(DWORD dwIndex) {
226 const LONG byteLen = ::ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
227 std::wstring wcs(byteLen / 2, 0);
228 ::ImmGetCompositionStringW(hIMC, dwIndex, &wcs[0], byteLen);
229 return wcs;
237 class ScintillaWin :
238 public ScintillaBase {
240 bool lastKeyDownConsumed;
241 wchar_t lastHighSurrogateChar;
243 bool capturedMouse;
244 bool trackedMouseLeave;
245 TrackMouseEventSig TrackMouseEventFn;
246 SetCoalescableTimerSig SetCoalescableTimerFn;
248 unsigned int linesPerScroll; ///< Intellimouse support
249 int wheelDelta; ///< Wheel delta from roll
251 HRGN hRgnUpdate;
253 bool hasOKText;
255 CLIPFORMAT cfColumnSelect;
256 CLIPFORMAT cfBorlandIDEBlockType;
257 CLIPFORMAT cfLineSelect;
258 CLIPFORMAT cfVSLineTag;
260 HRESULT hrOle;
261 DropSource ds;
262 DataObject dob;
263 DropTarget dt;
265 static HINSTANCE hInstance;
266 static ATOM scintillaClassAtom;
267 static ATOM callClassAtom;
269 #if defined(USE_D2D)
270 ID2D1RenderTarget *pRenderTarget;
271 bool renderTargetValid;
272 #endif
274 explicit ScintillaWin(HWND hwnd);
275 ScintillaWin(const ScintillaWin &);
276 virtual ~ScintillaWin();
277 ScintillaWin &operator=(const ScintillaWin &);
279 virtual void Initialise();
280 virtual void Finalise();
281 #if defined(USE_D2D)
282 void EnsureRenderTarget(HDC hdc);
283 void DropRenderTarget();
284 #endif
285 HWND MainHWND();
287 static sptr_t DirectFunction(
288 sptr_t ptr, UINT iMessage, uptr_t wParam, sptr_t lParam);
289 static LRESULT PASCAL SWndProc(
290 HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
291 static LRESULT PASCAL CTWndProc(
292 HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
294 enum { invalidTimerID, standardTimerID, idleTimerID, fineTimerStart };
296 virtual bool DragThreshold(Point ptStart, Point ptNow);
297 virtual void StartDrag();
298 int TargetAsUTF8(char *text);
299 void AddCharUTF16(wchar_t const *wcs, unsigned int wclen);
300 int EncodedFromUTF8(char *utf8, char *encoded) const;
301 sptr_t WndPaint(uptr_t wParam);
303 sptr_t HandleCompositionWindowed(uptr_t wParam, sptr_t lParam);
304 sptr_t HandleCompositionInline(uptr_t wParam, sptr_t lParam);
305 static bool KoreanIME();
306 void MoveImeCarets(int offset);
307 void DrawImeIndicator(int indicator, int len);
308 void SetCandidateWindowPos();
309 void SelectionToHangul();
310 void EscapeHanja();
311 void ToggleHanja();
312 void AddWString(std::wstring wcs);
314 UINT CodePageOfDocument() const;
315 virtual bool ValidCodePage(int codePage) const;
316 virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
317 virtual bool SetIdle(bool on);
318 UINT_PTR timers[tickDwell+1];
319 virtual bool FineTickerAvailable();
320 virtual bool FineTickerRunning(TickReason reason);
321 virtual void FineTickerStart(TickReason reason, int millis, int tolerance);
322 virtual void FineTickerCancel(TickReason reason);
323 virtual void SetMouseCapture(bool on);
324 virtual bool HaveMouseCapture();
325 virtual void SetTrackMouseLeaveEvent(bool on);
326 virtual bool PaintContains(PRectangle rc);
327 virtual void ScrollText(int linesToMove);
328 virtual void UpdateSystemCaret();
329 virtual void SetVerticalScrollPos();
330 virtual void SetHorizontalScrollPos();
331 virtual bool ModifyScrollBars(int nMax, int nPage);
332 virtual void NotifyChange();
333 virtual void NotifyFocus(bool focus);
334 virtual void SetCtrlID(int identifier);
335 virtual int GetCtrlID();
336 virtual void NotifyParent(SCNotification scn);
337 virtual void NotifyParent(SCNotification * scn);
338 virtual void NotifyDoubleClick(Point pt, int modifiers);
339 virtual CaseFolder *CaseFolderForEncoding();
340 virtual std::string CaseMapString(const std::string &s, int caseMapping);
341 virtual void Copy();
342 virtual void CopyAllowLine();
343 virtual bool CanPaste();
344 virtual void Paste();
345 virtual void CreateCallTipWindow(PRectangle rc);
346 virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
347 virtual void ClaimSelection();
349 // DBCS
350 void ImeStartComposition();
351 void ImeEndComposition();
352 LRESULT ImeOnReconvert(LPARAM lParam);
354 void GetIntelliMouseParameters();
355 virtual void CopyToClipboard(const SelectionText &selectedText);
356 void ScrollMessage(WPARAM wParam);
357 void HorizontalScrollMessage(WPARAM wParam);
358 void FullPaint();
359 void FullPaintDC(HDC dc);
360 bool IsCompatibleDC(HDC dc);
361 DWORD EffectFromState(DWORD grfKeyState) const;
363 virtual int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw);
364 virtual bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi);
365 void ChangeScrollPos(int barType, int pos);
366 sptr_t GetTextLength();
367 sptr_t GetText(uptr_t wParam, sptr_t lParam);
369 public:
370 // Public for benefit of Scintilla_DirectFunction
371 virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
373 /// Implement IUnknown
374 STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv);
375 STDMETHODIMP_(ULONG)AddRef();
376 STDMETHODIMP_(ULONG)Release();
378 /// Implement IDropTarget
379 STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
380 POINTL pt, PDWORD pdwEffect);
381 STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect);
382 STDMETHODIMP DragLeave();
383 STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
384 POINTL pt, PDWORD pdwEffect);
386 /// Implement important part of IDataObject
387 STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM);
389 static bool Register(HINSTANCE hInstance_);
390 static bool Unregister();
392 friend class DropSource;
393 friend class DataObject;
394 friend class DropTarget;
395 bool DragIsRectangularOK(CLIPFORMAT fmt) const {
396 return drag.rectangular && (fmt == cfColumnSelect);
399 private:
400 // For use in creating a system caret
401 bool HasCaretSizeChanged() const;
402 BOOL CreateSystemCaret();
403 BOOL DestroySystemCaret();
404 HBITMAP sysCaretBitmap;
405 int sysCaretWidth;
406 int sysCaretHeight;
409 HINSTANCE ScintillaWin::hInstance = 0;
410 ATOM ScintillaWin::scintillaClassAtom = 0;
411 ATOM ScintillaWin::callClassAtom = 0;
413 ScintillaWin::ScintillaWin(HWND hwnd) {
415 lastKeyDownConsumed = false;
416 lastHighSurrogateChar = 0;
418 capturedMouse = false;
419 trackedMouseLeave = false;
420 TrackMouseEventFn = 0;
421 SetCoalescableTimerFn = 0;
423 linesPerScroll = 0;
424 wheelDelta = 0; // Wheel delta from roll
426 hRgnUpdate = 0;
428 hasOKText = false;
430 // There does not seem to be a real standard for indicating that the clipboard
431 // contains a rectangular selection, so copy Developer Studio and Borland Delphi.
432 cfColumnSelect = static_cast<CLIPFORMAT>(
433 ::RegisterClipboardFormat(TEXT("MSDEVColumnSelect")));
434 cfBorlandIDEBlockType = static_cast<CLIPFORMAT>(
435 ::RegisterClipboardFormat(TEXT("Borland IDE Block Type")));
437 // Likewise for line-copy (copies a full line when no text is selected)
438 cfLineSelect = static_cast<CLIPFORMAT>(
439 ::RegisterClipboardFormat(TEXT("MSDEVLineSelect")));
440 cfVSLineTag = static_cast<CLIPFORMAT>(
441 ::RegisterClipboardFormat(TEXT("VisualStudioEditorOperationsLineCutCopyClipboardTag")));
442 hrOle = E_FAIL;
444 wMain = hwnd;
446 dob.sci = this;
447 ds.sci = this;
448 dt.sci = this;
450 sysCaretBitmap = 0;
451 sysCaretWidth = 0;
452 sysCaretHeight = 0;
454 #if defined(USE_D2D)
455 pRenderTarget = 0;
456 renderTargetValid = true;
457 #endif
459 caret.period = ::GetCaretBlinkTime();
460 if (caret.period < 0)
461 caret.period = 0;
463 Initialise();
466 ScintillaWin::~ScintillaWin() {}
468 void ScintillaWin::Initialise() {
469 // Initialize COM. If the app has already done this it will have
470 // no effect. If the app hasn't, we really shouldn't ask them to call
471 // it just so this internal feature works.
472 hrOle = ::OleInitialize(NULL);
474 // Find TrackMouseEvent which is available on Windows > 95
475 HMODULE user32 = ::GetModuleHandle(TEXT("user32.dll"));
476 if (user32) {
477 TrackMouseEventFn = (TrackMouseEventSig)::GetProcAddress(user32, "TrackMouseEvent");
478 SetCoalescableTimerFn = (SetCoalescableTimerSig)::GetProcAddress(user32, "SetCoalescableTimer");
480 if (TrackMouseEventFn == NULL) {
481 // Windows 95 has an emulation in comctl32.dll:_TrackMouseEvent
482 if (!commctrl32)
483 commctrl32 = ::LoadLibrary(TEXT("comctl32.dll"));
484 if (commctrl32 != NULL) {
485 TrackMouseEventFn = (TrackMouseEventSig)
486 ::GetProcAddress(commctrl32, "_TrackMouseEvent");
489 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
490 timers[tr] = 0;
492 vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
493 vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
494 vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
495 vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
498 void ScintillaWin::Finalise() {
499 ScintillaBase::Finalise();
500 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
501 FineTickerCancel(tr);
503 SetIdle(false);
504 #if defined(USE_D2D)
505 DropRenderTarget();
506 #endif
507 ::RevokeDragDrop(MainHWND());
508 if (SUCCEEDED(hrOle)) {
509 ::OleUninitialize();
513 #if defined(USE_D2D)
515 void ScintillaWin::EnsureRenderTarget(HDC hdc) {
516 if (!renderTargetValid) {
517 DropRenderTarget();
518 renderTargetValid = true;
520 if (pD2DFactory && !pRenderTarget) {
521 RECT rc;
522 HWND hw = MainHWND();
523 GetClientRect(hw, &rc);
525 D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
527 // Create a Direct2D render target.
528 #if 1
529 D2D1_RENDER_TARGET_PROPERTIES drtp;
530 drtp.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
531 drtp.pixelFormat.format = DXGI_FORMAT_UNKNOWN;
532 drtp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_UNKNOWN;
533 drtp.dpiX = 96.0;
534 drtp.dpiY = 96.0;
535 drtp.usage = D2D1_RENDER_TARGET_USAGE_NONE;
536 drtp.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
538 if (technology == SC_TECHNOLOGY_DIRECTWRITEDC) {
539 // Explicit pixel format needed.
540 drtp.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
541 D2D1_ALPHA_MODE_IGNORE);
543 ID2D1DCRenderTarget *pDCRT = NULL;
544 HRESULT hr = pD2DFactory->CreateDCRenderTarget(&drtp, &pDCRT);
545 if (SUCCEEDED(hr)) {
546 pRenderTarget = pDCRT;
547 } else {
548 Platform::DebugPrintf("Failed CreateDCRenderTarget 0x%x\n", hr);
549 pRenderTarget = NULL;
552 } else {
553 D2D1_HWND_RENDER_TARGET_PROPERTIES dhrtp;
554 dhrtp.hwnd = hw;
555 dhrtp.pixelSize = size;
556 dhrtp.presentOptions = (technology == SC_TECHNOLOGY_DIRECTWRITERETAIN) ?
557 D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS : D2D1_PRESENT_OPTIONS_NONE;
559 ID2D1HwndRenderTarget *pHwndRenderTarget = NULL;
560 HRESULT hr = pD2DFactory->CreateHwndRenderTarget(drtp, dhrtp, &pHwndRenderTarget);
561 if (SUCCEEDED(hr)) {
562 pRenderTarget = pHwndRenderTarget;
563 } else {
564 Platform::DebugPrintf("Failed CreateHwndRenderTarget 0x%x\n", hr);
565 pRenderTarget = NULL;
568 #else
569 pD2DFactory->CreateHwndRenderTarget(
570 D2D1::RenderTargetProperties(
571 D2D1_RENDER_TARGET_TYPE_DEFAULT ,
572 D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
573 96.0f, 96.0f, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_DEFAULT),
574 D2D1::HwndRenderTargetProperties(hw, size),
575 &pRenderTarget);
576 #endif
577 // Pixmaps were created to be compatible with previous render target so
578 // need to be recreated.
579 DropGraphics(false);
582 if ((technology == SC_TECHNOLOGY_DIRECTWRITEDC) && pRenderTarget) {
583 RECT rcWindow;
584 GetClientRect(MainHWND(), &rcWindow);
585 HRESULT hr = static_cast<ID2D1DCRenderTarget*>(pRenderTarget)->BindDC(hdc, &rcWindow);
586 if (FAILED(hr)) {
587 Platform::DebugPrintf("BindDC failed 0x%x\n", hr);
588 DropRenderTarget();
593 void ScintillaWin::DropRenderTarget() {
594 if (pRenderTarget) {
595 pRenderTarget->Release();
596 pRenderTarget = 0;
600 #endif
602 HWND ScintillaWin::MainHWND() {
603 return static_cast<HWND>(wMain.GetID());
606 bool ScintillaWin::DragThreshold(Point ptStart, Point ptNow) {
607 int xMove = static_cast<int>(std::abs(ptStart.x - ptNow.x));
608 int yMove = static_cast<int>(std::abs(ptStart.y - ptNow.y));
609 return (xMove > ::GetSystemMetrics(SM_CXDRAG)) ||
610 (yMove > ::GetSystemMetrics(SM_CYDRAG));
613 void ScintillaWin::StartDrag() {
614 inDragDrop = ddDragging;
615 DWORD dwEffect = 0;
616 dropWentOutside = true;
617 IDataObject *pDataObject = reinterpret_cast<IDataObject *>(&dob);
618 IDropSource *pDropSource = reinterpret_cast<IDropSource *>(&ds);
619 //Platform::DebugPrintf("About to DoDragDrop %x %x\n", pDataObject, pDropSource);
620 HRESULT hr = ::DoDragDrop(
621 pDataObject,
622 pDropSource,
623 DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
624 //Platform::DebugPrintf("DoDragDrop = %x\n", hr);
625 if (SUCCEEDED(hr)) {
626 if ((hr == DRAGDROP_S_DROP) && (dwEffect == DROPEFFECT_MOVE) && dropWentOutside) {
627 // Remove dragged out text
628 ClearSelection();
631 inDragDrop = ddNone;
632 SetDragPosition(SelectionPosition(invalidPosition));
635 // Avoid warnings everywhere for old style casts by concentrating them here
636 static WORD LoWord(uptr_t l) {
637 return LOWORD(l);
640 static WORD HiWord(uptr_t l) {
641 return HIWORD(l);
644 static int InputCodePage() {
645 HKL inputLocale = ::GetKeyboardLayout(0);
646 LANGID inputLang = LOWORD(inputLocale);
647 char sCodePage[10];
648 int res = ::GetLocaleInfoA(MAKELCID(inputLang, SORT_DEFAULT),
649 LOCALE_IDEFAULTANSICODEPAGE, sCodePage, sizeof(sCodePage));
650 if (!res)
651 return 0;
652 return atoi(sCodePage);
655 /** Map the key codes to their equivalent SCK_ form. */
656 static int KeyTranslate(int keyIn) {
657 //PLATFORM_ASSERT(!keyIn);
658 switch (keyIn) {
659 case VK_DOWN: return SCK_DOWN;
660 case VK_UP: return SCK_UP;
661 case VK_LEFT: return SCK_LEFT;
662 case VK_RIGHT: return SCK_RIGHT;
663 case VK_HOME: return SCK_HOME;
664 case VK_END: return SCK_END;
665 case VK_PRIOR: return SCK_PRIOR;
666 case VK_NEXT: return SCK_NEXT;
667 case VK_DELETE: return SCK_DELETE;
668 case VK_INSERT: return SCK_INSERT;
669 case VK_ESCAPE: return SCK_ESCAPE;
670 case VK_BACK: return SCK_BACK;
671 case VK_TAB: return SCK_TAB;
672 case VK_RETURN: return SCK_RETURN;
673 case VK_ADD: return SCK_ADD;
674 case VK_SUBTRACT: return SCK_SUBTRACT;
675 case VK_DIVIDE: return SCK_DIVIDE;
676 case VK_LWIN: return SCK_WIN;
677 case VK_RWIN: return SCK_RWIN;
678 case VK_APPS: return SCK_MENU;
679 case VK_OEM_2: return '/';
680 case VK_OEM_3: return '`';
681 case VK_OEM_4: return '[';
682 case VK_OEM_5: return '\\';
683 case VK_OEM_6: return ']';
684 default: return keyIn;
688 static bool BoundsContains(PRectangle rcBounds, HRGN hRgnBounds, PRectangle rcCheck) {
689 bool contains = true;
690 if (!rcCheck.Empty()) {
691 if (!rcBounds.Contains(rcCheck)) {
692 contains = false;
693 } else if (hRgnBounds) {
694 // In bounding rectangle so check more accurately using region
695 HRGN hRgnCheck = ::CreateRectRgn(static_cast<int>(rcCheck.left), static_cast<int>(rcCheck.top),
696 static_cast<int>(rcCheck.right), static_cast<int>(rcCheck.bottom));
697 if (hRgnCheck) {
698 HRGN hRgnDifference = ::CreateRectRgn(0, 0, 0, 0);
699 if (hRgnDifference) {
700 int combination = ::CombineRgn(hRgnDifference, hRgnCheck, hRgnBounds, RGN_DIFF);
701 if (combination != NULLREGION) {
702 contains = false;
704 ::DeleteRgn(hRgnDifference);
706 ::DeleteRgn(hRgnCheck);
710 return contains;
713 // Returns the target converted to UTF8.
714 // Return the length in bytes.
715 int ScintillaWin::TargetAsUTF8(char *text) {
716 int targetLength = targetEnd - targetStart;
717 if (IsUnicodeMode()) {
718 if (text) {
719 pdoc->GetCharRange(text, targetStart, targetLength);
721 } else {
722 // Need to convert
723 std::string s = RangeText(targetStart, targetEnd);
724 int charsLen = ::MultiByteToWideChar(CodePageOfDocument(), 0, &s[0], targetLength, NULL, 0);
725 std::wstring characters(charsLen, '\0');
726 ::MultiByteToWideChar(CodePageOfDocument(), 0, &s[0], targetLength, &characters[0], charsLen);
728 int utf8Len = ::WideCharToMultiByte(CP_UTF8, 0, &characters[0], charsLen, NULL, 0, 0, 0);
729 if (text) {
730 ::WideCharToMultiByte(CP_UTF8, 0, &characters[0], charsLen, text, utf8Len, 0, 0);
731 text[utf8Len] = '\0';
733 return utf8Len;
735 return targetLength;
738 // Translates a nul terminated UTF8 string into the document encoding.
739 // Return the length of the result in bytes.
740 int ScintillaWin::EncodedFromUTF8(char *utf8, char *encoded) const {
741 int inputLength = (lengthForEncode >= 0) ? lengthForEncode : static_cast<int>(strlen(utf8));
742 if (IsUnicodeMode()) {
743 if (encoded) {
744 memcpy(encoded, utf8, inputLength);
746 return inputLength;
747 } else {
748 // Need to convert
749 int charsLen = ::MultiByteToWideChar(CP_UTF8, 0, utf8, inputLength, NULL, 0);
750 std::wstring characters(charsLen, '\0');
751 ::MultiByteToWideChar(CP_UTF8, 0, utf8, inputLength, &characters[0], charsLen);
753 int encodedLen = ::WideCharToMultiByte(CodePageOfDocument(),
754 0, &characters[0], charsLen, NULL, 0, 0, 0);
755 if (encoded) {
756 ::WideCharToMultiByte(CodePageOfDocument(), 0, &characters[0], charsLen, encoded, encodedLen, 0, 0);
757 encoded[encodedLen] = '\0';
759 return encodedLen;
763 // Add one character from a UTF-16 string, by converting to either UTF-8 or
764 // the current codepage. Code is similar to HandleCompositionWindowed().
765 void ScintillaWin::AddCharUTF16(wchar_t const *wcs, unsigned int wclen) {
766 if (IsUnicodeMode()) {
767 char utfval[maxLenInputIME * 3];
768 unsigned int len = UTF8Length(wcs, wclen);
769 UTF8FromUTF16(wcs, wclen, utfval, len);
770 utfval[len] = '\0';
771 AddCharUTF(utfval, len);
772 } else {
773 UINT cpDest = CodePageOfDocument();
774 char inBufferCP[maxLenInputIME * 2];
775 int size = ::WideCharToMultiByte(cpDest,
776 0, wcs, wclen, inBufferCP, sizeof(inBufferCP) - 1, 0, 0);
777 for (int i=0; i<size; i++) {
778 AddChar(inBufferCP[i]);
783 sptr_t ScintillaWin::WndPaint(uptr_t wParam) {
784 //ElapsedTime et;
786 // Redirect assertions to debug output and save current state
787 bool assertsPopup = Platform::ShowAssertionPopUps(false);
788 paintState = painting;
789 PAINTSTRUCT ps;
790 PAINTSTRUCT *pps;
792 bool IsOcxCtrl = (wParam != 0); // if wParam != 0, it contains
793 // a PAINSTRUCT* from the OCX
794 // Removed since this interferes with reporting other assertions as it occurs repeatedly
795 //PLATFORM_ASSERT(hRgnUpdate == NULL);
796 hRgnUpdate = ::CreateRectRgn(0, 0, 0, 0);
797 if (IsOcxCtrl) {
798 pps = reinterpret_cast<PAINTSTRUCT*>(wParam);
799 } else {
800 ::GetUpdateRgn(MainHWND(), hRgnUpdate, FALSE);
801 pps = &ps;
802 ::BeginPaint(MainHWND(), pps);
804 rcPaint = PRectangle::FromInts(pps->rcPaint.left, pps->rcPaint.top, pps->rcPaint.right, pps->rcPaint.bottom);
805 PRectangle rcClient = GetClientRectangle();
806 paintingAllText = BoundsContains(rcPaint, hRgnUpdate, rcClient);
807 if (technology == SC_TECHNOLOGY_DEFAULT) {
808 AutoSurface surfaceWindow(pps->hdc, this);
809 if (surfaceWindow) {
810 Paint(surfaceWindow, rcPaint);
811 surfaceWindow->Release();
813 } else {
814 #if defined(USE_D2D)
815 EnsureRenderTarget(pps->hdc);
816 AutoSurface surfaceWindow(pRenderTarget, this);
817 if (surfaceWindow) {
818 pRenderTarget->BeginDraw();
819 Paint(surfaceWindow, rcPaint);
820 surfaceWindow->Release();
821 HRESULT hr = pRenderTarget->EndDraw();
822 if (hr == D2DERR_RECREATE_TARGET) {
823 DropRenderTarget();
824 paintState = paintAbandoned;
827 #endif
829 if (hRgnUpdate) {
830 ::DeleteRgn(hRgnUpdate);
831 hRgnUpdate = 0;
834 if (!IsOcxCtrl)
835 ::EndPaint(MainHWND(), pps);
836 if (paintState == paintAbandoned) {
837 // Painting area was insufficient to cover new styling or brace highlight positions
838 if (IsOcxCtrl) {
839 FullPaintDC(pps->hdc);
840 } else {
841 FullPaint();
844 paintState = notPainting;
846 // Restore debug output state
847 Platform::ShowAssertionPopUps(assertsPopup);
849 //Platform::DebugPrintf("Paint took %g\n", et.Duration());
850 return 0l;
853 sptr_t ScintillaWin::HandleCompositionWindowed(uptr_t wParam, sptr_t lParam) {
854 if (lParam & GCS_RESULTSTR) {
855 IMContext imc(MainHWND());
856 if (imc.hIMC) {
857 AddWString(imc.GetCompositionString(GCS_RESULTSTR));
859 // Set new position after converted
860 Point pos = PointMainCaret();
861 COMPOSITIONFORM CompForm;
862 CompForm.dwStyle = CFS_POINT;
863 CompForm.ptCurrentPos.x = static_cast<int>(pos.x);
864 CompForm.ptCurrentPos.y = static_cast<int>(pos.y);
865 ::ImmSetCompositionWindow(imc.hIMC, &CompForm);
867 return 0;
869 return ::DefWindowProc(MainHWND(), WM_IME_COMPOSITION, wParam, lParam);
872 bool ScintillaWin::KoreanIME() {
873 const int codePage = InputCodePage();
874 return codePage == 949 || codePage == 1361;
877 void ScintillaWin::MoveImeCarets(int offset) {
878 // Move carets relatively by bytes.
879 for (size_t r=0; r<sel.Count(); r++) {
880 int positionInsert = sel.Range(r).Start().Position();
881 sel.Range(r).caret.SetPosition(positionInsert + offset);
882 sel.Range(r).anchor.SetPosition(positionInsert + offset);
886 void ScintillaWin::DrawImeIndicator(int indicator, int len) {
887 // Emulate the visual style of IME characters with indicators.
888 // Draw an indicator on the character before caret by the character bytes of len
889 // so it should be called after addCharUTF().
890 // It does not affect caret positions.
891 if (indicator < 8 || indicator > INDIC_MAX) {
892 return;
894 pdoc->decorations.SetCurrentIndicator(indicator);
895 for (size_t r=0; r<sel.Count(); r++) {
896 int positionInsert = sel.Range(r).Start().Position();
897 pdoc->DecorationFillRange(positionInsert - len, 1, len);
901 void ScintillaWin::SetCandidateWindowPos() {
902 IMContext imc(MainHWND());
903 if (imc.hIMC) {
904 Point pos = PointMainCaret();
905 CANDIDATEFORM CandForm;
906 CandForm.dwIndex = 0;
907 CandForm.dwStyle = CFS_CANDIDATEPOS;
908 CandForm.ptCurrentPos.x = static_cast<int>(pos.x);
909 CandForm.ptCurrentPos.y = static_cast<int>(pos.y + vs.lineHeight);
910 ::ImmSetCandidateWindow(imc.hIMC, &CandForm);
914 static std::string StringEncode(std::wstring s, int codePage) {
915 if (s.length()) {
916 int cchMulti = ::WideCharToMultiByte(codePage, 0, s.c_str(), static_cast<int>(s.length()), NULL, 0, NULL, NULL);
917 std::string sMulti(cchMulti, 0);
918 ::WideCharToMultiByte(codePage, 0, s.c_str(), static_cast<int>(s.size()), &sMulti[0], cchMulti, NULL, NULL);
919 return sMulti;
920 } else {
921 return std::string();
925 static std::wstring StringDecode(std::string s, int codePage) {
926 if (s.length()) {
927 int cchWide = ::MultiByteToWideChar(codePage, 0, s.c_str(), static_cast<int>(s.length()), NULL, 0);
928 std::wstring sWide(cchWide, 0);
929 ::MultiByteToWideChar(codePage, 0, s.c_str(), static_cast<int>(s.length()), &sWide[0], cchWide);
930 return sWide;
931 } else {
932 return std::wstring();
936 void ScintillaWin::SelectionToHangul() {
937 // Convert every hanja to hangul within the main range.
938 const int selStart = sel.RangeMain().Start().Position();
939 const int documentStrLen = sel.RangeMain().Length();
940 const int selEnd = selStart + documentStrLen;
941 const int utf16Len = pdoc->CountUTF16(selStart, selEnd);
943 if (utf16Len > 0) {
944 std::string documentStr(documentStrLen, '\0');
945 pdoc->GetCharRange(&documentStr[0], selStart, documentStrLen);
947 std::wstring uniStr = StringDecode(documentStr, CodePageOfDocument());
948 int converted = HanjaDict::GetHangulOfHanja(&uniStr[0]);
949 documentStr = StringEncode(uniStr, CodePageOfDocument());
951 if (converted > 0) {
952 pdoc->BeginUndoAction();
953 ClearSelection();
954 InsertPaste(&documentStr[0], static_cast<int>(documentStr.size()));
955 pdoc->EndUndoAction();
960 void ScintillaWin::EscapeHanja() {
961 // The candidate box pops up to user to select a hanja.
962 // It comes into WM_IME_COMPOSITION with GCS_RESULTSTR.
963 // The existing hangul or hanja is replaced with it.
964 if (sel.Count() > 1) {
965 return; // Do not allow multi carets.
967 int currentPos = CurrentPosition();
968 int oneCharLen = pdoc->LenChar(currentPos);
970 if (oneCharLen < 2) {
971 return; // No need to handle SBCS.
974 // ImmEscapeW() may overwrite uniChar[] with a null terminated string.
975 // So enlarge it enough to Maximum 4 as in UTF-8.
976 unsigned int const safeLength = UTF8MaxBytes+1;
977 std::string oneChar(safeLength, '\0');
978 pdoc->GetCharRange(&oneChar[0], currentPos, oneCharLen);
980 std::wstring uniChar = StringDecode(oneChar, CodePageOfDocument());
982 IMContext imc(MainHWND());
983 if (imc.hIMC) {
984 // Set the candidate box position since IME may show it.
985 SetCandidateWindowPos();
986 // IME_ESC_HANJA_MODE appears to receive the first character only.
987 if (ImmEscapeW(GetKeyboardLayout(0), imc.hIMC, IME_ESC_HANJA_MODE, &uniChar[0])) {
988 SetSelection(currentPos, currentPos + oneCharLen);
993 void ScintillaWin::ToggleHanja() {
994 // If selection, convert every hanja to hangul within the main range.
995 // If no selection, commit to IME.
996 if (sel.Count() > 1) {
997 return; // Do not allow multi carets.
1000 if (sel.Empty()) {
1001 EscapeHanja();
1002 } else {
1003 SelectionToHangul();
1007 namespace {
1009 std::vector<int> MapImeIndicators(std::vector<BYTE> inputStyle) {
1010 std::vector<int> imeIndicator(inputStyle.size(), SC_INDICATOR_UNKNOWN);
1011 for (size_t i = 0; i < inputStyle.size(); i++) {
1012 switch (static_cast<int>(inputStyle.at(i))) {
1013 case ATTR_INPUT:
1014 imeIndicator[i] = SC_INDICATOR_INPUT;
1015 break;
1016 case ATTR_TARGET_NOTCONVERTED:
1017 case ATTR_TARGET_CONVERTED:
1018 imeIndicator[i] = SC_INDICATOR_TARGET;
1019 break;
1020 case ATTR_CONVERTED:
1021 imeIndicator[i] = SC_INDICATOR_CONVERTED;
1022 break;
1023 default:
1024 imeIndicator[i] = SC_INDICATOR_UNKNOWN;
1025 break;
1028 return imeIndicator;
1033 void ScintillaWin::AddWString(std::wstring wcs) {
1034 if (wcs.empty())
1035 return;
1037 int codePage = CodePageOfDocument();
1038 for (size_t i = 0; i < wcs.size(); ) {
1039 const size_t ucWidth = UTF16CharLength(wcs[i]);
1040 const std::wstring uniChar(wcs, i, ucWidth);
1041 std::string docChar = StringEncode(uniChar, codePage);
1043 AddCharUTF(docChar.c_str(), static_cast<unsigned int>(docChar.size()));
1044 i += ucWidth;
1048 sptr_t ScintillaWin::HandleCompositionInline(uptr_t, sptr_t lParam) {
1049 // Copy & paste by johnsonj with a lot of helps of Neil.
1050 // Great thanks for my foreruners, jiniya and BLUEnLIVE.
1052 IMContext imc(MainHWND());
1053 if (!imc.hIMC)
1054 return 0;
1055 if (pdoc->IsReadOnly() || SelectionContainsProtected()) {
1056 ::ImmNotifyIME(imc.hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
1057 return 0;
1060 if (pdoc->TentativeActive()) {
1061 pdoc->TentativeUndo();
1062 } else {
1063 // No tentative undo means start of this composition so
1064 // fill in any virtual spaces.
1065 ClearBeforeTentativeStart();
1068 view.imeCaretBlockOverride = false;
1070 if (lParam & GCS_COMPSTR) {
1071 const std::wstring wcs = imc.GetCompositionString(GCS_COMPSTR);
1072 if ((wcs.size() == 0) || (wcs.size() >= maxLenInputIME)) {
1073 ShowCaretAtCurrentPosition();
1074 return 0;
1077 pdoc->TentativeStart(); // TentativeActive from now on.
1079 std::vector<int> imeIndicator = MapImeIndicators(imc.GetImeAttributes());
1081 bool tmpRecordingMacro = recordingMacro;
1082 recordingMacro = false;
1083 int codePage = CodePageOfDocument();
1084 for (size_t i = 0; i < wcs.size(); ) {
1085 const size_t ucWidth = UTF16CharLength(wcs[i]);
1086 const std::wstring uniChar(wcs, i, ucWidth);
1087 std::string docChar = StringEncode(uniChar, codePage);
1089 AddCharUTF(docChar.c_str(), static_cast<unsigned int>(docChar.size()));
1091 DrawImeIndicator(imeIndicator[i], static_cast<unsigned int>(docChar.size()));
1092 i += ucWidth;
1094 recordingMacro = tmpRecordingMacro;
1096 // Move IME caret from current last position to imeCaretPos.
1097 int imeEndToImeCaretU16 = imc.GetImeCaretPos() - static_cast<unsigned int>(wcs.size());
1098 int imeCaretPosDoc = pdoc->GetRelativePositionUTF16(CurrentPosition(), imeEndToImeCaretU16);
1100 MoveImeCarets(- CurrentPosition() + imeCaretPosDoc);
1102 if (KoreanIME()) {
1103 view.imeCaretBlockOverride = true;
1105 } else if (lParam & GCS_RESULTSTR) {
1106 AddWString(imc.GetCompositionString(GCS_RESULTSTR));
1108 EnsureCaretVisible();
1109 SetCandidateWindowPos();
1110 ShowCaretAtCurrentPosition();
1111 return 0;
1114 // Translate message IDs from WM_* and EM_* to SCI_* so can partly emulate Windows Edit control
1115 static unsigned int SciMessageFromEM(unsigned int iMessage) {
1116 switch (iMessage) {
1117 case EM_CANPASTE: return SCI_CANPASTE;
1118 case EM_CANUNDO: return SCI_CANUNDO;
1119 case EM_EMPTYUNDOBUFFER: return SCI_EMPTYUNDOBUFFER;
1120 case EM_FINDTEXTEX: return SCI_FINDTEXT;
1121 case EM_FORMATRANGE: return SCI_FORMATRANGE;
1122 case EM_GETFIRSTVISIBLELINE: return SCI_GETFIRSTVISIBLELINE;
1123 case EM_GETLINECOUNT: return SCI_GETLINECOUNT;
1124 case EM_GETSELTEXT: return SCI_GETSELTEXT;
1125 case EM_GETTEXTRANGE: return SCI_GETTEXTRANGE;
1126 case EM_HIDESELECTION: return SCI_HIDESELECTION;
1127 case EM_LINEINDEX: return SCI_POSITIONFROMLINE;
1128 case EM_LINESCROLL: return SCI_LINESCROLL;
1129 case EM_REPLACESEL: return SCI_REPLACESEL;
1130 case EM_SCROLLCARET: return SCI_SCROLLCARET;
1131 case EM_SETREADONLY: return SCI_SETREADONLY;
1132 case WM_CLEAR: return SCI_CLEAR;
1133 case WM_COPY: return SCI_COPY;
1134 case WM_CUT: return SCI_CUT;
1135 case WM_SETTEXT: return SCI_SETTEXT;
1136 case WM_PASTE: return SCI_PASTE;
1137 case WM_UNDO: return SCI_UNDO;
1139 return iMessage;
1142 UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage) {
1143 if (documentCodePage == SC_CP_UTF8) {
1144 return SC_CP_UTF8;
1146 switch (characterSet) {
1147 case SC_CHARSET_ANSI: return 1252;
1148 case SC_CHARSET_DEFAULT: return documentCodePage;
1149 case SC_CHARSET_BALTIC: return 1257;
1150 case SC_CHARSET_CHINESEBIG5: return 950;
1151 case SC_CHARSET_EASTEUROPE: return 1250;
1152 case SC_CHARSET_GB2312: return 936;
1153 case SC_CHARSET_GREEK: return 1253;
1154 case SC_CHARSET_HANGUL: return 949;
1155 case SC_CHARSET_MAC: return 10000;
1156 case SC_CHARSET_OEM: return 437;
1157 case SC_CHARSET_RUSSIAN: return 1251;
1158 case SC_CHARSET_SHIFTJIS: return 932;
1159 case SC_CHARSET_TURKISH: return 1254;
1160 case SC_CHARSET_JOHAB: return 1361;
1161 case SC_CHARSET_HEBREW: return 1255;
1162 case SC_CHARSET_ARABIC: return 1256;
1163 case SC_CHARSET_VIETNAMESE: return 1258;
1164 case SC_CHARSET_THAI: return 874;
1165 case SC_CHARSET_8859_15: return 28605;
1166 // Not supported
1167 case SC_CHARSET_CYRILLIC: return documentCodePage;
1168 case SC_CHARSET_SYMBOL: return documentCodePage;
1170 return documentCodePage;
1173 UINT ScintillaWin::CodePageOfDocument() const {
1174 return CodePageFromCharSet(vs.styles[STYLE_DEFAULT].characterSet, pdoc->dbcsCodePage);
1177 sptr_t ScintillaWin::GetTextLength() {
1178 if (pdoc->Length() == 0)
1179 return 0;
1180 std::vector<char> docBytes(pdoc->Length(), '\0');
1181 pdoc->GetCharRange(&docBytes[0], 0, pdoc->Length());
1182 if (IsUnicodeMode()) {
1183 return UTF16Length(&docBytes[0], static_cast<unsigned int>(docBytes.size()));
1184 } else {
1185 return ::MultiByteToWideChar(CodePageOfDocument(), 0, &docBytes[0],
1186 static_cast<int>(docBytes.size()), NULL, 0);
1190 sptr_t ScintillaWin::GetText(uptr_t wParam, sptr_t lParam) {
1191 wchar_t *ptr = reinterpret_cast<wchar_t *>(lParam);
1192 if (pdoc->Length() == 0) {
1193 *ptr = L'\0';
1194 return 0;
1196 std::vector<char> docBytes(pdoc->Length(), '\0');
1197 pdoc->GetCharRange(&docBytes[0], 0, pdoc->Length());
1198 if (IsUnicodeMode()) {
1199 size_t lengthUTF16 = UTF16Length(&docBytes[0], static_cast<unsigned int>(docBytes.size()));
1200 if (lParam == 0)
1201 return lengthUTF16;
1202 if (wParam == 0)
1203 return 0;
1204 size_t uLen = UTF16FromUTF8(&docBytes[0], docBytes.size(),
1205 ptr, static_cast<int>(wParam) - 1);
1206 ptr[uLen] = L'\0';
1207 return uLen;
1208 } else {
1209 // Not Unicode mode
1210 // Convert to Unicode using the current Scintilla code page
1211 const UINT cpSrc = CodePageOfDocument();
1212 int lengthUTF16 = ::MultiByteToWideChar(cpSrc, 0, &docBytes[0],
1213 static_cast<int>(docBytes.size()), NULL, 0);
1214 if (lengthUTF16 >= static_cast<int>(wParam))
1215 lengthUTF16 = static_cast<int>(wParam)-1;
1216 ::MultiByteToWideChar(cpSrc, 0, &docBytes[0],
1217 static_cast<int>(docBytes.size()),
1218 ptr, lengthUTF16);
1219 ptr[lengthUTF16] = L'\0';
1220 return lengthUTF16;
1224 sptr_t ScintillaWin::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
1225 try {
1226 //Platform::DebugPrintf("S M:%x WP:%x L:%x\n", iMessage, wParam, lParam);
1227 iMessage = SciMessageFromEM(iMessage);
1228 switch (iMessage) {
1230 case WM_CREATE:
1231 ctrlID = ::GetDlgCtrlID(static_cast<HWND>(wMain.GetID()));
1232 // Get Intellimouse scroll line parameters
1233 GetIntelliMouseParameters();
1234 ::RegisterDragDrop(MainHWND(), reinterpret_cast<IDropTarget *>(&dt));
1235 break;
1237 case WM_COMMAND:
1238 Command(LoWord(wParam));
1239 break;
1241 case WM_PAINT:
1242 return WndPaint(wParam);
1244 case WM_PRINTCLIENT: {
1245 HDC hdc = reinterpret_cast<HDC>(wParam);
1246 if (!IsCompatibleDC(hdc)) {
1247 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1249 FullPaintDC(hdc);
1251 break;
1253 case WM_VSCROLL:
1254 ScrollMessage(wParam);
1255 break;
1257 case WM_HSCROLL:
1258 HorizontalScrollMessage(wParam);
1259 break;
1261 case WM_SIZE: {
1262 #if defined(USE_D2D)
1263 if (paintState == notPainting) {
1264 DropRenderTarget();
1265 } else {
1266 renderTargetValid = false;
1268 #endif
1269 //Platform::DebugPrintf("Scintilla WM_SIZE %d %d\n", LoWord(lParam), HiWord(lParam));
1270 ChangeSize();
1272 break;
1274 case WM_MOUSEWHEEL:
1275 // if autocomplete list active then send mousewheel message to it
1276 if (ac.Active()) {
1277 HWND hWnd = static_cast<HWND>(ac.lb->GetID());
1278 ::SendMessage(hWnd, iMessage, wParam, lParam);
1279 break;
1282 // Don't handle datazoom.
1283 // (A good idea for datazoom would be to "fold" or "unfold" details.
1284 // i.e. if datazoomed out only class structures are visible, when datazooming in the control
1285 // structures appear, then eventually the individual statements...)
1286 if (wParam & MK_SHIFT) {
1287 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1290 // Either SCROLL or ZOOM. We handle the wheel steppings calculation
1291 wheelDelta -= static_cast<short>(HiWord(wParam));
1292 if (abs(wheelDelta) >= WHEEL_DELTA && linesPerScroll > 0) {
1293 int linesToScroll = linesPerScroll;
1294 if (linesPerScroll == WHEEL_PAGESCROLL)
1295 linesToScroll = LinesOnScreen() - 1;
1296 if (linesToScroll == 0) {
1297 linesToScroll = 1;
1299 linesToScroll *= (wheelDelta / WHEEL_DELTA);
1300 if (wheelDelta >= 0)
1301 wheelDelta = wheelDelta % WHEEL_DELTA;
1302 else
1303 wheelDelta = - (-wheelDelta % WHEEL_DELTA);
1305 if (wParam & MK_CONTROL) {
1306 // Zoom! We play with the font sizes in the styles.
1307 // Number of steps/line is ignored, we just care if sizing up or down
1308 if (linesToScroll < 0) {
1309 KeyCommand(SCI_ZOOMIN);
1310 } else {
1311 KeyCommand(SCI_ZOOMOUT);
1313 } else {
1314 // Scroll
1315 ScrollTo(topLine + linesToScroll);
1318 return 0;
1320 case WM_TIMER:
1321 if (wParam == idleTimerID && idler.state) {
1322 SendMessage(MainHWND(), SC_WIN_IDLE, 0, 1);
1323 } else {
1324 TickFor(static_cast<TickReason>(wParam - fineTimerStart));
1326 break;
1328 case SC_WIN_IDLE:
1329 // wParam=dwTickCountInitial, or 0 to initialize. lParam=bSkipUserInputTest
1330 if (idler.state) {
1331 if (lParam || (WAIT_TIMEOUT == MsgWaitForMultipleObjects(0, 0, 0, 0, QS_INPUT|QS_HOTKEY))) {
1332 if (Idle()) {
1333 // User input was given priority above, but all events do get a turn. Other
1334 // messages, notifications, etc. will get interleaved with the idle messages.
1336 // However, some things like WM_PAINT are a lower priority, and will not fire
1337 // when there's a message posted. So, several times a second, we stop and let
1338 // the low priority events have a turn (after which the timer will fire again).
1340 DWORD dwCurrent = GetTickCount();
1341 DWORD dwStart = wParam ? static_cast<DWORD>(wParam) : dwCurrent;
1342 const DWORD maxWorkTime = 50;
1344 if (dwCurrent >= dwStart && dwCurrent > maxWorkTime && dwCurrent - maxWorkTime < dwStart)
1345 PostMessage(MainHWND(), SC_WIN_IDLE, dwStart, 0);
1346 } else {
1347 SetIdle(false);
1351 break;
1353 case WM_GETMINMAXINFO:
1354 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1356 case WM_LBUTTONDOWN: {
1357 // For IME, set the composition string as the result string.
1358 IMContext imc(MainHWND());
1359 ::ImmNotifyIME(imc.hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
1361 //Platform::DebugPrintf("Buttdown %d %x %x %x %x %x\n",iMessage, wParam, lParam,
1362 // Platform::IsKeyDown(VK_SHIFT),
1363 // Platform::IsKeyDown(VK_CONTROL),
1364 // Platform::IsKeyDown(VK_MENU));
1365 ::SetFocus(MainHWND());
1366 ButtonDown(Point::FromLong(static_cast<long>(lParam)), ::GetMessageTime(),
1367 (wParam & MK_SHIFT) != 0,
1368 (wParam & MK_CONTROL) != 0,
1369 Platform::IsKeyDown(VK_MENU));
1371 break;
1373 case WM_MOUSEMOVE: {
1374 const Point pt = Point::FromLong(static_cast<long>(lParam));
1376 // Windows might send WM_MOUSEMOVE even though the mouse has not been moved:
1377 // http://blogs.msdn.com/b/oldnewthing/archive/2003/10/01/55108.aspx
1378 if (ptMouseLast.x != pt.x || ptMouseLast.y != pt.y) {
1379 SetTrackMouseLeaveEvent(true);
1380 ButtonMoveWithModifiers(pt,
1381 ((wParam & MK_SHIFT) != 0 ? SCI_SHIFT : 0) |
1382 ((wParam & MK_CONTROL) != 0 ? SCI_CTRL : 0) |
1383 (Platform::IsKeyDown(VK_MENU) ? SCI_ALT : 0));
1386 break;
1388 case WM_MOUSELEAVE:
1389 SetTrackMouseLeaveEvent(false);
1390 MouseLeave();
1391 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1393 case WM_LBUTTONUP:
1394 ButtonUp(Point::FromLong(static_cast<long>(lParam)),
1395 ::GetMessageTime(),
1396 (wParam & MK_CONTROL) != 0);
1397 break;
1399 case WM_RBUTTONDOWN:
1400 ::SetFocus(MainHWND());
1401 if (!PointInSelection(Point::FromLong(static_cast<long>(lParam)))) {
1402 CancelModes();
1403 SetEmptySelection(PositionFromLocation(Point::FromLong(static_cast<long>(lParam))));
1405 break;
1407 case WM_SETCURSOR:
1408 if (LoWord(lParam) == HTCLIENT) {
1409 if (inDragDrop == ddDragging) {
1410 DisplayCursor(Window::cursorUp);
1411 } else {
1412 // Display regular (drag) cursor over selection
1413 POINT pt;
1414 if (0 != ::GetCursorPos(&pt)) {
1415 ::ScreenToClient(MainHWND(), &pt);
1416 if (PointInSelMargin(PointFromPOINT(pt))) {
1417 DisplayCursor(GetMarginCursor(PointFromPOINT(pt)));
1418 } else if (PointInSelection(PointFromPOINT(pt)) && !SelectionEmpty()) {
1419 DisplayCursor(Window::cursorArrow);
1420 } else if (PointIsHotspot(PointFromPOINT(pt))) {
1421 DisplayCursor(Window::cursorHand);
1422 } else {
1423 DisplayCursor(Window::cursorText);
1427 return TRUE;
1428 } else {
1429 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1432 case WM_CHAR:
1433 if (((wParam >= 128) || !iscntrl(static_cast<int>(wParam))) || !lastKeyDownConsumed) {
1434 wchar_t wcs[3] = {static_cast<wchar_t>(wParam), 0};
1435 unsigned int wclen = 1;
1436 if (IS_HIGH_SURROGATE(wcs[0])) {
1437 // If this is a high surrogate character, we need a second one
1438 lastHighSurrogateChar = wcs[0];
1439 return 0;
1440 } else if (IS_LOW_SURROGATE(wcs[0])) {
1441 wcs[1] = wcs[0];
1442 wcs[0] = lastHighSurrogateChar;
1443 lastHighSurrogateChar = 0;
1444 wclen = 2;
1446 AddCharUTF16(wcs, wclen);
1448 return 0;
1450 case WM_UNICHAR:
1451 if (wParam == UNICODE_NOCHAR) {
1452 return TRUE;
1453 } else if (lastKeyDownConsumed) {
1454 return 1;
1455 } else {
1456 wchar_t wcs[3] = {0};
1457 unsigned int wclen = UTF16FromUTF32Character(static_cast<unsigned int>(wParam), wcs);
1458 AddCharUTF16(wcs, wclen);
1459 return FALSE;
1462 case WM_SYSKEYDOWN:
1463 case WM_KEYDOWN: {
1464 //Platform::DebugPrintf("S keydown %d %x %x %x %x\n",iMessage, wParam, lParam, ::IsKeyDown(VK_SHIFT), ::IsKeyDown(VK_CONTROL));
1465 lastKeyDownConsumed = false;
1466 int ret = KeyDown(KeyTranslate(static_cast<int>(wParam)),
1467 Platform::IsKeyDown(VK_SHIFT),
1468 Platform::IsKeyDown(VK_CONTROL),
1469 Platform::IsKeyDown(VK_MENU),
1470 &lastKeyDownConsumed);
1471 if (!ret && !lastKeyDownConsumed) {
1472 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1474 break;
1477 case WM_IME_KEYDOWN: {
1478 if (wParam == VK_HANJA) {
1479 ToggleHanja();
1481 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1484 case WM_IME_REQUEST: {
1485 if (wParam == IMR_RECONVERTSTRING) {
1486 return ImeOnReconvert(lParam);
1488 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1491 case WM_KEYUP:
1492 //Platform::DebugPrintf("S keyup %d %x %x\n",iMessage, wParam, lParam);
1493 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1495 case WM_SETTINGCHANGE:
1496 //Platform::DebugPrintf("Setting Changed\n");
1497 InvalidateStyleData();
1498 // Get Intellimouse scroll line parameters
1499 GetIntelliMouseParameters();
1500 break;
1502 case WM_GETDLGCODE:
1503 return DLGC_HASSETSEL | DLGC_WANTALLKEYS;
1505 case WM_KILLFOCUS: {
1506 HWND wOther = reinterpret_cast<HWND>(wParam);
1507 HWND wThis = MainHWND();
1508 HWND wCT = static_cast<HWND>(ct.wCallTip.GetID());
1509 if (!wParam ||
1510 !(::IsChild(wThis, wOther) || (wOther == wCT))) {
1511 SetFocusState(false);
1512 DestroySystemCaret();
1514 // Explicitly complete any IME composition
1515 IMContext imc(MainHWND());
1516 if (imc.hIMC) {
1517 ::ImmNotifyIME(imc.hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
1520 break;
1522 case WM_SETFOCUS:
1523 SetFocusState(true);
1524 DestroySystemCaret();
1525 CreateSystemCaret();
1526 break;
1528 case WM_SYSCOLORCHANGE:
1529 //Platform::DebugPrintf("Setting Changed\n");
1530 InvalidateStyleData();
1531 break;
1533 case WM_IME_STARTCOMPOSITION: // dbcs
1534 if (KoreanIME() || imeInteraction == imeInline) {
1535 return 0;
1536 } else {
1537 ImeStartComposition();
1538 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1541 case WM_IME_ENDCOMPOSITION: // dbcs
1542 ImeEndComposition();
1543 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1545 case WM_IME_COMPOSITION:
1546 if (KoreanIME() || imeInteraction == imeInline) {
1547 return HandleCompositionInline(wParam, lParam);
1548 } else {
1549 return HandleCompositionWindowed(wParam, lParam);
1552 case WM_CONTEXTMENU:
1553 if (displayPopupMenu) {
1554 Point pt = Point::FromLong(static_cast<long>(lParam));
1555 if ((pt.x == -1) && (pt.y == -1)) {
1556 // Caused by keyboard so display menu near caret
1557 pt = PointMainCaret();
1558 POINT spt = {static_cast<int>(pt.x), static_cast<int>(pt.y)};
1559 ::ClientToScreen(MainHWND(), &spt);
1560 pt = PointFromPOINT(spt);
1562 ContextMenu(pt);
1563 return 0;
1565 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1567 case WM_INPUTLANGCHANGE:
1568 //::SetThreadLocale(LOWORD(lParam));
1569 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1571 case WM_INPUTLANGCHANGEREQUEST:
1572 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1574 case WM_ERASEBKGND:
1575 return 1; // Avoid any background erasure as whole window painted.
1577 case WM_CAPTURECHANGED:
1578 capturedMouse = false;
1579 return 0;
1581 case WM_IME_SETCONTEXT:
1582 if (KoreanIME() || imeInteraction == imeInline) {
1583 if (wParam) {
1584 LPARAM NoImeWin = lParam;
1585 NoImeWin = NoImeWin & (~ISC_SHOWUICOMPOSITIONWINDOW);
1586 return ::DefWindowProc(MainHWND(), iMessage, wParam, NoImeWin);
1589 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1591 // These are not handled in Scintilla and its faster to dispatch them here.
1592 // Also moves time out to here so profile doesn't count lots of empty message calls.
1594 case WM_MOVE:
1595 case WM_MOUSEACTIVATE:
1596 case WM_NCHITTEST:
1597 case WM_NCCALCSIZE:
1598 case WM_NCPAINT:
1599 case WM_NCMOUSEMOVE:
1600 case WM_NCLBUTTONDOWN:
1601 case WM_IME_NOTIFY:
1602 case WM_SYSCOMMAND:
1603 case WM_WINDOWPOSCHANGING:
1604 case WM_WINDOWPOSCHANGED:
1605 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1607 case WM_GETTEXTLENGTH:
1608 return GetTextLength();
1610 case WM_GETTEXT:
1611 return GetText(wParam, lParam);
1613 case EM_LINEFROMCHAR:
1614 if (static_cast<int>(wParam) < 0) {
1615 wParam = SelectionStart().Position();
1617 return pdoc->LineFromPosition(static_cast<int>(wParam));
1619 case EM_EXLINEFROMCHAR:
1620 return pdoc->LineFromPosition(static_cast<int>(lParam));
1622 case EM_GETSEL:
1623 if (wParam) {
1624 *reinterpret_cast<int *>(wParam) = SelectionStart().Position();
1626 if (lParam) {
1627 *reinterpret_cast<int *>(lParam) = SelectionEnd().Position();
1629 return MAKELONG(SelectionStart().Position(), SelectionEnd().Position());
1631 case EM_EXGETSEL: {
1632 if (lParam == 0) {
1633 return 0;
1635 Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
1636 pCR->cpMin = SelectionStart().Position();
1637 pCR->cpMax = SelectionEnd().Position();
1639 break;
1641 case EM_SETSEL: {
1642 int nStart = static_cast<int>(wParam);
1643 int nEnd = static_cast<int>(lParam);
1644 if (nStart == 0 && nEnd == -1) {
1645 nEnd = pdoc->Length();
1647 if (nStart == -1) {
1648 nStart = nEnd; // Remove selection
1650 if (nStart > nEnd) {
1651 SetSelection(nEnd, nStart);
1652 } else {
1653 SetSelection(nStart, nEnd);
1655 EnsureCaretVisible();
1657 break;
1659 case EM_EXSETSEL: {
1660 if (lParam == 0) {
1661 return 0;
1663 Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
1664 sel.selType = Selection::selStream;
1665 if (pCR->cpMin == 0 && pCR->cpMax == -1) {
1666 SetSelection(pCR->cpMin, pdoc->Length());
1667 } else {
1668 SetSelection(pCR->cpMin, pCR->cpMax);
1670 EnsureCaretVisible();
1671 return pdoc->LineFromPosition(SelectionStart().Position());
1674 case SCI_GETDIRECTFUNCTION:
1675 return reinterpret_cast<sptr_t>(DirectFunction);
1677 case SCI_GETDIRECTPOINTER:
1678 return reinterpret_cast<sptr_t>(this);
1680 case SCI_GRABFOCUS:
1681 ::SetFocus(MainHWND());
1682 break;
1684 #ifdef INCLUDE_DEPRECATED_FEATURES
1685 case SCI_SETKEYSUNICODE:
1686 break;
1688 case SCI_GETKEYSUNICODE:
1689 return true;
1690 #endif
1692 case SCI_SETTECHNOLOGY:
1693 if ((wParam == SC_TECHNOLOGY_DEFAULT) ||
1694 (wParam == SC_TECHNOLOGY_DIRECTWRITERETAIN) ||
1695 (wParam == SC_TECHNOLOGY_DIRECTWRITEDC) ||
1696 (wParam == SC_TECHNOLOGY_DIRECTWRITE)) {
1697 if (technology != static_cast<int>(wParam)) {
1698 if (static_cast<int>(wParam) > SC_TECHNOLOGY_DEFAULT) {
1699 #if defined(USE_D2D)
1700 if (!LoadD2D())
1701 // Failed to load Direct2D or DirectWrite so no effect
1702 return 0;
1703 #else
1704 return 0;
1705 #endif
1707 #if defined(USE_D2D)
1708 DropRenderTarget();
1709 #endif
1710 technology = static_cast<int>(wParam);
1711 // Invalidate all cached information including layout.
1712 DropGraphics(true);
1713 InvalidateStyleRedraw();
1716 break;
1718 #ifdef SCI_LEXER
1719 case SCI_LOADLEXERLIBRARY:
1720 LexerManager::GetInstance()->Load(reinterpret_cast<const char *>(lParam));
1721 break;
1722 #endif
1724 case SCI_TARGETASUTF8:
1725 return TargetAsUTF8(reinterpret_cast<char*>(lParam));
1727 case SCI_ENCODEDFROMUTF8:
1728 return EncodedFromUTF8(reinterpret_cast<char*>(wParam),
1729 reinterpret_cast<char*>(lParam));
1731 default:
1732 return ScintillaBase::WndProc(iMessage, wParam, lParam);
1734 } catch (std::bad_alloc &) {
1735 errorStatus = SC_STATUS_BADALLOC;
1736 } catch (...) {
1737 errorStatus = SC_STATUS_FAILURE;
1739 return 0l;
1742 bool ScintillaWin::ValidCodePage(int codePage) const {
1743 return codePage == 0 || codePage == SC_CP_UTF8 ||
1744 codePage == 932 || codePage == 936 || codePage == 949 ||
1745 codePage == 950 || codePage == 1361;
1748 sptr_t ScintillaWin::DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
1749 return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
1753 * Report that this Editor subclass has a working implementation of FineTickerStart.
1755 bool ScintillaWin::FineTickerAvailable() {
1756 return true;
1759 bool ScintillaWin::FineTickerRunning(TickReason reason) {
1760 return timers[reason] != 0;
1763 void ScintillaWin::FineTickerStart(TickReason reason, int millis, int tolerance) {
1764 FineTickerCancel(reason);
1765 if (SetCoalescableTimerFn && tolerance) {
1766 timers[reason] = SetCoalescableTimerFn(MainHWND(), fineTimerStart + reason, millis, NULL, tolerance);
1767 } else {
1768 timers[reason] = ::SetTimer(MainHWND(), fineTimerStart + reason, millis, NULL);
1772 void ScintillaWin::FineTickerCancel(TickReason reason) {
1773 if (timers[reason]) {
1774 ::KillTimer(MainHWND(), timers[reason]);
1775 timers[reason] = 0;
1780 bool ScintillaWin::SetIdle(bool on) {
1781 // On Win32 the Idler is implemented as a Timer on the Scintilla window. This
1782 // takes advantage of the fact that WM_TIMER messages are very low priority,
1783 // and are only posted when the message queue is empty, i.e. during idle time.
1784 if (idler.state != on) {
1785 if (on) {
1786 idler.idlerID = ::SetTimer(MainHWND(), idleTimerID, 10, NULL)
1787 ? reinterpret_cast<IdlerID>(idleTimerID) : 0;
1788 } else {
1789 ::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(idler.idlerID));
1790 idler.idlerID = 0;
1792 idler.state = idler.idlerID != 0;
1794 return idler.state;
1797 void ScintillaWin::SetMouseCapture(bool on) {
1798 if (mouseDownCaptures) {
1799 if (on) {
1800 ::SetCapture(MainHWND());
1801 } else {
1802 ::ReleaseCapture();
1805 capturedMouse = on;
1808 bool ScintillaWin::HaveMouseCapture() {
1809 // Cannot just see if GetCapture is this window as the scroll bar also sets capture for the window
1810 return capturedMouse;
1811 //return capturedMouse && (::GetCapture() == MainHWND());
1814 void ScintillaWin::SetTrackMouseLeaveEvent(bool on) {
1815 if (on && TrackMouseEventFn && !trackedMouseLeave) {
1816 TRACKMOUSEEVENT tme;
1817 tme.cbSize = sizeof(tme);
1818 tme.dwFlags = TME_LEAVE;
1819 tme.hwndTrack = MainHWND();
1820 tme.dwHoverTime = HOVER_DEFAULT; // Unused but triggers Dr. Memory if not initialized
1821 TrackMouseEventFn(&tme);
1823 trackedMouseLeave = on;
1826 bool ScintillaWin::PaintContains(PRectangle rc) {
1827 if (paintState == painting) {
1828 return BoundsContains(rcPaint, hRgnUpdate, rc);
1830 return true;
1833 void ScintillaWin::ScrollText(int /* linesToMove */) {
1834 //Platform::DebugPrintf("ScintillaWin::ScrollText %d\n", linesToMove);
1835 //::ScrollWindow(MainHWND(), 0,
1836 // vs.lineHeight * linesToMove, 0, 0);
1837 //::UpdateWindow(MainHWND());
1838 Redraw();
1839 UpdateSystemCaret();
1842 void ScintillaWin::UpdateSystemCaret() {
1843 if (hasFocus) {
1844 if (HasCaretSizeChanged()) {
1845 DestroySystemCaret();
1846 CreateSystemCaret();
1848 Point pos = PointMainCaret();
1849 ::SetCaretPos(static_cast<int>(pos.x), static_cast<int>(pos.y));
1853 int ScintillaWin::SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) {
1854 return ::SetScrollInfo(MainHWND(), nBar, lpsi, bRedraw);
1857 bool ScintillaWin::GetScrollInfo(int nBar, LPSCROLLINFO lpsi) {
1858 return ::GetScrollInfo(MainHWND(), nBar, lpsi) ? true : false;
1861 // Change the scroll position but avoid repaint if changing to same value
1862 void ScintillaWin::ChangeScrollPos(int barType, int pos) {
1863 SCROLLINFO sci = {
1864 sizeof(sci), 0, 0, 0, 0, 0, 0
1866 sci.fMask = SIF_POS;
1867 GetScrollInfo(barType, &sci);
1868 if (sci.nPos != pos) {
1869 DwellEnd(true);
1870 sci.nPos = pos;
1871 SetScrollInfo(barType, &sci, TRUE);
1875 void ScintillaWin::SetVerticalScrollPos() {
1876 ChangeScrollPos(SB_VERT, topLine);
1879 void ScintillaWin::SetHorizontalScrollPos() {
1880 ChangeScrollPos(SB_HORZ, xOffset);
1883 bool ScintillaWin::ModifyScrollBars(int nMax, int nPage) {
1884 bool modified = false;
1885 SCROLLINFO sci = {
1886 sizeof(sci), 0, 0, 0, 0, 0, 0
1888 sci.fMask = SIF_PAGE | SIF_RANGE;
1889 GetScrollInfo(SB_VERT, &sci);
1890 int vertEndPreferred = nMax;
1891 if (!verticalScrollBarVisible)
1892 nPage = vertEndPreferred + 1;
1893 if ((sci.nMin != 0) ||
1894 (sci.nMax != vertEndPreferred) ||
1895 (sci.nPage != static_cast<unsigned int>(nPage)) ||
1896 (sci.nPos != 0)) {
1897 sci.fMask = SIF_PAGE | SIF_RANGE;
1898 sci.nMin = 0;
1899 sci.nMax = vertEndPreferred;
1900 sci.nPage = nPage;
1901 sci.nPos = 0;
1902 sci.nTrackPos = 1;
1903 SetScrollInfo(SB_VERT, &sci, TRUE);
1904 modified = true;
1907 PRectangle rcText = GetTextRectangle();
1908 int horizEndPreferred = scrollWidth;
1909 if (horizEndPreferred < 0)
1910 horizEndPreferred = 0;
1911 unsigned int pageWidth = static_cast<unsigned int>(rcText.Width());
1912 if (!horizontalScrollBarVisible || Wrapping())
1913 pageWidth = horizEndPreferred + 1;
1914 sci.fMask = SIF_PAGE | SIF_RANGE;
1915 GetScrollInfo(SB_HORZ, &sci);
1916 if ((sci.nMin != 0) ||
1917 (sci.nMax != horizEndPreferred) ||
1918 (sci.nPage != pageWidth) ||
1919 (sci.nPos != 0)) {
1920 sci.fMask = SIF_PAGE | SIF_RANGE;
1921 sci.nMin = 0;
1922 sci.nMax = horizEndPreferred;
1923 sci.nPage = pageWidth;
1924 sci.nPos = 0;
1925 sci.nTrackPos = 1;
1926 SetScrollInfo(SB_HORZ, &sci, TRUE);
1927 modified = true;
1928 if (scrollWidth < static_cast<int>(pageWidth)) {
1929 HorizontalScrollTo(0);
1932 return modified;
1935 void ScintillaWin::NotifyChange() {
1936 ::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
1937 MAKELONG(GetCtrlID(), SCEN_CHANGE),
1938 reinterpret_cast<LPARAM>(MainHWND()));
1941 void ScintillaWin::NotifyFocus(bool focus) {
1942 ::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
1943 MAKELONG(GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS),
1944 reinterpret_cast<LPARAM>(MainHWND()));
1945 Editor::NotifyFocus(focus);
1948 void ScintillaWin::SetCtrlID(int identifier) {
1949 ::SetWindowID(static_cast<HWND>(wMain.GetID()), identifier);
1952 int ScintillaWin::GetCtrlID() {
1953 return ::GetDlgCtrlID(static_cast<HWND>(wMain.GetID()));
1956 void ScintillaWin::NotifyParent(SCNotification scn) {
1957 scn.nmhdr.hwndFrom = MainHWND();
1958 scn.nmhdr.idFrom = GetCtrlID();
1959 ::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
1960 GetCtrlID(), reinterpret_cast<LPARAM>(&scn));
1963 void ScintillaWin::NotifyParent(SCNotification * scn) {
1964 scn->nmhdr.hwndFrom = MainHWND();
1965 scn->nmhdr.idFrom = GetCtrlID();
1966 ::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
1967 GetCtrlID(), reinterpret_cast<LPARAM>(scn));
1970 void ScintillaWin::NotifyDoubleClick(Point pt, int modifiers) {
1971 //Platform::DebugPrintf("ScintillaWin Double click 0\n");
1972 ScintillaBase::NotifyDoubleClick(pt, modifiers);
1973 // Send myself a WM_LBUTTONDBLCLK, so the container can handle it too.
1974 ::SendMessage(MainHWND(),
1975 WM_LBUTTONDBLCLK,
1976 (modifiers & SCI_SHIFT) ? MK_SHIFT : 0,
1977 MAKELPARAM(pt.x, pt.y));
1980 class CaseFolderDBCS : public CaseFolderTable {
1981 // Allocate the expandable storage here so that it does not need to be reallocated
1982 // for each call to Fold.
1983 std::vector<wchar_t> utf16Mixed;
1984 std::vector<wchar_t> utf16Folded;
1985 UINT cp;
1986 public:
1987 explicit CaseFolderDBCS(UINT cp_) : cp(cp_) {
1988 StandardASCII();
1990 virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
1991 if ((lenMixed == 1) && (sizeFolded > 0)) {
1992 folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
1993 return 1;
1994 } else {
1995 if (lenMixed > utf16Mixed.size()) {
1996 utf16Mixed.resize(lenMixed + 8);
1998 size_t nUtf16Mixed = ::MultiByteToWideChar(cp, 0, mixed,
1999 static_cast<int>(lenMixed),
2000 &utf16Mixed[0],
2001 static_cast<int>(utf16Mixed.size()));
2003 if (nUtf16Mixed == 0) {
2004 // Failed to convert -> bad input
2005 folded[0] = '\0';
2006 return 1;
2009 unsigned int lenFlat = 0;
2010 for (size_t mixIndex=0; mixIndex < nUtf16Mixed; mixIndex++) {
2011 if ((lenFlat + 20) > utf16Folded.size())
2012 utf16Folded.resize(lenFlat + 60);
2013 const char *foldedUTF8 = CaseConvert(utf16Mixed[mixIndex], CaseConversionFold);
2014 if (foldedUTF8) {
2015 // Maximum length of a case conversion is 6 bytes, 3 characters
2016 wchar_t wFolded[20];
2017 size_t charsConverted = UTF16FromUTF8(foldedUTF8,
2018 strlen(foldedUTF8),
2019 wFolded, ELEMENTS(wFolded));
2020 for (size_t j=0; j<charsConverted; j++)
2021 utf16Folded[lenFlat++] = wFolded[j];
2022 } else {
2023 utf16Folded[lenFlat++] = utf16Mixed[mixIndex];
2027 size_t lenOut = ::WideCharToMultiByte(cp, 0,
2028 &utf16Folded[0], lenFlat,
2029 NULL, 0, NULL, 0);
2031 if (lenOut < sizeFolded) {
2032 ::WideCharToMultiByte(cp, 0,
2033 &utf16Folded[0], lenFlat,
2034 folded, static_cast<int>(lenOut), NULL, 0);
2035 return lenOut;
2036 } else {
2037 return 0;
2043 CaseFolder *ScintillaWin::CaseFolderForEncoding() {
2044 UINT cpDest = CodePageOfDocument();
2045 if (cpDest == SC_CP_UTF8) {
2046 return new CaseFolderUnicode();
2047 } else {
2048 if (pdoc->dbcsCodePage == 0) {
2049 CaseFolderTable *pcf = new CaseFolderTable();
2050 pcf->StandardASCII();
2051 // Only for single byte encodings
2052 UINT cpDoc = CodePageOfDocument();
2053 for (int i=0x80; i<0x100; i++) {
2054 char sCharacter[2] = "A";
2055 sCharacter[0] = static_cast<char>(i);
2056 wchar_t wCharacter[20];
2057 unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, sCharacter, 1,
2058 wCharacter, ELEMENTS(wCharacter));
2059 if (lengthUTF16 == 1) {
2060 const char *caseFolded = CaseConvert(wCharacter[0], CaseConversionFold);
2061 if (caseFolded) {
2062 wchar_t wLower[20];
2063 size_t charsConverted = UTF16FromUTF8(caseFolded,
2064 strlen(caseFolded),
2065 wLower, ELEMENTS(wLower));
2066 if (charsConverted == 1) {
2067 char sCharacterLowered[20];
2068 unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
2069 wLower, static_cast<int>(charsConverted),
2070 sCharacterLowered, ELEMENTS(sCharacterLowered), NULL, 0);
2071 if ((lengthConverted == 1) && (sCharacter[0] != sCharacterLowered[0])) {
2072 pcf->SetTranslation(sCharacter[0], sCharacterLowered[0]);
2078 return pcf;
2079 } else {
2080 return new CaseFolderDBCS(cpDest);
2085 std::string ScintillaWin::CaseMapString(const std::string &s, int caseMapping) {
2086 if ((s.size() == 0) || (caseMapping == cmSame))
2087 return s;
2089 UINT cpDoc = CodePageOfDocument();
2090 if (cpDoc == SC_CP_UTF8) {
2091 std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
2092 size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
2093 (caseMapping == cmUpper) ? CaseConversionUpper : CaseConversionLower);
2094 retMapped.resize(lenMapped);
2095 return retMapped;
2098 unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, s.c_str(),
2099 static_cast<int>(s.size()), NULL, 0);
2100 if (lengthUTF16 == 0) // Failed to convert
2101 return s;
2103 DWORD mapFlags = LCMAP_LINGUISTIC_CASING |
2104 ((caseMapping == cmUpper) ? LCMAP_UPPERCASE : LCMAP_LOWERCASE);
2106 // Change text to UTF-16
2107 std::vector<wchar_t> vwcText(lengthUTF16);
2108 ::MultiByteToWideChar(cpDoc, 0, s.c_str(), static_cast<int>(s.size()), &vwcText[0], lengthUTF16);
2110 // Change case
2111 int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
2112 &vwcText[0], lengthUTF16, NULL, 0);
2113 std::vector<wchar_t> vwcConverted(charsConverted);
2114 ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
2115 &vwcText[0], lengthUTF16, &vwcConverted[0], charsConverted);
2117 // Change back to document encoding
2118 unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
2119 &vwcConverted[0], static_cast<int>(vwcConverted.size()),
2120 NULL, 0, NULL, 0);
2121 std::vector<char> vcConverted(lengthConverted);
2122 ::WideCharToMultiByte(cpDoc, 0,
2123 &vwcConverted[0], static_cast<int>(vwcConverted.size()),
2124 &vcConverted[0], static_cast<int>(vcConverted.size()), NULL, 0);
2126 return std::string(&vcConverted[0], vcConverted.size());
2129 void ScintillaWin::Copy() {
2130 //Platform::DebugPrintf("Copy\n");
2131 if (!sel.Empty()) {
2132 SelectionText selectedText;
2133 CopySelectionRange(&selectedText);
2134 CopyToClipboard(selectedText);
2138 void ScintillaWin::CopyAllowLine() {
2139 SelectionText selectedText;
2140 CopySelectionRange(&selectedText, true);
2141 CopyToClipboard(selectedText);
2144 bool ScintillaWin::CanPaste() {
2145 if (!Editor::CanPaste())
2146 return false;
2147 if (::IsClipboardFormatAvailable(CF_TEXT))
2148 return true;
2149 if (IsUnicodeMode())
2150 return ::IsClipboardFormatAvailable(CF_UNICODETEXT) != 0;
2151 return false;
2154 class GlobalMemory {
2155 HGLOBAL hand;
2156 public:
2157 void *ptr;
2158 GlobalMemory() : hand(0), ptr(0) {
2160 explicit GlobalMemory(HGLOBAL hand_) : hand(hand_), ptr(0) {
2161 if (hand) {
2162 ptr = ::GlobalLock(hand);
2165 ~GlobalMemory() {
2166 PLATFORM_ASSERT(!ptr);
2167 assert(!hand);
2169 void Allocate(size_t bytes) {
2170 assert(!hand);
2171 hand = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bytes);
2172 if (hand) {
2173 ptr = ::GlobalLock(hand);
2176 HGLOBAL Unlock() {
2177 PLATFORM_ASSERT(ptr);
2178 HGLOBAL handCopy = hand;
2179 ::GlobalUnlock(hand);
2180 ptr = 0;
2181 hand = 0;
2182 return handCopy;
2184 void SetClip(UINT uFormat) {
2185 ::SetClipboardData(uFormat, Unlock());
2187 operator bool() const {
2188 return ptr != 0;
2190 SIZE_T Size() {
2191 return ::GlobalSize(hand);
2195 // OpenClipboard may fail if another application has opened the clipboard.
2196 // Try up to 8 times, with an initial delay of 1 ms and an exponential back off
2197 // for a maximum total delay of 127 ms (1+2+4+8+16+32+64).
2198 static bool OpenClipboardRetry(HWND hwnd) {
2199 for (int attempt=0; attempt<8; attempt++) {
2200 if (attempt > 0) {
2201 ::Sleep(1 << (attempt-1));
2203 if (::OpenClipboard(hwnd)) {
2204 return true;
2207 return false;
2210 void ScintillaWin::Paste() {
2211 if (!::OpenClipboardRetry(MainHWND())) {
2212 return;
2214 UndoGroup ug(pdoc);
2215 const bool isLine = SelectionEmpty() &&
2216 (::IsClipboardFormatAvailable(cfLineSelect) || ::IsClipboardFormatAvailable(cfVSLineTag));
2217 ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
2218 bool isRectangular = (::IsClipboardFormatAvailable(cfColumnSelect) != 0);
2220 if (!isRectangular) {
2221 // Evaluate "Borland IDE Block Type" explicitly
2222 GlobalMemory memBorlandSelection(::GetClipboardData(cfBorlandIDEBlockType));
2223 if (memBorlandSelection) {
2224 isRectangular = (memBorlandSelection.Size() == 1) && (static_cast<BYTE *>(memBorlandSelection.ptr)[0] == 0x02);
2225 memBorlandSelection.Unlock();
2228 const PasteShape pasteShape = isRectangular ? pasteRectangular : (isLine ? pasteLine : pasteStream);
2230 // Always use CF_UNICODETEXT if available
2231 GlobalMemory memUSelection(::GetClipboardData(CF_UNICODETEXT));
2232 if (memUSelection) {
2233 wchar_t *uptr = static_cast<wchar_t *>(memUSelection.ptr);
2234 if (uptr) {
2235 unsigned int len;
2236 std::vector<char> putf;
2237 // Default Scintilla behaviour in Unicode mode
2238 if (IsUnicodeMode()) {
2239 unsigned int bytes = static_cast<unsigned int>(memUSelection.Size());
2240 len = UTF8Length(uptr, bytes / 2);
2241 putf.resize(len + 1);
2242 UTF8FromUTF16(uptr, bytes / 2, &putf[0], len);
2243 } else {
2244 // CF_UNICODETEXT available, but not in Unicode mode
2245 // Convert from Unicode to current Scintilla code page
2246 UINT cpDest = CodePageOfDocument();
2247 len = ::WideCharToMultiByte(cpDest, 0, uptr, -1,
2248 NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
2249 putf.resize(len + 1);
2250 ::WideCharToMultiByte(cpDest, 0, uptr, -1,
2251 &putf[0], len + 1, NULL, NULL);
2254 InsertPasteShape(&putf[0], len, pasteShape);
2256 memUSelection.Unlock();
2257 } else {
2258 // CF_UNICODETEXT not available, paste ANSI text
2259 GlobalMemory memSelection(::GetClipboardData(CF_TEXT));
2260 if (memSelection) {
2261 char *ptr = static_cast<char *>(memSelection.ptr);
2262 if (ptr) {
2263 unsigned int bytes = static_cast<unsigned int>(memSelection.Size());
2264 unsigned int len = bytes;
2265 for (unsigned int i = 0; i < bytes; i++) {
2266 if ((len == bytes) && (0 == ptr[i]))
2267 len = i;
2270 // In Unicode mode, convert clipboard text to UTF-8
2271 if (IsUnicodeMode()) {
2272 std::vector<wchar_t> uptr(len+1);
2274 unsigned int ulen = ::MultiByteToWideChar(CP_ACP, 0,
2275 ptr, len, &uptr[0], len+1);
2277 unsigned int mlen = UTF8Length(&uptr[0], ulen);
2278 std::vector<char> putf(mlen+1);
2279 UTF8FromUTF16(&uptr[0], ulen, &putf[0], mlen);
2281 InsertPasteShape(&putf[0], mlen, pasteShape);
2282 } else {
2283 InsertPasteShape(ptr, len, pasteShape);
2286 memSelection.Unlock();
2289 ::CloseClipboard();
2290 Redraw();
2293 void ScintillaWin::CreateCallTipWindow(PRectangle) {
2294 if (!ct.wCallTip.Created()) {
2295 ct.wCallTip = ::CreateWindow(callClassName, TEXT("ACallTip"),
2296 WS_POPUP, 100, 100, 150, 20,
2297 MainHWND(), 0,
2298 GetWindowInstance(MainHWND()),
2299 this);
2300 ct.wDraw = ct.wCallTip;
2304 void ScintillaWin::AddToPopUp(const char *label, int cmd, bool enabled) {
2305 HMENU hmenuPopup = static_cast<HMENU>(popup.GetID());
2306 if (!label[0])
2307 ::AppendMenuA(hmenuPopup, MF_SEPARATOR, 0, "");
2308 else if (enabled)
2309 ::AppendMenuA(hmenuPopup, MF_STRING, cmd, label);
2310 else
2311 ::AppendMenuA(hmenuPopup, MF_STRING | MF_DISABLED | MF_GRAYED, cmd, label);
2314 void ScintillaWin::ClaimSelection() {
2315 // Windows does not have a primary selection
2318 /// Implement IUnknown
2320 STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe);
2321 STDMETHODIMP FormatEnumerator_QueryInterface(FormatEnumerator *fe, REFIID riid, PVOID *ppv) {
2322 //Platform::DebugPrintf("EFE QI");
2323 *ppv = NULL;
2324 if (riid == IID_IUnknown)
2325 *ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
2326 if (riid == IID_IEnumFORMATETC)
2327 *ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
2328 if (!*ppv)
2329 return E_NOINTERFACE;
2330 FormatEnumerator_AddRef(fe);
2331 return S_OK;
2333 STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe) {
2334 return ++fe->ref;
2336 STDMETHODIMP_(ULONG)FormatEnumerator_Release(FormatEnumerator *fe) {
2337 fe->ref--;
2338 if (fe->ref > 0)
2339 return fe->ref;
2340 delete fe;
2341 return 0;
2343 /// Implement IEnumFORMATETC
2344 STDMETHODIMP FormatEnumerator_Next(FormatEnumerator *fe, ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) {
2345 if (rgelt == NULL) return E_POINTER;
2346 unsigned int putPos = 0;
2347 while ((fe->pos < fe->formats.size()) && (putPos < celt)) {
2348 rgelt->cfFormat = fe->formats[fe->pos];
2349 rgelt->ptd = 0;
2350 rgelt->dwAspect = DVASPECT_CONTENT;
2351 rgelt->lindex = -1;
2352 rgelt->tymed = TYMED_HGLOBAL;
2353 rgelt++;
2354 fe->pos++;
2355 putPos++;
2357 if (pceltFetched)
2358 *pceltFetched = putPos;
2359 return putPos ? S_OK : S_FALSE;
2361 STDMETHODIMP FormatEnumerator_Skip(FormatEnumerator *fe, ULONG celt) {
2362 fe->pos += celt;
2363 return S_OK;
2365 STDMETHODIMP FormatEnumerator_Reset(FormatEnumerator *fe) {
2366 fe->pos = 0;
2367 return S_OK;
2369 STDMETHODIMP FormatEnumerator_Clone(FormatEnumerator *fe, IEnumFORMATETC **ppenum) {
2370 FormatEnumerator *pfe;
2371 try {
2372 pfe = new FormatEnumerator(fe->pos, &fe->formats[0], fe->formats.size());
2373 } catch (...) {
2374 return E_OUTOFMEMORY;
2376 return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
2377 reinterpret_cast<void **>(ppenum));
2380 static VFunction *vtFormatEnumerator[] = {
2381 (VFunction *)(FormatEnumerator_QueryInterface),
2382 (VFunction *)(FormatEnumerator_AddRef),
2383 (VFunction *)(FormatEnumerator_Release),
2384 (VFunction *)(FormatEnumerator_Next),
2385 (VFunction *)(FormatEnumerator_Skip),
2386 (VFunction *)(FormatEnumerator_Reset),
2387 (VFunction *)(FormatEnumerator_Clone)
2390 FormatEnumerator::FormatEnumerator(int pos_, CLIPFORMAT formats_[], size_t formatsLen_) {
2391 vtbl = vtFormatEnumerator;
2392 ref = 0; // First QI adds first reference...
2393 pos = pos_;
2394 formats.insert(formats.begin(), formats_, formats_+formatsLen_);
2397 /// Implement IUnknown
2398 STDMETHODIMP DropSource_QueryInterface(DropSource *ds, REFIID riid, PVOID *ppv) {
2399 return ds->sci->QueryInterface(riid, ppv);
2401 STDMETHODIMP_(ULONG)DropSource_AddRef(DropSource *ds) {
2402 return ds->sci->AddRef();
2404 STDMETHODIMP_(ULONG)DropSource_Release(DropSource *ds) {
2405 return ds->sci->Release();
2408 /// Implement IDropSource
2409 STDMETHODIMP DropSource_QueryContinueDrag(DropSource *, BOOL fEsc, DWORD grfKeyState) {
2410 if (fEsc)
2411 return DRAGDROP_S_CANCEL;
2412 if (!(grfKeyState & MK_LBUTTON))
2413 return DRAGDROP_S_DROP;
2414 return S_OK;
2417 STDMETHODIMP DropSource_GiveFeedback(DropSource *, DWORD) {
2418 return DRAGDROP_S_USEDEFAULTCURSORS;
2421 static VFunction *vtDropSource[] = {
2422 (VFunction *)(DropSource_QueryInterface),
2423 (VFunction *)(DropSource_AddRef),
2424 (VFunction *)(DropSource_Release),
2425 (VFunction *)(DropSource_QueryContinueDrag),
2426 (VFunction *)(DropSource_GiveFeedback)
2429 DropSource::DropSource() {
2430 vtbl = vtDropSource;
2431 sci = 0;
2434 /// Implement IUnkown
2435 STDMETHODIMP DataObject_QueryInterface(DataObject *pd, REFIID riid, PVOID *ppv) {
2436 //Platform::DebugPrintf("DO QI %x\n", pd);
2437 return pd->sci->QueryInterface(riid, ppv);
2439 STDMETHODIMP_(ULONG)DataObject_AddRef(DataObject *pd) {
2440 return pd->sci->AddRef();
2442 STDMETHODIMP_(ULONG)DataObject_Release(DataObject *pd) {
2443 return pd->sci->Release();
2445 /// Implement IDataObject
2446 STDMETHODIMP DataObject_GetData(DataObject *pd, FORMATETC *pFEIn, STGMEDIUM *pSTM) {
2447 return pd->sci->GetData(pFEIn, pSTM);
2450 STDMETHODIMP DataObject_GetDataHere(DataObject *, FORMATETC *, STGMEDIUM *) {
2451 //Platform::DebugPrintf("DOB GetDataHere\n");
2452 return E_NOTIMPL;
2455 STDMETHODIMP DataObject_QueryGetData(DataObject *pd, FORMATETC *pFE) {
2456 if (pd->sci->DragIsRectangularOK(pFE->cfFormat) &&
2457 pFE->ptd == 0 &&
2458 (pFE->dwAspect & DVASPECT_CONTENT) != 0 &&
2459 pFE->lindex == -1 &&
2460 (pFE->tymed & TYMED_HGLOBAL) != 0
2462 return S_OK;
2465 bool formatOK = (pFE->cfFormat == CF_TEXT) ||
2466 ((pFE->cfFormat == CF_UNICODETEXT) && pd->sci->IsUnicodeMode());
2467 if (!formatOK ||
2468 pFE->ptd != 0 ||
2469 (pFE->dwAspect & DVASPECT_CONTENT) == 0 ||
2470 pFE->lindex != -1 ||
2471 (pFE->tymed & TYMED_HGLOBAL) == 0
2473 //Platform::DebugPrintf("DOB QueryGetData No %x\n",pFE->cfFormat);
2474 //return DATA_E_FORMATETC;
2475 return S_FALSE;
2477 //Platform::DebugPrintf("DOB QueryGetData OK %x\n",pFE->cfFormat);
2478 return S_OK;
2481 STDMETHODIMP DataObject_GetCanonicalFormatEtc(DataObject *pd, FORMATETC *, FORMATETC *pFEOut) {
2482 //Platform::DebugPrintf("DOB GetCanon\n");
2483 if (pd->sci->IsUnicodeMode())
2484 pFEOut->cfFormat = CF_UNICODETEXT;
2485 else
2486 pFEOut->cfFormat = CF_TEXT;
2487 pFEOut->ptd = 0;
2488 pFEOut->dwAspect = DVASPECT_CONTENT;
2489 pFEOut->lindex = -1;
2490 pFEOut->tymed = TYMED_HGLOBAL;
2491 return S_OK;
2494 STDMETHODIMP DataObject_SetData(DataObject *, FORMATETC *, STGMEDIUM *, BOOL) {
2495 //Platform::DebugPrintf("DOB SetData\n");
2496 return E_FAIL;
2499 STDMETHODIMP DataObject_EnumFormatEtc(DataObject *pd, DWORD dwDirection, IEnumFORMATETC **ppEnum) {
2500 try {
2501 //Platform::DebugPrintf("DOB EnumFormatEtc %d\n", dwDirection);
2502 if (dwDirection != DATADIR_GET) {
2503 *ppEnum = 0;
2504 return E_FAIL;
2506 FormatEnumerator *pfe;
2507 if (pd->sci->IsUnicodeMode()) {
2508 CLIPFORMAT formats[] = {CF_UNICODETEXT, CF_TEXT};
2509 pfe = new FormatEnumerator(0, formats, ELEMENTS(formats));
2510 } else {
2511 CLIPFORMAT formats[] = {CF_TEXT};
2512 pfe = new FormatEnumerator(0, formats, ELEMENTS(formats));
2514 return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
2515 reinterpret_cast<void **>(ppEnum));
2516 } catch (std::bad_alloc &) {
2517 pd->sci->errorStatus = SC_STATUS_BADALLOC;
2518 return E_OUTOFMEMORY;
2519 } catch (...) {
2520 pd->sci->errorStatus = SC_STATUS_FAILURE;
2521 return E_FAIL;
2525 STDMETHODIMP DataObject_DAdvise(DataObject *, FORMATETC *, DWORD, IAdviseSink *, PDWORD) {
2526 //Platform::DebugPrintf("DOB DAdvise\n");
2527 return E_FAIL;
2530 STDMETHODIMP DataObject_DUnadvise(DataObject *, DWORD) {
2531 //Platform::DebugPrintf("DOB DUnadvise\n");
2532 return E_FAIL;
2535 STDMETHODIMP DataObject_EnumDAdvise(DataObject *, IEnumSTATDATA **) {
2536 //Platform::DebugPrintf("DOB EnumDAdvise\n");
2537 return E_FAIL;
2540 static VFunction *vtDataObject[] = {
2541 (VFunction *)(DataObject_QueryInterface),
2542 (VFunction *)(DataObject_AddRef),
2543 (VFunction *)(DataObject_Release),
2544 (VFunction *)(DataObject_GetData),
2545 (VFunction *)(DataObject_GetDataHere),
2546 (VFunction *)(DataObject_QueryGetData),
2547 (VFunction *)(DataObject_GetCanonicalFormatEtc),
2548 (VFunction *)(DataObject_SetData),
2549 (VFunction *)(DataObject_EnumFormatEtc),
2550 (VFunction *)(DataObject_DAdvise),
2551 (VFunction *)(DataObject_DUnadvise),
2552 (VFunction *)(DataObject_EnumDAdvise)
2555 DataObject::DataObject() {
2556 vtbl = vtDataObject;
2557 sci = 0;
2560 /// Implement IUnknown
2561 STDMETHODIMP DropTarget_QueryInterface(DropTarget *dt, REFIID riid, PVOID *ppv) {
2562 //Platform::DebugPrintf("DT QI %x\n", dt);
2563 return dt->sci->QueryInterface(riid, ppv);
2565 STDMETHODIMP_(ULONG)DropTarget_AddRef(DropTarget *dt) {
2566 return dt->sci->AddRef();
2568 STDMETHODIMP_(ULONG)DropTarget_Release(DropTarget *dt) {
2569 return dt->sci->Release();
2572 /// Implement IDropTarget by forwarding to Scintilla
2573 STDMETHODIMP DropTarget_DragEnter(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2574 POINTL pt, PDWORD pdwEffect) {
2575 try {
2576 return dt->sci->DragEnter(pIDataSource, grfKeyState, pt, pdwEffect);
2577 } catch (...) {
2578 dt->sci->errorStatus = SC_STATUS_FAILURE;
2580 return E_FAIL;
2582 STDMETHODIMP DropTarget_DragOver(DropTarget *dt, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
2583 try {
2584 return dt->sci->DragOver(grfKeyState, pt, pdwEffect);
2585 } catch (...) {
2586 dt->sci->errorStatus = SC_STATUS_FAILURE;
2588 return E_FAIL;
2590 STDMETHODIMP DropTarget_DragLeave(DropTarget *dt) {
2591 try {
2592 return dt->sci->DragLeave();
2593 } catch (...) {
2594 dt->sci->errorStatus = SC_STATUS_FAILURE;
2596 return E_FAIL;
2598 STDMETHODIMP DropTarget_Drop(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
2599 POINTL pt, PDWORD pdwEffect) {
2600 try {
2601 return dt->sci->Drop(pIDataSource, grfKeyState, pt, pdwEffect);
2602 } catch (...) {
2603 dt->sci->errorStatus = SC_STATUS_FAILURE;
2605 return E_FAIL;
2608 static VFunction *vtDropTarget[] = {
2609 (VFunction *)(DropTarget_QueryInterface),
2610 (VFunction *)(DropTarget_AddRef),
2611 (VFunction *)(DropTarget_Release),
2612 (VFunction *)(DropTarget_DragEnter),
2613 (VFunction *)(DropTarget_DragOver),
2614 (VFunction *)(DropTarget_DragLeave),
2615 (VFunction *)(DropTarget_Drop)
2618 DropTarget::DropTarget() {
2619 vtbl = vtDropTarget;
2620 sci = 0;
2624 * DBCS: support Input Method Editor (IME).
2625 * Called when IME Window opened.
2627 void ScintillaWin::ImeStartComposition() {
2628 if (caret.active) {
2629 // Move IME Window to current caret position
2630 IMContext imc(MainHWND());
2631 Point pos = PointMainCaret();
2632 COMPOSITIONFORM CompForm;
2633 CompForm.dwStyle = CFS_POINT;
2634 CompForm.ptCurrentPos.x = static_cast<int>(pos.x);
2635 CompForm.ptCurrentPos.y = static_cast<int>(pos.y);
2637 ::ImmSetCompositionWindow(imc.hIMC, &CompForm);
2639 // Set font of IME window to same as surrounded text.
2640 if (stylesValid) {
2641 // Since the style creation code has been made platform independent,
2642 // The logfont for the IME is recreated here.
2643 const int styleHere = pdoc->StyleIndexAt(sel.MainCaret());
2644 LOGFONTW lf = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L""};
2645 int sizeZoomed = vs.styles[styleHere].size + vs.zoomLevel * SC_FONT_SIZE_MULTIPLIER;
2646 if (sizeZoomed <= 2 * SC_FONT_SIZE_MULTIPLIER) // Hangs if sizeZoomed <= 1
2647 sizeZoomed = 2 * SC_FONT_SIZE_MULTIPLIER;
2648 AutoSurface surface(this);
2649 int deviceHeight = sizeZoomed;
2650 if (surface) {
2651 deviceHeight = (sizeZoomed * surface->LogPixelsY()) / 72;
2653 // The negative is to allow for leading
2654 lf.lfHeight = -(abs(deviceHeight / SC_FONT_SIZE_MULTIPLIER));
2655 lf.lfWeight = vs.styles[styleHere].weight;
2656 lf.lfItalic = static_cast<BYTE>(vs.styles[styleHere].italic ? 1 : 0);
2657 lf.lfCharSet = DEFAULT_CHARSET;
2658 lf.lfFaceName[0] = L'\0';
2659 if (vs.styles[styleHere].fontName) {
2660 const char* fontName = vs.styles[styleHere].fontName;
2661 UTF16FromUTF8(fontName, strlen(fontName)+1, lf.lfFaceName, LF_FACESIZE);
2664 ::ImmSetCompositionFontW(imc.hIMC, &lf);
2666 // Caret is displayed in IME window. So, caret in Scintilla is useless.
2667 DropCaret();
2671 /** Called when IME Window closed. */
2672 void ScintillaWin::ImeEndComposition() {
2673 ShowCaretAtCurrentPosition();
2676 LRESULT ScintillaWin::ImeOnReconvert(LPARAM lParam) {
2677 // Reconversion on windows limits within one line without eol.
2678 // Look around: baseStart <-- (|mainStart| -- mainEnd) --> baseEnd.
2679 const int mainStart = sel.RangeMain().Start().Position();
2680 const int mainEnd = sel.RangeMain().End().Position();
2681 const int curLine = pdoc->LineFromPosition(mainStart);
2682 if (curLine != pdoc->LineFromPosition(mainEnd))
2683 return 0;
2684 const int baseStart = pdoc->LineStart(curLine);
2685 const int baseEnd = pdoc->LineEnd(curLine);
2686 if ((baseStart == baseEnd) || (mainEnd > baseEnd))
2687 return 0;
2689 const int codePage = CodePageOfDocument();
2690 const std::wstring rcFeed = StringDecode(RangeText(baseStart, baseEnd), codePage);
2691 const int rcFeedLen = static_cast<int>(rcFeed.length()) * sizeof(wchar_t);
2692 const int rcSize = sizeof(RECONVERTSTRING) + rcFeedLen + sizeof(wchar_t);
2694 RECONVERTSTRING *rc = (RECONVERTSTRING *)lParam;
2695 if (!rc)
2696 return rcSize; // Immediately be back with rcSize of memory block.
2698 wchar_t *rcFeedStart = (wchar_t*)(rc + 1);
2699 memcpy(rcFeedStart, &rcFeed[0], rcFeedLen);
2701 std::string rcCompString = RangeText(mainStart, mainEnd);
2702 std::wstring rcCompWstring = StringDecode(rcCompString, codePage);
2703 std::string rcCompStart = RangeText(baseStart, mainStart);
2704 std::wstring rcCompWstart = StringDecode(rcCompStart, codePage);
2706 // Map selection to dwCompStr.
2707 // No selection assumes current caret as rcCompString without length.
2708 rc->dwVersion = 0; // It should be absolutely 0.
2709 rc->dwStrLen = (DWORD)static_cast<int>(rcFeed.length());
2710 rc->dwStrOffset = sizeof(RECONVERTSTRING);
2711 rc->dwCompStrLen = (DWORD)static_cast<int>(rcCompWstring.length());
2712 rc->dwCompStrOffset = (DWORD)static_cast<int>(rcCompWstart.length()) * sizeof(wchar_t);
2713 rc->dwTargetStrLen = rc->dwCompStrLen;
2714 rc->dwTargetStrOffset =rc->dwCompStrOffset;
2716 IMContext imc(MainHWND());
2717 if (!imc.hIMC)
2718 return 0;
2720 if (!::ImmSetCompositionStringW(imc.hIMC, SCS_QUERYRECONVERTSTRING, rc, rcSize, NULL, 0))
2721 return 0;
2723 // No selection asks IME to fill target fields with its own value.
2724 int tgWlen = rc->dwTargetStrLen;
2725 int tgWstart = rc->dwTargetStrOffset / sizeof(wchar_t);
2727 std::string tgCompStart = StringEncode(rcFeed.substr(0, tgWstart), codePage);
2728 std::string tgComp = StringEncode(rcFeed.substr(tgWstart, tgWlen), codePage);
2730 // No selection needs to adjust reconvert start position for IME set.
2731 int adjust = static_cast<int>(tgCompStart.length() - rcCompStart.length());
2732 int docCompLen = static_cast<int>(tgComp.length());
2734 // Make place for next composition string to sit in.
2735 for (size_t r=0; r<sel.Count(); r++) {
2736 int rBase = sel.Range(r).Start().Position();
2737 int docCompStart = rBase + adjust;
2739 if (inOverstrike) { // the docCompLen of bytes will be overstriked.
2740 sel.Range(r).caret.SetPosition(docCompStart);
2741 sel.Range(r).anchor.SetPosition(docCompStart);
2742 } else {
2743 // Ensure docCompStart+docCompLen be not beyond lineEnd.
2744 // since docCompLen by byte might break eol.
2745 int lineEnd = pdoc->LineEnd(pdoc->LineFromPosition(rBase));
2746 int overflow = (docCompStart + docCompLen) - lineEnd;
2747 if (overflow > 0) {
2748 pdoc->DeleteChars(docCompStart, docCompLen - overflow);
2749 } else {
2750 pdoc->DeleteChars(docCompStart, docCompLen);
2754 // Immediately Target Input or candidate box choice with GCS_COMPSTR.
2755 return rcSize;
2758 void ScintillaWin::GetIntelliMouseParameters() {
2759 // This retrieves the number of lines per scroll as configured inthe Mouse Properties sheet in Control Panel
2760 ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
2763 void ScintillaWin::CopyToClipboard(const SelectionText &selectedText) {
2764 if (!::OpenClipboardRetry(MainHWND())) {
2765 return;
2767 ::EmptyClipboard();
2769 GlobalMemory uniText;
2771 // Default Scintilla behaviour in Unicode mode
2772 if (IsUnicodeMode()) {
2773 size_t uchars = UTF16Length(selectedText.Data(),
2774 static_cast<int>(selectedText.LengthWithTerminator()));
2775 uniText.Allocate(2 * uchars);
2776 if (uniText) {
2777 UTF16FromUTF8(selectedText.Data(), selectedText.LengthWithTerminator(),
2778 static_cast<wchar_t *>(uniText.ptr), uchars);
2780 } else {
2781 // Not Unicode mode
2782 // Convert to Unicode using the current Scintilla code page
2783 UINT cpSrc = CodePageFromCharSet(
2784 selectedText.characterSet, selectedText.codePage);
2785 int uLen = ::MultiByteToWideChar(cpSrc, 0, selectedText.Data(),
2786 static_cast<int>(selectedText.LengthWithTerminator()), 0, 0);
2787 uniText.Allocate(2 * uLen);
2788 if (uniText) {
2789 ::MultiByteToWideChar(cpSrc, 0, selectedText.Data(),
2790 static_cast<int>(selectedText.LengthWithTerminator()),
2791 static_cast<wchar_t *>(uniText.ptr), uLen);
2795 if (uniText) {
2796 uniText.SetClip(CF_UNICODETEXT);
2797 } else {
2798 // There was a failure - try to copy at least ANSI text
2799 GlobalMemory ansiText;
2800 ansiText.Allocate(selectedText.LengthWithTerminator());
2801 if (ansiText) {
2802 memcpy(static_cast<char *>(ansiText.ptr), selectedText.Data(), selectedText.LengthWithTerminator());
2803 ansiText.SetClip(CF_TEXT);
2807 if (selectedText.rectangular) {
2808 ::SetClipboardData(cfColumnSelect, 0);
2810 GlobalMemory borlandSelection;
2811 borlandSelection.Allocate(1);
2812 if (borlandSelection) {
2813 static_cast<BYTE *>(borlandSelection.ptr)[0] = 0x02;
2814 borlandSelection.SetClip(cfBorlandIDEBlockType);
2818 if (selectedText.lineCopy) {
2819 ::SetClipboardData(cfLineSelect, 0);
2820 ::SetClipboardData(cfVSLineTag, 0);
2823 ::CloseClipboard();
2826 void ScintillaWin::ScrollMessage(WPARAM wParam) {
2827 //DWORD dwStart = timeGetTime();
2828 //Platform::DebugPrintf("Scroll %x %d\n", wParam, lParam);
2830 SCROLLINFO sci = {};
2831 sci.cbSize = sizeof(sci);
2832 sci.fMask = SIF_ALL;
2834 GetScrollInfo(SB_VERT, &sci);
2836 //Platform::DebugPrintf("ScrollInfo %d mask=%x min=%d max=%d page=%d pos=%d track=%d\n", b,sci.fMask,
2837 //sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
2839 int topLineNew = topLine;
2840 switch (LoWord(wParam)) {
2841 case SB_LINEUP:
2842 topLineNew -= 1;
2843 break;
2844 case SB_LINEDOWN:
2845 topLineNew += 1;
2846 break;
2847 case SB_PAGEUP:
2848 topLineNew -= LinesToScroll(); break;
2849 case SB_PAGEDOWN: topLineNew += LinesToScroll(); break;
2850 case SB_TOP: topLineNew = 0; break;
2851 case SB_BOTTOM: topLineNew = MaxScrollPos(); break;
2852 case SB_THUMBPOSITION: topLineNew = sci.nTrackPos; break;
2853 case SB_THUMBTRACK: topLineNew = sci.nTrackPos; break;
2855 ScrollTo(topLineNew);
2858 void ScintillaWin::HorizontalScrollMessage(WPARAM wParam) {
2859 int xPos = xOffset;
2860 PRectangle rcText = GetTextRectangle();
2861 int pageWidth = static_cast<int>(rcText.Width() * 2 / 3);
2862 switch (LoWord(wParam)) {
2863 case SB_LINEUP:
2864 xPos -= 20;
2865 break;
2866 case SB_LINEDOWN: // May move past the logical end
2867 xPos += 20;
2868 break;
2869 case SB_PAGEUP:
2870 xPos -= pageWidth;
2871 break;
2872 case SB_PAGEDOWN:
2873 xPos += pageWidth;
2874 if (xPos > scrollWidth - rcText.Width()) { // Hit the end exactly
2875 xPos = scrollWidth - static_cast<int>(rcText.Width());
2877 break;
2878 case SB_TOP:
2879 xPos = 0;
2880 break;
2881 case SB_BOTTOM:
2882 xPos = scrollWidth;
2883 break;
2884 case SB_THUMBPOSITION:
2885 case SB_THUMBTRACK: {
2886 // 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 =]
2887 SCROLLINFO si;
2888 si.cbSize = sizeof(si);
2889 si.fMask = SIF_TRACKPOS;
2890 if (GetScrollInfo(SB_HORZ, &si)) {
2891 xPos = si.nTrackPos;
2894 break;
2896 HorizontalScrollTo(xPos);
2900 * Redraw all of text area.
2901 * This paint will not be abandoned.
2903 void ScintillaWin::FullPaint() {
2904 if ((technology == SC_TECHNOLOGY_DEFAULT) || (technology == SC_TECHNOLOGY_DIRECTWRITEDC)) {
2905 HDC hdc = ::GetDC(MainHWND());
2906 FullPaintDC(hdc);
2907 ::ReleaseDC(MainHWND(), hdc);
2908 } else {
2909 FullPaintDC(0);
2914 * Redraw all of text area on the specified DC.
2915 * This paint will not be abandoned.
2917 void ScintillaWin::FullPaintDC(HDC hdc) {
2918 paintState = painting;
2919 rcPaint = GetClientRectangle();
2920 paintingAllText = true;
2921 if (technology == SC_TECHNOLOGY_DEFAULT) {
2922 AutoSurface surfaceWindow(hdc, this);
2923 if (surfaceWindow) {
2924 Paint(surfaceWindow, rcPaint);
2925 surfaceWindow->Release();
2927 } else {
2928 #if defined(USE_D2D)
2929 EnsureRenderTarget(hdc);
2930 AutoSurface surfaceWindow(pRenderTarget, this);
2931 if (surfaceWindow) {
2932 pRenderTarget->BeginDraw();
2933 Paint(surfaceWindow, rcPaint);
2934 surfaceWindow->Release();
2935 HRESULT hr = pRenderTarget->EndDraw();
2936 if (hr == D2DERR_RECREATE_TARGET) {
2937 DropRenderTarget();
2940 #endif
2942 paintState = notPainting;
2945 static bool CompareDevCap(HDC hdc, HDC hOtherDC, int nIndex) {
2946 return ::GetDeviceCaps(hdc, nIndex) == ::GetDeviceCaps(hOtherDC, nIndex);
2949 bool ScintillaWin::IsCompatibleDC(HDC hOtherDC) {
2950 HDC hdc = ::GetDC(MainHWND());
2951 bool isCompatible =
2952 CompareDevCap(hdc, hOtherDC, TECHNOLOGY) &&
2953 CompareDevCap(hdc, hOtherDC, LOGPIXELSY) &&
2954 CompareDevCap(hdc, hOtherDC, LOGPIXELSX) &&
2955 CompareDevCap(hdc, hOtherDC, BITSPIXEL) &&
2956 CompareDevCap(hdc, hOtherDC, PLANES);
2957 ::ReleaseDC(MainHWND(), hdc);
2958 return isCompatible;
2961 DWORD ScintillaWin::EffectFromState(DWORD grfKeyState) const {
2962 // These are the Wordpad semantics.
2963 DWORD dwEffect;
2964 if (inDragDrop == ddDragging) // Internal defaults to move
2965 dwEffect = DROPEFFECT_MOVE;
2966 else
2967 dwEffect = DROPEFFECT_COPY;
2968 if (grfKeyState & MK_ALT)
2969 dwEffect = DROPEFFECT_MOVE;
2970 if (grfKeyState & MK_CONTROL)
2971 dwEffect = DROPEFFECT_COPY;
2972 return dwEffect;
2975 /// Implement IUnknown
2976 STDMETHODIMP ScintillaWin::QueryInterface(REFIID riid, PVOID *ppv) {
2977 *ppv = NULL;
2978 if (riid == IID_IUnknown)
2979 *ppv = reinterpret_cast<IDropTarget *>(&dt);
2980 if (riid == IID_IDropSource)
2981 *ppv = reinterpret_cast<IDropSource *>(&ds);
2982 if (riid == IID_IDropTarget)
2983 *ppv = reinterpret_cast<IDropTarget *>(&dt);
2984 if (riid == IID_IDataObject)
2985 *ppv = reinterpret_cast<IDataObject *>(&dob);
2986 if (!*ppv)
2987 return E_NOINTERFACE;
2988 return S_OK;
2991 STDMETHODIMP_(ULONG) ScintillaWin::AddRef() {
2992 return 1;
2995 STDMETHODIMP_(ULONG) ScintillaWin::Release() {
2996 return 1;
2999 /// Implement IDropTarget
3000 STDMETHODIMP ScintillaWin::DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
3001 POINTL, PDWORD pdwEffect) {
3002 if (pIDataSource == NULL)
3003 return E_POINTER;
3004 FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
3005 HRESULT hrHasUText = pIDataSource->QueryGetData(&fmtu);
3006 hasOKText = (hrHasUText == S_OK);
3007 if (!hasOKText) {
3008 FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
3009 HRESULT hrHasText = pIDataSource->QueryGetData(&fmte);
3010 hasOKText = (hrHasText == S_OK);
3012 if (!hasOKText) {
3013 *pdwEffect = DROPEFFECT_NONE;
3014 return S_OK;
3017 *pdwEffect = EffectFromState(grfKeyState);
3018 return S_OK;
3021 STDMETHODIMP ScintillaWin::DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
3022 try {
3023 if (!hasOKText || pdoc->IsReadOnly()) {
3024 *pdwEffect = DROPEFFECT_NONE;
3025 return S_OK;
3028 *pdwEffect = EffectFromState(grfKeyState);
3030 // Update the cursor.
3031 POINT rpt = {pt.x, pt.y};
3032 ::ScreenToClient(MainHWND(), &rpt);
3033 SetDragPosition(SPositionFromLocation(PointFromPOINT(rpt), false, false, UserVirtualSpace()));
3035 return S_OK;
3036 } catch (...) {
3037 errorStatus = SC_STATUS_FAILURE;
3039 return E_FAIL;
3042 STDMETHODIMP ScintillaWin::DragLeave() {
3043 try {
3044 SetDragPosition(SelectionPosition(invalidPosition));
3045 return S_OK;
3046 } catch (...) {
3047 errorStatus = SC_STATUS_FAILURE;
3049 return E_FAIL;
3052 STDMETHODIMP ScintillaWin::Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
3053 POINTL pt, PDWORD pdwEffect) {
3054 try {
3055 *pdwEffect = EffectFromState(grfKeyState);
3057 if (pIDataSource == NULL)
3058 return E_POINTER;
3060 SetDragPosition(SelectionPosition(invalidPosition));
3062 STGMEDIUM medium = {0, {0}, 0};
3064 std::vector<char> data; // Includes terminating NUL
3066 FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
3067 HRESULT hr = pIDataSource->GetData(&fmtu, &medium);
3068 if (SUCCEEDED(hr) && medium.hGlobal) {
3069 GlobalMemory memUDrop(medium.hGlobal);
3070 wchar_t *udata = static_cast<wchar_t *>(memUDrop.ptr);
3071 if (udata) {
3072 if (IsUnicodeMode()) {
3073 int tlen = static_cast<int>(memUDrop.Size());
3074 // Convert UTF-16 to UTF-8
3075 int dataLen = UTF8Length(udata, tlen/2);
3076 data.resize(dataLen+1);
3077 UTF8FromUTF16(udata, tlen/2, &data[0], dataLen);
3078 } else {
3079 // Convert UTF-16 to ANSI
3081 // Default Scintilla behavior in Unicode mode
3082 // CF_UNICODETEXT available, but not in Unicode mode
3083 // Convert from Unicode to current Scintilla code page
3084 UINT cpDest = CodePageOfDocument();
3085 int tlen = ::WideCharToMultiByte(cpDest, 0, udata, -1,
3086 NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
3087 data.resize(tlen + 1);
3088 ::WideCharToMultiByte(cpDest, 0, udata, -1,
3089 &data[0], tlen + 1, NULL, NULL);
3092 memUDrop.Unlock();
3093 } else {
3094 FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
3095 hr = pIDataSource->GetData(&fmte, &medium);
3096 if (SUCCEEDED(hr) && medium.hGlobal) {
3097 GlobalMemory memDrop(medium.hGlobal);
3098 const char *cdata = static_cast<char *>(memDrop.ptr);
3099 if (cdata)
3100 data.assign(cdata, cdata+strlen(cdata)+1);
3101 memDrop.Unlock();
3105 if (!SUCCEEDED(hr) || data.empty()) {
3106 //Platform::DebugPrintf("Bad data format: 0x%x\n", hres);
3107 return hr;
3110 FORMATETC fmtr = {cfColumnSelect, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
3111 HRESULT hrRectangular = pIDataSource->QueryGetData(&fmtr);
3113 POINT rpt = {pt.x, pt.y};
3114 ::ScreenToClient(MainHWND(), &rpt);
3115 SelectionPosition movePos = SPositionFromLocation(PointFromPOINT(rpt), false, false, UserVirtualSpace());
3117 DropAt(movePos, &data[0], data.size() - 1, *pdwEffect == DROPEFFECT_MOVE, hrRectangular == S_OK);
3119 // Free data
3120 if (medium.pUnkForRelease != NULL)
3121 medium.pUnkForRelease->Release();
3122 else
3123 ::GlobalFree(medium.hGlobal);
3125 return S_OK;
3126 } catch (...) {
3127 errorStatus = SC_STATUS_FAILURE;
3129 return E_FAIL;
3132 /// Implement important part of IDataObject
3133 STDMETHODIMP ScintillaWin::GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM) {
3134 bool formatOK = (pFEIn->cfFormat == CF_TEXT) ||
3135 ((pFEIn->cfFormat == CF_UNICODETEXT) && IsUnicodeMode());
3136 if (!formatOK ||
3137 pFEIn->ptd != 0 ||
3138 (pFEIn->dwAspect & DVASPECT_CONTENT) == 0 ||
3139 pFEIn->lindex != -1 ||
3140 (pFEIn->tymed & TYMED_HGLOBAL) == 0
3142 //Platform::DebugPrintf("DOB GetData No %d %x %x fmt=%x\n", lenDrag, pFEIn, pSTM, pFEIn->cfFormat);
3143 return DATA_E_FORMATETC;
3145 pSTM->tymed = TYMED_HGLOBAL;
3146 //Platform::DebugPrintf("DOB GetData OK %d %x %x\n", lenDrag, pFEIn, pSTM);
3148 GlobalMemory text;
3149 if (pFEIn->cfFormat == CF_UNICODETEXT) {
3150 size_t uchars = UTF16Length(drag.Data(), static_cast<int>(drag.LengthWithTerminator()));
3151 text.Allocate(2 * uchars);
3152 if (text) {
3153 UTF16FromUTF8(drag.Data(), drag.LengthWithTerminator(),
3154 static_cast<wchar_t *>(text.ptr), uchars);
3156 } else {
3157 text.Allocate(drag.LengthWithTerminator());
3158 if (text) {
3159 memcpy(static_cast<char *>(text.ptr), drag.Data(), drag.LengthWithTerminator());
3162 pSTM->hGlobal = text ? text.Unlock() : 0;
3163 pSTM->pUnkForRelease = 0;
3164 return S_OK;
3167 bool ScintillaWin::Register(HINSTANCE hInstance_) {
3169 hInstance = hInstance_;
3170 bool result;
3172 // Register the Scintilla class
3173 // Register Scintilla as a wide character window
3174 WNDCLASSEXW wndclass;
3175 wndclass.cbSize = sizeof(wndclass);
3176 wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
3177 wndclass.lpfnWndProc = ScintillaWin::SWndProc;
3178 wndclass.cbClsExtra = 0;
3179 wndclass.cbWndExtra = sizeof(ScintillaWin *);
3180 wndclass.hInstance = hInstance;
3181 wndclass.hIcon = NULL;
3182 wndclass.hCursor = NULL;
3183 wndclass.hbrBackground = NULL;
3184 wndclass.lpszMenuName = NULL;
3185 wndclass.lpszClassName = L"Scintilla";
3186 wndclass.hIconSm = 0;
3187 scintillaClassAtom = ::RegisterClassExW(&wndclass);
3188 result = 0 != scintillaClassAtom;
3190 if (result) {
3191 // Register the CallTip class
3192 WNDCLASSEX wndclassc;
3193 wndclassc.cbSize = sizeof(wndclassc);
3194 wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
3195 wndclassc.cbClsExtra = 0;
3196 wndclassc.cbWndExtra = sizeof(ScintillaWin *);
3197 wndclassc.hInstance = hInstance;
3198 wndclassc.hIcon = NULL;
3199 wndclassc.hbrBackground = NULL;
3200 wndclassc.lpszMenuName = NULL;
3201 wndclassc.lpfnWndProc = ScintillaWin::CTWndProc;
3202 wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
3203 wndclassc.lpszClassName = callClassName;
3204 wndclassc.hIconSm = 0;
3206 callClassAtom = ::RegisterClassEx(&wndclassc);
3207 result = 0 != callClassAtom;
3210 return result;
3213 bool ScintillaWin::Unregister() {
3214 bool result = true;
3215 if (0 != scintillaClassAtom) {
3216 if (::UnregisterClass(MAKEINTATOM(scintillaClassAtom), hInstance) == 0) {
3217 result = false;
3219 scintillaClassAtom = 0;
3221 if (0 != callClassAtom) {
3222 if (::UnregisterClass(MAKEINTATOM(callClassAtom), hInstance) == 0) {
3223 result = false;
3225 callClassAtom = 0;
3227 return result;
3230 bool ScintillaWin::HasCaretSizeChanged() const {
3231 if (
3232 ( (0 != vs.caretWidth) && (sysCaretWidth != vs.caretWidth) )
3233 || ((0 != vs.lineHeight) && (sysCaretHeight != vs.lineHeight))
3235 return true;
3237 return false;
3240 BOOL ScintillaWin::CreateSystemCaret() {
3241 sysCaretWidth = vs.caretWidth;
3242 if (0 == sysCaretWidth) {
3243 sysCaretWidth = 1;
3245 sysCaretHeight = vs.lineHeight;
3246 int bitmapSize = (((sysCaretWidth + 15) & ~15) >> 3) *
3247 sysCaretHeight;
3248 std::vector<char> bits(bitmapSize);
3249 sysCaretBitmap = ::CreateBitmap(sysCaretWidth, sysCaretHeight, 1,
3250 1, reinterpret_cast<BYTE *>(&bits[0]));
3251 BOOL retval = ::CreateCaret(
3252 MainHWND(), sysCaretBitmap,
3253 sysCaretWidth, sysCaretHeight);
3254 if (technology == SC_TECHNOLOGY_DEFAULT) {
3255 // System caret interferes with Direct2D drawing so only show it for GDI.
3256 ::ShowCaret(MainHWND());
3258 return retval;
3261 BOOL ScintillaWin::DestroySystemCaret() {
3262 ::HideCaret(MainHWND());
3263 BOOL retval = ::DestroyCaret();
3264 if (sysCaretBitmap) {
3265 ::DeleteObject(sysCaretBitmap);
3266 sysCaretBitmap = 0;
3268 return retval;
3271 LRESULT PASCAL ScintillaWin::CTWndProc(
3272 HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
3273 // Find C++ object associated with window.
3274 ScintillaWin *sciThis = static_cast<ScintillaWin *>(PointerFromWindow(hWnd));
3275 try {
3276 // ctp will be zero if WM_CREATE not seen yet
3277 if (sciThis == 0) {
3278 if (iMessage == WM_CREATE) {
3279 // Associate CallTip object with window
3280 CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
3281 SetWindowPointer(hWnd, pCreate->lpCreateParams);
3282 return 0;
3283 } else {
3284 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3286 } else {
3287 if (iMessage == WM_NCDESTROY) {
3288 ::SetWindowLong(hWnd, 0, 0);
3289 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3290 } else if (iMessage == WM_PAINT) {
3291 PAINTSTRUCT ps;
3292 ::BeginPaint(hWnd, &ps);
3293 Surface *surfaceWindow = Surface::Allocate(sciThis->technology);
3294 if (surfaceWindow) {
3295 #if defined(USE_D2D)
3296 ID2D1HwndRenderTarget *pCTRenderTarget = 0;
3297 #endif
3298 RECT rc;
3299 GetClientRect(hWnd, &rc);
3300 // Create a Direct2D render target.
3301 if (sciThis->technology == SC_TECHNOLOGY_DEFAULT) {
3302 surfaceWindow->Init(ps.hdc, hWnd);
3303 } else {
3304 #if defined(USE_D2D)
3305 D2D1_HWND_RENDER_TARGET_PROPERTIES dhrtp;
3306 dhrtp.hwnd = hWnd;
3307 dhrtp.pixelSize = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
3308 dhrtp.presentOptions = (sciThis->technology == SC_TECHNOLOGY_DIRECTWRITERETAIN) ?
3309 D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS : D2D1_PRESENT_OPTIONS_NONE;
3311 D2D1_RENDER_TARGET_PROPERTIES drtp;
3312 drtp.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
3313 drtp.pixelFormat.format = DXGI_FORMAT_UNKNOWN;
3314 drtp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_UNKNOWN;
3315 drtp.dpiX = 96.0;
3316 drtp.dpiY = 96.0;
3317 drtp.usage = D2D1_RENDER_TARGET_USAGE_NONE;
3318 drtp.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
3320 if (!SUCCEEDED(pD2DFactory->CreateHwndRenderTarget(drtp, dhrtp, &pCTRenderTarget))) {
3321 surfaceWindow->Release();
3322 delete surfaceWindow;
3323 ::EndPaint(hWnd, &ps);
3324 return 0;
3326 surfaceWindow->Init(pCTRenderTarget, hWnd);
3327 pCTRenderTarget->BeginDraw();
3328 #endif
3330 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == sciThis->ct.codePage);
3331 surfaceWindow->SetDBCSMode(sciThis->ct.codePage);
3332 sciThis->ct.PaintCT(surfaceWindow);
3333 #if defined(USE_D2D)
3334 if (pCTRenderTarget)
3335 pCTRenderTarget->EndDraw();
3336 #endif
3337 surfaceWindow->Release();
3338 delete surfaceWindow;
3339 #if defined(USE_D2D)
3340 if (pCTRenderTarget)
3341 pCTRenderTarget->Release();
3342 #endif
3344 ::EndPaint(hWnd, &ps);
3345 return 0;
3346 } else if ((iMessage == WM_NCLBUTTONDOWN) || (iMessage == WM_NCLBUTTONDBLCLK)) {
3347 POINT pt;
3348 pt.x = static_cast<short>(LOWORD(lParam));
3349 pt.y = static_cast<short>(HIWORD(lParam));
3350 ScreenToClient(hWnd, &pt);
3351 sciThis->ct.MouseClick(PointFromPOINT(pt));
3352 sciThis->CallTipClick();
3353 return 0;
3354 } else if (iMessage == WM_LBUTTONDOWN) {
3355 // This does not fire due to the hit test code
3356 sciThis->ct.MouseClick(Point::FromLong(static_cast<long>(lParam)));
3357 sciThis->CallTipClick();
3358 return 0;
3359 } else if (iMessage == WM_SETCURSOR) {
3360 ::SetCursor(::LoadCursor(NULL, IDC_ARROW));
3361 return 0;
3362 } else if (iMessage == WM_NCHITTEST) {
3363 return HTCAPTION;
3364 } else {
3365 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3368 } catch (...) {
3369 sciThis->errorStatus = SC_STATUS_FAILURE;
3371 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3374 sptr_t ScintillaWin::DirectFunction(
3375 sptr_t ptr, UINT iMessage, uptr_t wParam, sptr_t lParam) {
3376 PLATFORM_ASSERT(::GetCurrentThreadId() == ::GetWindowThreadProcessId(reinterpret_cast<ScintillaWin *>(ptr)->MainHWND(), NULL));
3377 return reinterpret_cast<ScintillaWin *>(ptr)->WndProc(iMessage, wParam, lParam);
3380 extern "C"
3381 #ifndef STATIC_BUILD
3382 __declspec(dllexport)
3383 #endif
3384 sptr_t __stdcall Scintilla_DirectFunction(
3385 ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
3386 return sci->WndProc(iMessage, wParam, lParam);
3389 LRESULT PASCAL ScintillaWin::SWndProc(
3390 HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
3391 //Platform::DebugPrintf("S W:%x M:%x WP:%x L:%x\n", hWnd, iMessage, wParam, lParam);
3393 // Find C++ object associated with window.
3394 ScintillaWin *sci = static_cast<ScintillaWin *>(PointerFromWindow(hWnd));
3395 // sci will be zero if WM_CREATE not seen yet
3396 if (sci == 0) {
3397 try {
3398 if (iMessage == WM_CREATE) {
3399 // Create C++ object associated with window
3400 sci = new ScintillaWin(hWnd);
3401 SetWindowPointer(hWnd, sci);
3402 return sci->WndProc(iMessage, wParam, lParam);
3404 } catch (...) {
3406 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3407 } else {
3408 if (iMessage == WM_NCDESTROY) {
3409 try {
3410 sci->Finalise();
3411 delete sci;
3412 } catch (...) {
3414 ::SetWindowLong(hWnd, 0, 0);
3415 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
3416 } else {
3417 return sci->WndProc(iMessage, wParam, lParam);
3422 // This function is externally visible so it can be called from container when building statically.
3423 // Must be called once only.
3424 int Scintilla_RegisterClasses(void *hInstance) {
3425 Platform_Initialise(hInstance);
3426 bool result = ScintillaWin::Register(static_cast<HINSTANCE>(hInstance));
3427 #ifdef SCI_LEXER
3428 Scintilla_LinkLexers();
3429 #endif
3430 return result;
3433 static int ResourcesRelease(bool fromDllMain) {
3434 bool result = ScintillaWin::Unregister();
3435 if (commctrl32) {
3436 FreeLibrary(commctrl32);
3437 commctrl32 = NULL;
3439 Platform_Finalise(fromDllMain);
3440 return result;
3443 // This function is externally visible so it can be called from container when building statically.
3444 int Scintilla_ReleaseResources() {
3445 return ResourcesRelease(false);
3448 #ifndef STATIC_BUILD
3449 extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved) {
3450 //Platform::DebugPrintf("Scintilla::DllMain %d %d\n", hInstance, dwReason);
3451 if (dwReason == DLL_PROCESS_ATTACH) {
3452 if (!Scintilla_RegisterClasses(hInstance))
3453 return FALSE;
3454 } else if (dwReason == DLL_PROCESS_DETACH) {
3455 if (lpvReserved == NULL) {
3456 ResourcesRelease(true);
3459 return TRUE;
3461 #endif