ScintillaGTK.cxx 96.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Scintilla source code edit control
// ScintillaGTK.cxx - GTK+ specific subclass of ScintillaBase
// Copyright 1998-2004 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cmath>

#include <stdexcept>
#include <new>
#include <string>
17
#include <string_view>
18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <vector>
#include <map>
#include <algorithm>
#include <memory>

#include <glib.h>
#include <gmodule.h>
#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#if defined(GDK_WINDOWING_WAYLAND)
#include <gdk/gdkwayland.h>
#endif

32 33 34 35
#if defined(_WIN32)
// On Win32 use windows.h to access clipboard (rectangular format) and systems parameters
#undef NOMINMAX
#define NOMINMAX
36 37 38 39 40
#include <windows.h>
#endif

#include "Platform.h"

41
#include "ILoader.h"
42 43 44 45 46 47 48
#include "ILexer.h"
#include "Scintilla.h"
#include "ScintillaWidget.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#endif
#include "StringCopy.h"
49
#include "CharacterCategory.h"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#ifdef SCI_LEXER
#include "LexerModule.h"
#endif
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "CaseConvert.h"
#include "UniConversion.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "Editor.h"
#include "AutoComplete.h"
#include "ScintillaBase.h"

#ifdef SCI_LEXER
#include "ExternalLexer.h"
#endif

#include "ScintillaGTK.h"
#include "scintilla-marshal.h"
#include "ScintillaGTKAccessible.h"

#include "Converter.h"

#define IS_WIDGET_REALIZED(w) (gtk_widget_get_realized(GTK_WIDGET(w)))
#define IS_WIDGET_MAPPED(w) (gtk_widget_get_mapped(GTK_WIDGET(w)))

94 95 96 97
#define SC_INDICATOR_INPUT INDICATOR_IME
#define SC_INDICATOR_TARGET INDICATOR_IME+1
#define SC_INDICATOR_CONVERTED INDICATOR_IME+2
#define SC_INDICATOR_UNKNOWN INDICATOR_IME_MAX
98

99
static GdkWindow *WindowFromWidget(GtkWidget *w) noexcept {
100 101 102 103 104 105 106 107 108 109 110 111
	return gtk_widget_get_window(w);
}

#ifdef _MSC_VER
// Constant conditional expressions are because of GTK+ headers
#pragma warning(disable: 4127)
// Ignore unreferenced local functions in GTK+ headers
#pragma warning(disable: 4505)
#endif

using namespace Scintilla;

112
static GdkWindow *PWindow(const Window &w) noexcept {
113 114 115 116
	GtkWidget *widget = static_cast<GtkWidget *>(w.GetID());
	return gtk_widget_get_window(widget);
}

117
extern std::string UTF8FromLatin1(std::string_view text);
118 119

enum {
120 121 122
	COMMAND_SIGNAL,
	NOTIFY_SIGNAL,
	LAST_SIGNAL
123 124 125 126 127
};

static gint scintilla_signals[LAST_SIGNAL] = { 0 };

enum {
128 129 130 131 132
	TARGET_STRING,
	TARGET_TEXT,
	TARGET_COMPOUND_TEXT,
	TARGET_UTF8_STRING,
	TARGET_URI
133 134
};

135 136 137 138
GdkAtom ScintillaGTK::atomUTF8 = nullptr;
GdkAtom ScintillaGTK::atomString = nullptr;
GdkAtom ScintillaGTK::atomUriList = nullptr;
GdkAtom ScintillaGTK::atomDROPFILES_DND = nullptr;
139 140 141 142 143 144 145 146 147 148 149 150 151 152

static const GtkTargetEntry clipboardCopyTargets[] = {
	{ (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
	{ (gchar *) "STRING", 0, TARGET_STRING },
};
static const gint nClipboardCopyTargets = ELEMENTS(clipboardCopyTargets);

static const GtkTargetEntry clipboardPasteTargets[] = {
	{ (gchar *) "text/uri-list", 0, TARGET_URI },
	{ (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
	{ (gchar *) "STRING", 0, TARGET_STRING },
};
static const gint nClipboardPasteTargets = ELEMENTS(clipboardPasteTargets);

153 154
static const GdkDragAction actionCopyOrMove = static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE);

155
static GtkWidget *PWidget(const Window &w) noexcept {
156 157 158 159 160 161 162 163 164
	return static_cast<GtkWidget *>(w.GetID());
}

ScintillaGTK *ScintillaGTK::FromWidget(GtkWidget *widget) {
	ScintillaObject *scio = SCINTILLA(widget);
	return static_cast<ScintillaGTK *>(scio->pscin);
}

ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) :
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
	adjustmentv(nullptr), adjustmenth(nullptr),
	verticalScrollBarWidth(30), horizontalScrollBarHeight(30),
	evbtn(nullptr),
	buttonMouse(0),
	capturedMouse(false), dragWasDropped(false),
	lastKey(0), rectangularSelectionModifier(SCMOD_CTRL),
	parentClass(nullptr),
	atomSought(nullptr),
	im_context(nullptr),
	lastNonCommonScript(PANGO_SCRIPT_INVALID_CODE),
	lastWheelMouseDirection(0),
	wheelMouseIntensity(0),
	smoothScrollY(0),
	smoothScrollX(0),
	rgnUpdate(nullptr),
	repaintFullWindow(false),
	styleIdleID(0),
	accessibilityEnabled(SC_ACCESSIBILITY_ENABLED),
	accessible(nullptr) {
184 185 186 187 188 189 190 191 192
	sci = sci_;
	wMain = GTK_WIDGET(sci);

	rectangularSelectionModifier = SCMOD_ALT;

#if PLAT_GTK_WIN32
	// There does not seem to be a real standard for indicating that the clipboard
	// contains a rectangular selection, so copy Developer Studio.
	cfColumnSelect = static_cast<CLIPFORMAT>(
193
				 ::RegisterClipboardFormat("MSDEVColumnSelect"));
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

	// Get intellimouse parameters when running on win32; otherwise use
	// reasonable default
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES   104
#endif
	::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
#else
	linesPerScroll = 4;
#endif
	lastWheelMouseTime.tv_sec = 0;
	lastWheelMouseTime.tv_usec = 0;

	Init();
}

ScintillaGTK::~ScintillaGTK() {
	if (styleIdleID) {
		g_source_remove(styleIdleID);
		styleIdleID = 0;
	}
	if (evbtn) {
216 217
		gdk_event_free(evbtn);
		evbtn = nullptr;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	}
	wPreedit.Destroy();
}

static void UnRefCursor(GdkCursor *cursor) {
#if GTK_CHECK_VERSION(3,0,0)
	g_object_unref(cursor);
#else
	gdk_cursor_unref(cursor);
#endif
}

void ScintillaGTK::RealizeThis(GtkWidget *widget) {
	//Platform::DebugPrintf("ScintillaGTK::realize this\n");
	gtk_widget_set_realized(widget, TRUE);
	GdkWindowAttr attrs;
	attrs.window_type = GDK_WINDOW_CHILD;
	GtkAllocation allocation;
	gtk_widget_get_allocation(widget, &allocation);
	attrs.x = allocation.x;
	attrs.y = allocation.y;
	attrs.width = allocation.width;
	attrs.height = allocation.height;
	attrs.wclass = GDK_INPUT_OUTPUT;
	attrs.visual = gtk_widget_get_visual(widget);
#if !GTK_CHECK_VERSION(3,0,0)
	attrs.colormap = gtk_widget_get_colormap(widget);
#endif
	attrs.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
	GdkDisplay *pdisplay = gtk_widget_get_display(widget);
	GdkCursor *cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
	attrs.cursor = cursor;
#if GTK_CHECK_VERSION(3,0,0)
	gtk_widget_set_window(widget, gdk_window_new(gtk_widget_get_parent_window(widget), &attrs,
252
			      GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_CURSOR));
253 254 255 256 257 258 259
#if GTK_CHECK_VERSION(3,8,0)
	gtk_widget_register_window(widget, gtk_widget_get_window(widget));
#else
	gdk_window_set_user_data(gtk_widget_get_window(widget), widget);
#endif
#if !GTK_CHECK_VERSION(3,18,0)
	gtk_style_context_set_background(gtk_widget_get_style_context(widget),
260
					 gtk_widget_get_window(widget));
261 262 263 264 265
#endif
	gdk_window_show(gtk_widget_get_window(widget));
	UnRefCursor(cursor);
#else
	widget->window = gdk_window_new(gtk_widget_get_parent_window(widget), &attrs,
266
					GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP | GDK_WA_CURSOR);
267 268 269 270 271 272 273 274 275 276 277
	gdk_window_set_user_data(widget->window, widget);
	widget->style = gtk_style_attach(widget->style, widget->window);
	gdk_window_set_background(widget->window, &widget->style->bg[GTK_STATE_NORMAL]);
	gdk_window_show(widget->window);
	UnRefCursor(cursor);
#endif
	gtk_widget_realize(PWidget(wPreedit));
	gtk_widget_realize(PWidget(wPreeditDraw));

	im_context = gtk_im_multicontext_new();
	g_signal_connect(G_OBJECT(im_context), "commit",
278
			 G_CALLBACK(Commit), this);
279
	g_signal_connect(G_OBJECT(im_context), "preedit_changed",
280
			 G_CALLBACK(PreeditChanged), this);
281 282 283
	gtk_im_context_set_client_window(im_context, WindowFromWidget(widget));
	GtkWidget *widtxt = PWidget(wText);	//	// No code inside the G_OBJECT macro
	g_signal_connect_after(G_OBJECT(widtxt), "style_set",
284
			       G_CALLBACK(ScintillaGTK::StyleSetText), nullptr);
285
	g_signal_connect_after(G_OBJECT(widtxt), "realize",
286
			       G_CALLBACK(ScintillaGTK::RealizeText), nullptr);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	gtk_widget_realize(widtxt);
	gtk_widget_realize(PWidget(scrollbarv));
	gtk_widget_realize(PWidget(scrollbarh));

	cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
	gdk_window_set_cursor(PWindow(wText), cursor);
	UnRefCursor(cursor);

	cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
	gdk_window_set_cursor(PWindow(scrollbarv), cursor);
	UnRefCursor(cursor);

	cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
	gdk_window_set_cursor(PWindow(scrollbarh), cursor);
	UnRefCursor(cursor);

303
	wSelection = gtk_invisible_new();
304 305 306
	g_signal_connect(PWidget(wSelection), "selection_get", G_CALLBACK(PrimarySelection), (gpointer) this);
	g_signal_connect(PWidget(wSelection), "selection_clear_event", G_CALLBACK(PrimaryClear), (gpointer) this);
	gtk_selection_add_targets(PWidget(wSelection), GDK_SELECTION_PRIMARY,
307
				  clipboardCopyTargets, nClipboardCopyTargets);
308 309 310 311 312 313 314 315 316 317
}

void ScintillaGTK::Realize(GtkWidget *widget) {
	ScintillaGTK *sciThis = FromWidget(widget);
	sciThis->RealizeThis(widget);
}

void ScintillaGTK::UnRealizeThis(GtkWidget *widget) {
	try {
		gtk_selection_clear_targets(PWidget(wSelection), GDK_SELECTION_PRIMARY);
318
		wSelection.Destroy();
319 320 321 322 323 324 325 326 327 328 329 330 331

		if (IS_WIDGET_MAPPED(widget)) {
			gtk_widget_unmap(widget);
		}
		gtk_widget_set_realized(widget, FALSE);
		gtk_widget_unrealize(PWidget(wText));
		if (PWidget(scrollbarv))
			gtk_widget_unrealize(PWidget(scrollbarv));
		if (PWidget(scrollbarh))
			gtk_widget_unrealize(PWidget(scrollbarh));
		gtk_widget_unrealize(PWidget(wPreedit));
		gtk_widget_unrealize(PWidget(wPreeditDraw));
		g_object_unref(im_context);
332
		im_context = nullptr;
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
		if (GTK_WIDGET_CLASS(parentClass)->unrealize)
			GTK_WIDGET_CLASS(parentClass)->unrealize(widget);

		Finalise();
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::UnRealize(GtkWidget *widget) {
	ScintillaGTK *sciThis = FromWidget(widget);
	sciThis->UnRealizeThis(widget);
}

static void MapWidget(GtkWidget *widget) {
	if (widget &&
349 350
			gtk_widget_get_visible(GTK_WIDGET(widget)) &&
			!IS_WIDGET_MAPPED(widget)) {
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
		gtk_widget_map(widget);
	}
}

void ScintillaGTK::MapThis() {
	try {
		//Platform::DebugPrintf("ScintillaGTK::map this\n");
		gtk_widget_set_mapped(PWidget(wMain), TRUE);
		MapWidget(PWidget(wText));
		MapWidget(PWidget(scrollbarh));
		MapWidget(PWidget(scrollbarv));
		wMain.SetCursor(Window::cursorArrow);
		scrollbarv.SetCursor(Window::cursorArrow);
		scrollbarh.SetCursor(Window::cursorArrow);
		ChangeSize();
		gdk_window_show(PWindow(wMain));
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::Map(GtkWidget *widget) {
	ScintillaGTK *sciThis = FromWidget(widget);
	sciThis->MapThis();
}

void ScintillaGTK::UnMapThis() {
	try {
		//Platform::DebugPrintf("ScintillaGTK::unmap this\n");
		gtk_widget_set_mapped(PWidget(wMain), FALSE);
		DropGraphics(false);
		gdk_window_hide(PWindow(wMain));
		gtk_widget_unmap(PWidget(wText));
		if (PWidget(scrollbarh))
			gtk_widget_unmap(PWidget(scrollbarh));
		if (PWidget(scrollbarv))
			gtk_widget_unmap(PWidget(scrollbarv));
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::UnMap(GtkWidget *widget) {
	ScintillaGTK *sciThis = FromWidget(widget);
	sciThis->UnMapThis();
}

void ScintillaGTK::ForAll(GtkCallback callback, gpointer callback_data) {
	try {
400
		(*callback)(PWidget(wText), callback_data);
401
		if (PWidget(scrollbarv))
402
			(*callback)(PWidget(scrollbarv), callback_data);
403
		if (PWidget(scrollbarh))
404
			(*callback)(PWidget(scrollbarh), callback_data);
405 406 407 408 409 410 411 412
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data) {
	ScintillaGTK *sciThis = FromWidget((GtkWidget *)container);

413
	if (callback && include_internals) {
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
		sciThis->ForAll(callback, callback_data);
	}
}

namespace {

class PreEditString {
public:
	gchar *str;
	gint cursor_pos;
	PangoAttrList *attrs;
	gboolean validUTF8;
	glong uniStrLen;
	gunichar *uniStr;
	PangoScript pscript;

	explicit PreEditString(GtkIMContext *im_context) {
		gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
432
		validUTF8 = g_utf8_validate(str, strlen(str), nullptr);
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
		uniStr = g_utf8_to_ucs4_fast(str, strlen(str), &uniStrLen);
		pscript = pango_script_for_unichar(uniStr[0]);
	}
	~PreEditString() {
		g_free(str);
		g_free(uniStr);
		pango_attr_list_unref(attrs);
	}
};

}

gint ScintillaGTK::FocusInThis(GtkWidget *) {
	try {
		SetFocusState(true);
448
		if (im_context) {
449
			PreEditString pes(im_context);
450
			if (PWidget(wPreedit)) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
				if (strlen(pes.str) > 0) {
					gtk_widget_show(PWidget(wPreedit));
				} else {
					gtk_widget_hide(PWidget(wPreedit));
				}
			}
			gtk_im_context_focus_in(im_context);
		}

	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
	return FALSE;
}

gint ScintillaGTK::FocusIn(GtkWidget *widget, GdkEventFocus * /*event*/) {
	ScintillaGTK *sciThis = FromWidget(widget);
	return sciThis->FocusInThis(widget);
}

gint ScintillaGTK::FocusOutThis(GtkWidget *) {
	try {
		SetFocusState(false);

475
		if (PWidget(wPreedit))
476
			gtk_widget_hide(PWidget(wPreedit));
477
		if (im_context)
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
			gtk_im_context_focus_out(im_context);

	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
	return FALSE;
}

gint ScintillaGTK::FocusOut(GtkWidget *widget, GdkEventFocus * /*event*/) {
	ScintillaGTK *sciThis = FromWidget(widget);
	return sciThis->FocusOutThis(widget);
}

void ScintillaGTK::SizeRequest(GtkWidget *widget, GtkRequisition *requisition) {
	ScintillaGTK *sciThis = FromWidget(widget);
	requisition->width = 1;
	requisition->height = 1;
	GtkRequisition child_requisition;
#if GTK_CHECK_VERSION(3,0,0)
497 498
	gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarh), nullptr, &child_requisition);
	gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarv), nullptr, &child_requisition);
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
#else
	gtk_widget_size_request(PWidget(sciThis->scrollbarh), &child_requisition);
	gtk_widget_size_request(PWidget(sciThis->scrollbarv), &child_requisition);
#endif
}

#if GTK_CHECK_VERSION(3,0,0)

void ScintillaGTK::GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth) {
	GtkRequisition requisition;
	SizeRequest(widget, &requisition);
	*minimalWidth = *naturalWidth = requisition.width;
}

void ScintillaGTK::GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight) {
	GtkRequisition requisition;
	SizeRequest(widget, &requisition);
	*minimalHeight = *naturalHeight = requisition.height;
}

#endif

void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) {
	ScintillaGTK *sciThis = FromWidget(widget);
	try {
		gtk_widget_set_allocation(widget, allocation);
		if (IS_WIDGET_REALIZED(widget))
			gdk_window_move_resize(WindowFromWidget(widget),
527 528 529 530
					       allocation->x,
					       allocation->y,
					       allocation->width,
					       allocation->height);
531 532 533 534 535 536 537 538 539 540

		sciThis->Resize(allocation->width, allocation->height);

	} catch (...) {
		sciThis->errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::Init() {
	parentClass = reinterpret_cast<GtkWidgetClass *>(
541
			      g_type_class_ref(gtk_container_get_type()));
542 543 544 545 546 547 548 549 550 551 552 553 554

	gint maskSmooth = 0;
#if defined(GDK_WINDOWING_WAYLAND)
	GdkDisplay *pdisplay = gdk_display_get_default();
	if (GDK_IS_WAYLAND_DISPLAY(pdisplay)) {
		// On Wayland, touch pads only produce smooth scroll events
		maskSmooth = GDK_SMOOTH_SCROLL_MASK;
	}
#endif

	gtk_widget_set_can_focus(PWidget(wMain), TRUE);
	gtk_widget_set_sensitive(PWidget(wMain), TRUE);
	gtk_widget_set_events(PWidget(wMain),
555 556 557 558 559 560 561 562 563 564 565 566
			      GDK_EXPOSURE_MASK
			      | GDK_SCROLL_MASK
			      | maskSmooth
			      | GDK_STRUCTURE_MASK
			      | GDK_KEY_PRESS_MASK
			      | GDK_KEY_RELEASE_MASK
			      | GDK_FOCUS_CHANGE_MASK
			      | GDK_LEAVE_NOTIFY_MASK
			      | GDK_BUTTON_PRESS_MASK
			      | GDK_BUTTON_RELEASE_MASK
			      | GDK_POINTER_MOTION_MASK
			      | GDK_POINTER_MOTION_HINT_MASK);
567 568 569 570 571 572 573

	wText = gtk_drawing_area_new();
	gtk_widget_set_parent(PWidget(wText), PWidget(wMain));
	GtkWidget *widtxt = PWidget(wText);	// No code inside the G_OBJECT macro
	gtk_widget_show(widtxt);
#if GTK_CHECK_VERSION(3,0,0)
	g_signal_connect(G_OBJECT(widtxt), "draw",
574
			 G_CALLBACK(ScintillaGTK::DrawText), this);
575 576
#else
	g_signal_connect(G_OBJECT(widtxt), "expose_event",
577
			 G_CALLBACK(ScintillaGTK::ExposeText), this);
578 579 580 581
#endif
#if GTK_CHECK_VERSION(3,0,0)
	// we need a runtime check because we don't want double buffering when
	// running on >= 3.9.2
582
	if (gtk_check_version(3, 9, 2) != nullptr /* on < 3.9.2 */)
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
#endif
	{
#if !GTK_CHECK_VERSION(3,14,0)
		// Avoid background drawing flash/missing redraws
		gtk_widget_set_double_buffered(widtxt, FALSE);
#endif
	}
	gtk_widget_set_events(widtxt, GDK_EXPOSURE_MASK);
	gtk_widget_set_size_request(widtxt, 100, 100);
	adjustmentv = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 201.0, 1.0, 20.0, 20.0));
#if GTK_CHECK_VERSION(3,0,0)
	scrollbarv = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT(adjustmentv));
#else
	scrollbarv = gtk_vscrollbar_new(GTK_ADJUSTMENT(adjustmentv));
#endif
	gtk_widget_set_can_focus(PWidget(scrollbarv), FALSE);
	g_signal_connect(G_OBJECT(adjustmentv), "value_changed",
600
			 G_CALLBACK(ScrollSignal), this);
601 602 603 604 605 606 607 608 609 610 611
	gtk_widget_set_parent(PWidget(scrollbarv), PWidget(wMain));
	gtk_widget_show(PWidget(scrollbarv));

	adjustmenth = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 101.0, 1.0, 20.0, 20.0));
#if GTK_CHECK_VERSION(3,0,0)
	scrollbarh = gtk_scrollbar_new(GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT(adjustmenth));
#else
	scrollbarh = gtk_hscrollbar_new(GTK_ADJUSTMENT(adjustmenth));
#endif
	gtk_widget_set_can_focus(PWidget(scrollbarh), FALSE);
	g_signal_connect(G_OBJECT(adjustmenth), "value_changed",
612
			 G_CALLBACK(ScrollHSignal), this);
613 614 615 616 617 618
	gtk_widget_set_parent(PWidget(scrollbarh), PWidget(wMain));
	gtk_widget_show(PWidget(scrollbarh));

	gtk_widget_grab_focus(PWidget(wMain));

	gtk_drag_dest_set(GTK_WIDGET(PWidget(wMain)),
619 620
			  GTK_DEST_DEFAULT_ALL, clipboardPasteTargets, nClipboardPasteTargets,
			  actionCopyOrMove);
621 622 623 624 625 626 627

	/* create pre-edit window */
	wPreedit = gtk_window_new(GTK_WINDOW_POPUP);
	wPreeditDraw = gtk_drawing_area_new();
	GtkWidget *predrw = PWidget(wPreeditDraw);      // No code inside the G_OBJECT macro
#if GTK_CHECK_VERSION(3,0,0)
	g_signal_connect(G_OBJECT(predrw), "draw",
628
			 G_CALLBACK(DrawPreedit), this);
629 630
#else
	g_signal_connect(G_OBJECT(predrw), "expose_event",
631
			 G_CALLBACK(ExposePreedit), this);
632 633 634 635 636 637 638 639 640
#endif
	gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw);
	gtk_widget_show(predrw);

	// Set caret period based on GTK settings
	gboolean blinkOn = false;
	if (g_object_class_find_property(G_OBJECT_GET_CLASS(
			G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink")) {
		g_object_get(G_OBJECT(
641
				     gtk_settings_get_default()), "gtk-cursor-blink", &blinkOn, nullptr);
642 643
	}
	if (blinkOn &&
644 645
			g_object_class_find_property(G_OBJECT_GET_CLASS(
						G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink-time")) {
646 647
		gint value;
		g_object_get(G_OBJECT(
648 649
				     gtk_settings_get_default()), "gtk-cursor-blink-time", &value, nullptr);
		caret.period = static_cast<int>(value / 1.75);
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
	} else {
		caret.period = 0;
	}

	for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
		timers[tr].reason = tr;
		timers[tr].scintilla = this;
	}
	vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
	vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
	vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
	vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
}

void ScintillaGTK::Finalise() {
	for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
		FineTickerCancel(tr);
	}
	if (accessible) {
669
		gtk_accessible_set_widget(GTK_ACCESSIBLE(accessible), nullptr);
670
		g_object_unref(accessible);
671
		accessible = nullptr;
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
	}

	ScintillaBase::Finalise();
}

bool ScintillaGTK::AbandonPaint() {
	if ((paintState == painting) && !paintingAllText) {
		repaintFullWindow = true;
	}
	return false;
}

void ScintillaGTK::DisplayCursor(Window::Cursor c) {
	if (cursorMode == SC_CURSORNORMAL)
		wText.SetCursor(c);
	else
		wText.SetCursor(static_cast<Window::Cursor>(cursorMode));
}

bool ScintillaGTK::DragThreshold(Point ptStart, Point ptNow) {
	return gtk_drag_check_threshold(GTK_WIDGET(PWidget(wMain)),
693
					ptStart.x, ptStart.y, ptNow.x, ptNow.y);
694 695 696
}

void ScintillaGTK::StartDrag() {
697
	PLATFORM_ASSERT(evbtn);
698 699 700 701 702
	dragWasDropped = false;
	inDragDrop = ddDragging;
	GtkTargetList *tl = gtk_target_list_new(clipboardCopyTargets, nClipboardCopyTargets);
#if GTK_CHECK_VERSION(3,10,0)
	gtk_drag_begin_with_coordinates(GTK_WIDGET(PWidget(wMain)),
703 704 705 706 707
					tl,
					actionCopyOrMove,
					buttonMouse,
					evbtn,
					-1, -1);
708 709
#else
	gtk_drag_begin(GTK_WIDGET(PWidget(wMain)),
710 711 712 713
		       tl,
		       actionCopyOrMove,
		       buttonMouse,
		       evbtn);
714 715 716 717 718
#endif
}

namespace Scintilla {
std::string ConvertText(const char *s, size_t len, const char *charSetDest,
719
			const char *charSetSource, bool transliterations, bool silent) {
720 721 722 723 724 725 726 727 728 729 730
	// s is not const because of different versions of iconv disagreeing about const
	std::string destForm;
	Converter conv(charSetDest, charSetSource, transliterations);
	if (conv) {
		gsize outLeft = len*3+1;
		destForm = std::string(outLeft, '\0');
		// g_iconv does not actually write to its input argument so safe to cast away const
		char *pin = const_cast<char *>(s);
		gsize inLeft = len;
		char *putf = &destForm[0];
		char *pout = putf;
731
		const gsize conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
		if (conversions == sizeFailure) {
			if (!silent) {
				if (len == 1)
					fprintf(stderr, "iconv %s->%s failed for %0x '%s'\n",
						charSetSource, charSetDest, (unsigned char)(*s), s);
				else
					fprintf(stderr, "iconv %s->%s failed for %s\n",
						charSetSource, charSetDest, s);
			}
			destForm = std::string();
		} else {
			destForm.resize(pout - putf);
		}
	} else {
		fprintf(stderr, "Can not iconv %s %s\n", charSetDest, charSetSource);
	}
	return destForm;
}
}

// Returns the target converted to UTF8.
// Return the length in bytes.
754
Sci::Position ScintillaGTK::TargetAsUTF8(char *text) const {
755
	const Sci::Position targetLength = targetEnd - targetStart;
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
	if (IsUnicodeMode()) {
		if (text) {
			pdoc->GetCharRange(text, targetStart, targetLength);
		}
	} else {
		// Need to convert
		const char *charSetBuffer = CharacterSetID();
		if (*charSetBuffer) {
			std::string s = RangeText(targetStart, targetEnd);
			std::string tmputf = ConvertText(&s[0], targetLength, "UTF-8", charSetBuffer, false);
			if (text) {
				memcpy(text, tmputf.c_str(), tmputf.length());
			}
			return tmputf.length();
		} else {
			if (text) {
				pdoc->GetCharRange(text, targetStart, targetLength);
			}
		}
	}
	return targetLength;
}

// Translates a nul terminated UTF8 string into the document encoding.
// Return the length of the result in bytes.
781
Sci::Position ScintillaGTK::EncodedFromUTF8(const char *utf8, char *encoded) const {
782
	const Sci::Position inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8);
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
	if (IsUnicodeMode()) {
		if (encoded) {
			memcpy(encoded, utf8, inputLength);
		}
		return inputLength;
	} else {
		// Need to convert
		const char *charSetBuffer = CharacterSetID();
		if (*charSetBuffer) {
			std::string tmpEncoded = ConvertText(utf8, inputLength, charSetBuffer, "UTF-8", true);
			if (encoded) {
				memcpy(encoded, tmpEncoded.c_str(), tmpEncoded.length());
			}
			return tmpEncoded.length();
		} else {
			if (encoded) {
				memcpy(encoded, utf8, inputLength);
			}
			return inputLength;
		}
	}
	// Fail
	return 0;
}

bool ScintillaGTK::ValidCodePage(int codePage) const {
	return codePage == 0
810 811 812 813 814 815
	       || codePage == SC_CP_UTF8
	       || codePage == 932
	       || codePage == 936
	       || codePage == 949
	       || codePage == 950
	       || codePage == 1361;
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
}

sptr_t ScintillaGTK::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
	try {
		switch (iMessage) {

		case SCI_GRABFOCUS:
			gtk_widget_grab_focus(PWidget(wMain));
			break;

		case SCI_GETDIRECTFUNCTION:
			return reinterpret_cast<sptr_t>(DirectFunction);

		case SCI_GETDIRECTPOINTER:
			return reinterpret_cast<sptr_t>(this);

#ifdef SCI_LEXER
		case SCI_LOADLEXERLIBRARY:
834
			LexerManager::GetInstance()->Load(ConstCharPtrFromSPtr(lParam));
835 836 837
			break;
#endif
		case SCI_TARGETASUTF8:
838
			return TargetAsUTF8(CharPtrFromSPtr(lParam));
839 840

		case SCI_ENCODEDFROMUTF8:
841
			return EncodedFromUTF8(ConstCharPtrFromUPtr(wParam),
842
					       CharPtrFromSPtr(lParam));
843 844 845 846 847 848 849 850 851

		case SCI_SETRECTANGULARSELECTIONMODIFIER:
			rectangularSelectionModifier = wParam;
			break;

		case SCI_GETRECTANGULARSELECTIONMODIFIER:
			return rectangularSelectionModifier;

		case SCI_SETREADONLY: {
852 853 854 855 856 857
				const sptr_t ret = ScintillaBase::WndProc(iMessage, wParam, lParam);
				if (accessible) {
					ScintillaGTKAccessible *sciAccessible = ScintillaGTKAccessible::FromAccessible(accessible);
					if (sciAccessible) {
						sciAccessible->NotifyReadOnly();
					}
858
				}
859
				return ret;
860 861 862 863 864 865 866 867 868 869
			}

		case SCI_GETACCESSIBILITY:
			return accessibilityEnabled;

		case SCI_SETACCESSIBILITY:
			accessibilityEnabled = wParam;
			if (accessible) {
				ScintillaGTKAccessible *sciAccessible = ScintillaGTKAccessible::FromAccessible(accessible);
				if (sciAccessible) {
870
					sciAccessible->SetAccessibility(accessibilityEnabled);
871 872 873 874 875 876 877
				}
			}
			break;

		default:
			return ScintillaBase::WndProc(iMessage, wParam, lParam);
		}
878
	} catch (std::bad_alloc &) {
879 880 881 882
		errorStatus = SC_STATUS_BADALLOC;
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
883
	return 0;
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
}

sptr_t ScintillaGTK::DefWndProc(unsigned int, uptr_t, sptr_t) {
	return 0;
}

bool ScintillaGTK::FineTickerRunning(TickReason reason) {
	return timers[reason].timer != 0;
}

void ScintillaGTK::FineTickerStart(TickReason reason, int millis, int /* tolerance */) {
	FineTickerCancel(reason);
	timers[reason].timer = gdk_threads_add_timeout(millis, TimeOut, &timers[reason]);
}

void ScintillaGTK::FineTickerCancel(TickReason reason) {
	if (timers[reason].timer) {
		g_source_remove(timers[reason].timer);
		timers[reason].timer = 0;
	}
}

bool ScintillaGTK::SetIdle(bool on) {
	if (on) {
		// Start idler, if it's not running.
		if (!idler.state) {
			idler.state = true;
911
			idler.idlerID = GUINT_TO_POINTER(
912
						gdk_threads_add_idle_full(G_PRIORITY_DEFAULT_IDLE, IdleCallback, this, nullptr));
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
		}
	} else {
		// Stop idler, if it's running
		if (idler.state) {
			idler.state = false;
			g_source_remove(GPOINTER_TO_UINT(idler.idlerID));
		}
	}
	return true;
}

void ScintillaGTK::SetMouseCapture(bool on) {
	if (mouseDownCaptures) {
		if (on) {
			gtk_grab_add(GTK_WIDGET(PWidget(wMain)));
		} else {
			gtk_grab_remove(GTK_WIDGET(PWidget(wMain)));
		}
	}
	capturedMouse = on;
}

bool ScintillaGTK::HaveMouseCapture() {
	return capturedMouse;
}

#if GTK_CHECK_VERSION(3,0,0)

// Is crcTest completely in crcContainer?
static bool CRectContains(const cairo_rectangle_t &crcContainer, const cairo_rectangle_t &crcTest) {
	return
		(crcTest.x >= crcContainer.x) && ((crcTest.x + crcTest.width) <= (crcContainer.x + crcContainer.width)) &&
		(crcTest.y >= crcContainer.y) && ((crcTest.y + crcTest.height) <= (crcContainer.y + crcContainer.height));
}

// Is crcTest completely in crcListContainer?
// May incorrectly return false if complex shape
static bool CRectListContains(const cairo_rectangle_list_t *crcListContainer, const cairo_rectangle_t &crcTest) {
	for (int r=0; r<crcListContainer->num_rectangles; r++) {
		if (CRectContains(crcListContainer->rectangles[r], crcTest))
			return true;
	}
	return false;
}

#endif

bool ScintillaGTK::PaintContains(PRectangle rc) {
	// This allows optimization when a rectangle is completely in the update region.
	// It is OK to return false when too difficult to determine as that just performs extra drawing
	bool contains = true;
	if (paintState == painting) {
		if (!rcPaint.Contains(rc)) {
			contains = false;
		} else if (rgnUpdate) {
#if GTK_CHECK_VERSION(3,0,0)
			cairo_rectangle_t grc = {rc.left, rc.top,
970 971
						 rc.right - rc.left, rc.bottom - rc.top
						};
972 973 974
			contains = CRectListContains(rgnUpdate, grc);
#else
			GdkRectangle grc = {static_cast<gint>(rc.left), static_cast<gint>(rc.top),
975 976
					    static_cast<gint>(rc.right - rc.left), static_cast<gint>(rc.bottom - rc.top)
					   };
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
			if (gdk_region_rect_in(rgnUpdate, &grc) != GDK_OVERLAP_RECTANGLE_IN) {
				contains = false;
			}
#endif
		}
	}
	return contains;
}

// Redraw all of text area. This paint will not be abandoned.
void ScintillaGTK::FullPaint() {
	wText.InvalidateAll();
}

PRectangle ScintillaGTK::GetClientRectangle() const {
992
	PRectangle rc = wMain.GetClientPosition();
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	if (verticalScrollBarVisible)
		rc.right -= verticalScrollBarWidth;
	if (horizontalScrollBarVisible && !Wrapping())
		rc.bottom -= horizontalScrollBarHeight;
	// Move to origin
	rc.right -= rc.left;
	rc.bottom -= rc.top;
	if (rc.bottom < 0)
		rc.bottom = 0;
	if (rc.right < 0)
		rc.right = 0;
	rc.left = 0;
	rc.top = 0;
	return rc;
}

void ScintillaGTK::ScrollText(Sci::Line linesToMove) {
	NotifyUpdateUI();

#if GTK_CHECK_VERSION(3,22,0)
	Redraw();
#else
	GtkWidget *wi = PWidget(wText);
	if (IS_WIDGET_REALIZED(wi)) {
		const int diff = vs.lineHeight * -linesToMove;
		gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
		gdk_window_process_updates(WindowFromWidget(wi), FALSE);
	}
#endif
}

void ScintillaGTK::SetVerticalScrollPos() {
	DwellEnd(true);
	gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmentv), topLine);
}

void ScintillaGTK::SetHorizontalScrollPos() {
	DwellEnd(true);
	gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset);
}

bool ScintillaGTK::ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) {
	bool modified = false;
1036
	const int pageScroll = LinesToScroll();
1037 1038

	if (gtk_adjustment_get_upper(adjustmentv) != (nMax + 1) ||
1039 1040
			gtk_adjustment_get_page_size(adjustmentv) != nPage ||
			gtk_adjustment_get_page_increment(adjustmentv) != pageScroll) {
1041
		gtk_adjustment_set_upper(adjustmentv, nMax + 1);
1042 1043
		gtk_adjustment_set_page_size(adjustmentv, nPage);
		gtk_adjustment_set_page_increment(adjustmentv, pageScroll);
1044 1045 1046 1047 1048 1049
#if !GTK_CHECK_VERSION(3,18,0)
		gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv));
#endif
		modified = true;
	}

1050
	const PRectangle rcText = GetTextRectangle();
1051 1052 1053
	int horizEndPreferred = scrollWidth;
	if (horizEndPreferred < 0)
		horizEndPreferred = 0;
1054 1055 1056
	const unsigned int pageWidth = static_cast<unsigned int>(rcText.Width());
	const unsigned int pageIncrement = pageWidth / 3;
	const unsigned int charWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
1057
	if (gtk_adjustment_get_upper(adjustmenth) != horizEndPreferred ||
1058 1059 1060
			gtk_adjustment_get_page_size(adjustmenth) != pageWidth ||
			gtk_adjustment_get_page_increment(adjustmenth) != pageIncrement ||
			gtk_adjustment_get_step_increment(adjustmenth) != charWidth) {
1061
		gtk_adjustment_set_upper(adjustmenth, horizEndPreferred);
1062 1063 1064
		gtk_adjustment_set_page_size(adjustmenth, pageWidth);
		gtk_adjustment_set_page_increment(adjustmenth, pageIncrement);
		gtk_adjustment_set_step_increment(adjustmenth, charWidth);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
#if !GTK_CHECK_VERSION(3,18,0)
		gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth));
#endif
		modified = true;
	}
	if (modified && (paintState == painting)) {
		repaintFullWindow = true;
	}

	return modified;
}

void ScintillaGTK::ReconfigureScrollBars() {
1078 1079
	const PRectangle rc = wMain.GetClientPosition();
	Resize(static_cast<int>(rc.Width()), static_cast<int>(rc.Height()));
1080 1081 1082 1083
}

void ScintillaGTK::NotifyChange() {
	g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1084
		      Platform::LongFromTwoShorts(GetCtrlID(), SCEN_CHANGE), PWidget(wMain));
1085 1086 1087
}

void ScintillaGTK::NotifyFocus(bool focus) {
1088 1089
	if (commandEvents)
		g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1090 1091
			      Platform::LongFromTwoShorts
			      (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), PWidget(wMain));
1092 1093 1094 1095 1096 1097 1098
	Editor::NotifyFocus(focus);
}

void ScintillaGTK::NotifyParent(SCNotification scn) {
	scn.nmhdr.hwndFrom = PWidget(wMain);
	scn.nmhdr.idFrom = GetCtrlID();
	g_signal_emit(G_OBJECT(sci), scintilla_signals[NOTIFY_SIGNAL], 0,
1099
		      GetCtrlID(), &scn);
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
}

void ScintillaGTK::NotifyKey(int key, int modifiers) {
	SCNotification scn = {};
	scn.nmhdr.code = SCN_KEY;
	scn.ch = key;
	scn.modifiers = modifiers;

	NotifyParent(scn);
}

void ScintillaGTK::NotifyURIDropped(const char *list) {
	SCNotification scn = {};
	scn.nmhdr.code = SCN_URIDROPPED;
	scn.text = list;

	NotifyParent(scn);
}

const char *CharacterSetID(int characterSet);

const char *ScintillaGTK::CharacterSetID() const {
	return ::CharacterSetID(vs.styles[STYLE_DEFAULT].characterSet);
}

class CaseFolderDBCS : public CaseFolderTable {
	const char *charSet;
public:
	explicit CaseFolderDBCS(const char *charSet_) : charSet(charSet_) {
		StandardASCII();
	}
	size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) override {
		if ((lenMixed == 1) && (sizeFolded > 0)) {
			folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
			return 1;
		} else if (*charSet) {
			std::string sUTF8 = ConvertText(mixed, lenMixed,
1137
							"UTF-8", charSet, false);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
			if (!sUTF8.empty()) {
				gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
				size_t lenMapped = strlen(mapped);
				if (lenMapped < sizeFolded) {
					memcpy(folded, mapped,  lenMapped);
				} else {
					folded[0] = '\0';
					lenMapped = 1;
				}
				g_free(mapped);
				return lenMapped;
			}
		}
		// Something failed so return a single NUL byte
		folded[0] = '\0';
		return 1;
	}
};

CaseFolder *ScintillaGTK::CaseFolderForEncoding() {
	if (pdoc->dbcsCodePage == SC_CP_UTF8) {
		return new CaseFolderUnicode();
	} else {
		const char *charSetBuffer = CharacterSetID();
		if (charSetBuffer) {
			if (pdoc->dbcsCodePage == 0) {
				CaseFolderTable *pcf = new CaseFolderTable();
				pcf->StandardASCII();
				// Only for single byte encodings
				for (int i=0x80; i<0x100; i++) {
					char sCharacter[2] = "A";
					sCharacter[0] = i;
					// Silent as some bytes have no assigned character
					std::string sUTF8 = ConvertText(sCharacter, 1,
1172
									"UTF-8", charSetBuffer, false, true);
1173 1174 1175 1176
					if (!sUTF8.empty()) {
						gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
						if (mapped) {
							std::string mappedBack = ConvertText(mapped, strlen(mapped),
1177
											     charSetBuffer, "UTF-8", false, true);
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
							if ((mappedBack.length() == 1) && (mappedBack[0] != sCharacter[0])) {
								pcf->SetTranslation(sCharacter[0], mappedBack[0]);
							}
							g_free(mapped);
						}
					}
				}
				return pcf;
			} else {
				return new CaseFolderDBCS(charSetBuffer);
			}
		}
1190
		return nullptr;
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
	}
}

namespace {

struct CaseMapper {
	gchar *mapped;	// Must be freed with g_free
	CaseMapper(const std::string &sUTF8, bool toUpperCase) {
		if (toUpperCase) {
			mapped = g_utf8_strup(sUTF8.c_str(), sUTF8.length());
		} else {
			mapped = g_utf8_strdown(sUTF8.c_str(), sUTF8.length());
		}
	}
	~CaseMapper() {
		g_free(mapped);
	}
};

}

std::string ScintillaGTK::CaseMapString(const std::string &s, int caseMapping) {
	if ((s.size() == 0) || (caseMapping == cmSame))
		return s;

	if (IsUnicodeMode()) {
		std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
1218 1219
		const size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
					 (caseMapping == cmUpper) ? CaseConversionUpper : CaseConversionLower);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
		retMapped.resize(lenMapped);
		return retMapped;
	}

	const char *charSetBuffer = CharacterSetID();

	if (!*charSetBuffer) {
		CaseMapper mapper(s, caseMapping == cmUpper);
		return std::string(mapper.mapped, strlen(mapper.mapped));
	} else {
		// Change text to UTF-8
		std::string sUTF8 = ConvertText(s.c_str(), s.length(),
1232
						"UTF-8", charSetBuffer, false);
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
		CaseMapper mapper(sUTF8, caseMapping == cmUpper);
		return ConvertText(mapper.mapped, strlen(mapper.mapped), charSetBuffer, "UTF-8", false);
	}
}

int ScintillaGTK::KeyDefault(int key, int modifiers) {
	// Pass up to container in case it is an accelerator
	NotifyKey(key, modifiers);
	return 0;
}

void ScintillaGTK::CopyToClipboard(const SelectionText &selectedText) {
	SelectionText *clipText = new SelectionText();
	clipText->Copy(selectedText);
	StoreOnClipboard(clipText);
}

void ScintillaGTK::Copy() {
	if (!sel.Empty()) {
		SelectionText *clipText = new SelectionText();
		CopySelectionRange(clipText);
		StoreOnClipboard(clipText);
#if PLAT_GTK_WIN32
		if (sel.IsRectangular()) {
			::OpenClipboard(NULL);
			::SetClipboardData(cfColumnSelect, 0);
			::CloseClipboard();
		}
#endif
	}
}

1265
namespace {
1266

1267
// Helper class for the asynchronous paste not to risk calling in a destroyed ScintillaGTK
1268

1269 1270
class SelectionReceiver : GObjectWatcher {
	ScintillaGTK *sci;
1271

1272 1273 1274
	void Destroyed() override {
		sci = nullptr;
	}
1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
public:
	SelectionReceiver(ScintillaGTK *sci_) :
		GObjectWatcher(G_OBJECT(sci_->MainObject())),
		sci(sci_) {
	}

	static void ClipboardReceived(GtkClipboard *, GtkSelectionData *selection_data, gpointer data) {
		SelectionReceiver *self = static_cast<SelectionReceiver *>(data);
		if (self->sci) {
			self->sci->ReceivedClipboard(selection_data);
1286
		}
1287 1288 1289
		delete self;
	}
};
1290

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
}

void ScintillaGTK::RequestSelection(GdkAtom atomSelection) {
	atomSought = atomUTF8;
	GtkClipboard *clipBoard =
		gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomSelection);
	if (clipBoard) {
		gtk_clipboard_request_contents(clipBoard, atomSought,
					       SelectionReceiver::ClipboardReceived,
					       new SelectionReceiver(this));
	}
}

void ScintillaGTK::Paste() {
	RequestSelection(GDK_SELECTION_CLIPBOARD);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
}

void ScintillaGTK::CreateCallTipWindow(PRectangle rc) {
	if (!ct.wCallTip.Created()) {
		ct.wCallTip = gtk_window_new(GTK_WINDOW_POPUP);
		ct.wDraw = gtk_drawing_area_new();
		GtkWidget *widcdrw = PWidget(ct.wDraw);	//	// No code inside the G_OBJECT macro
		gtk_container_add(GTK_CONTAINER(PWidget(ct.wCallTip)), widcdrw);
#if GTK_CHECK_VERSION(3,0,0)
		g_signal_connect(G_OBJECT(widcdrw), "draw",
1316
				 G_CALLBACK(ScintillaGTK::DrawCT), &ct);
1317 1318
#else
		g_signal_connect(G_OBJECT(widcdrw), "expose_event",
1319
				 G_CALLBACK(ScintillaGTK::ExposeCT), &ct);
1320 1321
#endif
		g_signal_connect(G_OBJECT(widcdrw), "button_press_event",
1322
				 G_CALLBACK(ScintillaGTK::PressCT), this);
1323
		gtk_widget_set_events(widcdrw,
1324
				      GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK);
1325 1326
		GtkWidget *top = gtk_widget_get_toplevel(static_cast<GtkWidget *>(wMain.GetID()));
		gtk_window_set_transient_for(GTK_WINDOW(static_cast<GtkWidget *>(PWidget(ct.wCallTip))),
1327
					     GTK_WINDOW(top));
1328
	}
1329 1330 1331
	const int width = static_cast<int>(rc.Width());
	const int height = static_cast<int>(rc.Height());
	gtk_widget_set_size_request(PWidget(ct.wDraw), width, height);
1332 1333
	ct.wDraw.Show();
	if (PWindow(ct.wCallTip)) {
1334
		gdk_window_resize(PWindow(ct.wCallTip), width, height);
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
	}
}

void ScintillaGTK::AddToPopUp(const char *label, int cmd, bool enabled) {
	GtkWidget *menuItem;
	if (label[0])
		menuItem = gtk_menu_item_new_with_label(label);
	else
		menuItem = gtk_separator_menu_item_new();
	gtk_menu_shell_append(GTK_MENU_SHELL(popup.GetID()), menuItem);
	g_object_set_data(G_OBJECT(menuItem), "CmdNum", GINT_TO_POINTER(cmd));
1346
	g_signal_connect(G_OBJECT(menuItem), "activate", G_CALLBACK(PopUpCB), this);
1347 1348 1349 1350 1351 1352 1353 1354

	if (cmd) {
		if (menuItem)
			gtk_widget_set_sensitive(menuItem, enabled);
	}
}

bool ScintillaGTK::OwnPrimarySelection() {
1355 1356
	return (wSelection.Created() &&
		(gdk_selection_owner_get(GDK_SELECTION_PRIMARY) == PWindow(wSelection)) &&
1357
		(PWindow(wSelection) != nullptr));
1358 1359 1360 1361 1362
}

void ScintillaGTK::ClaimSelection() {
	// X Windows has a 'primary selection' as well as the clipboard.
	// Whenever the user selects some text, we become the primary selection
1363
	if (!sel.Empty() && wSelection.Created() && IS_WIDGET_REALIZED(GTK_WIDGET(PWidget(wSelection)))) {
1364 1365
		primarySelection = true;
		gtk_selection_owner_set(GTK_WIDGET(PWidget(wSelection)),
1366
					GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1367 1368 1369 1370
		primary.Clear();
	} else if (OwnPrimarySelection()) {
		primarySelection = true;
		if (primary.Empty())
1371
			gtk_selection_owner_set(nullptr, GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
	} else {
		primarySelection = false;
		primary.Clear();
	}
}

static const guchar *DataOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data(sd); }
static gint LengthOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_length(sd); }
static GdkAtom TypeOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data_type(sd); }
static GdkAtom SelectionOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_selection(sd); }

// Detect rectangular text, convert line ends to current mode, convert from or to UTF-8
void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText) {
	const char *data = reinterpret_cast<const char *>(DataOfGSD(selectionData));
	int len = LengthOfGSD(selectionData);
	GdkAtom selectionTypeData = TypeOfGSD(selectionData);

	// Return empty string if selection is not a string
	if ((selectionTypeData != GDK_TARGET_STRING) && (selectionTypeData != atomUTF8)) {
		selText.Clear();
		return;
	}

	// Check for "\n\0" ending to string indicating that selection is rectangular
	bool isRectangular;
#if PLAT_GTK_WIN32
	isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
#else
	isRectangular = ((len > 2) && (data[len - 1] == 0 && data[len - 2] == '\n'));
	if (isRectangular)
		len--;	// Forget the extra '\0'
#endif

#if PLAT_GTK_WIN32
	// Win32 includes an ending '\0' byte in 'len' for clipboard text from
	// external applications; ignore it.
	if ((len > 0) && (data[len - 1] == '\0'))
		len--;
#endif

	std::string dest(data, len);
	if (selectionTypeData == GDK_TARGET_STRING) {
		if (IsUnicodeMode()) {
			// Unknown encoding so assume in Latin1
1416
			dest = UTF8FromLatin1(dest);
1417 1418 1419 1420
			selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
		} else {
			// Assume buffer is in same encoding as selection
			selText.Copy(dest, pdoc->dbcsCodePage,
1421
				     vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1422 1423 1424 1425 1426 1427 1428
		}
	} else {	// UTF-8
		const char *charSetBuffer = CharacterSetID();
		if (!IsUnicodeMode() && *charSetBuffer) {
			// Convert to locale
			dest = ConvertText(dest.c_str(), dest.length(), charSetBuffer, "UTF-8", true);
			selText.Copy(dest, pdoc->dbcsCodePage,
1429
				     vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1430 1431 1432 1433 1434 1435
		} else {
			selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
		}
	}
}

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
void ScintillaGTK::InsertSelection(GtkSelectionData *selectionData) {
	const gint length = gtk_selection_data_get_length(selectionData);
	if (length >= 0) {
		GdkAtom selection = gtk_selection_data_get_selection(selectionData);
		SelectionText selText;
		GetGtkSelectionText(selectionData, selText);

		UndoGroup ug(pdoc);
		if (selection == GDK_SELECTION_CLIPBOARD) {
			ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
		}

		InsertPasteShape(selText.Data(), selText.Length(),
				 selText.rectangular ? pasteRectangular : pasteStream);
		EnsureCaretVisible();
	}
	Redraw();
}

GObject *ScintillaGTK::MainObject() const noexcept {
	return G_OBJECT(PWidget(wMain));
}

void ScintillaGTK::ReceivedClipboard(GtkSelectionData *selection_data) noexcept {
	try {
		InsertSelection(selection_data);
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

1467 1468
void ScintillaGTK::ReceivedSelection(GtkSelectionData *selection_data) {
	try {
1469 1470
		if ((SelectionOfGSD(selection_data) == GDK_SELECTION_CLIPBOARD) ||
				(SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY)) {
1471 1472 1473
			if ((atomSought == atomUTF8) && (LengthOfGSD(selection_data) <= 0)) {
				atomSought = atomString;
				gtk_selection_convert(GTK_WIDGET(PWidget(wMain)),
1474
						      SelectionOfGSD(selection_data), atomSought, GDK_CURRENT_TIME);
1475
			} else if ((LengthOfGSD(selection_data) > 0) &&
1476 1477
					((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8))) {
				InsertSelection(selection_data);
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
			}
		}
//	else fprintf(stderr, "Target non string %d %d\n", (int)(selection_data->type),
//		(int)(atomUTF8));
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::ReceivedDrop(GtkSelectionData *selection_data) {
	dragWasDropped = true;
	if (TypeOfGSD(selection_data) == atomUriList || TypeOfGSD(selection_data) == atomDROPFILES_DND) {
		const char *data = reinterpret_cast<const char *>(DataOfGSD(selection_data));
		std::vector<char> drop(data, data + LengthOfGSD(selection_data));
		drop.push_back('\0');
		NotifyURIDropped(&drop[0]);
	} else if ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8)) {
		if (LengthOfGSD(selection_data) > 0) {
			SelectionText selText;
			GetGtkSelectionText(selection_data, selText);
			DropAt(posDrop, selText.Data(), selText.Length(), false, selText.rectangular);
		}
	} else if (LengthOfGSD(selection_data) > 0) {
		//~ fprintf(stderr, "ReceivedDrop other %p\n", static_cast<void *>(selection_data->type));
	}
	Redraw();
}



void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *text) {
#if PLAT_GTK_WIN32
	// GDK on Win32 expands any \n into \r\n, so make a copy of
	// the clip text now with newlines converted to \n.  Use { } to hide symbols
	// from code below
	std::unique_ptr<SelectionText> newline_normalized;
	{
		std::string tmpstr = Document::TransformLineEnds(text->Data(), text->Length(), SC_EOL_LF);
		newline_normalized.reset(new SelectionText());
		newline_normalized->Copy(tmpstr, SC_CP_UTF8, 0, text->rectangular, false);
		text = newline_normalized.get();
	}
#endif

	// Convert text to utf8 if it isn't already
	std::unique_ptr<SelectionText> converted;
	if ((text->codePage != SC_CP_UTF8) && (info == TARGET_UTF8_STRING)) {
		const char *charSet = ::CharacterSetID(text->characterSet);
		if (*charSet) {
			std::string tmputf = ConvertText(text->Data(), text->Length(), "UTF-8", charSet, false);
1528
			converted = std::make_unique<SelectionText>();
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
			converted->Copy(tmputf, SC_CP_UTF8, 0, text->rectangular, false);
			text = converted.get();
		}
	}

	// Here is a somewhat evil kludge.
	// As I can not work out how to store data on the clipboard in multiple formats
	// and need some way to mark the clipping as being stream or rectangular,
	// the terminating \0 is included in the length for rectangular clippings.
	// All other tested aplications behave benignly by ignoring the \0.
	// The #if is here because on Windows cfColumnSelect clip entry is used
	// instead as standard indicator of rectangularness (so no need to kludge)
	const char *textData = text->Data();
	int len = text->Length();
#if PLAT_GTK_WIN32 == 0
	if (text->rectangular)
		len++;
#endif

	if (info == TARGET_UTF8_STRING) {
		gtk_selection_data_set_text(selection_data, textData, len);
	} else {
		gtk_selection_data_set(selection_data,
1552 1553
				       static_cast<GdkAtom>(GDK_SELECTION_TYPE_STRING),
				       8, reinterpret_cast<const guchar *>(textData), len);
1554 1555 1556 1557 1558
	}
}

void ScintillaGTK::StoreOnClipboard(SelectionText *clipText) {
	GtkClipboard *clipBoard =
1559 1560
		gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_CLIPBOARD);
	if (clipBoard == nullptr) // Occurs if widget isn't in a toplevel
1561 1562 1563
		return;

	if (gtk_clipboard_set_with_data(clipBoard, clipboardCopyTargets, nClipboardCopyTargets,
1564
					ClipboardGetSelection, ClipboardClearSelection, clipText)) {
1565 1566 1567 1568 1569
		gtk_clipboard_set_can_store(clipBoard, clipboardCopyTargets, nClipboardCopyTargets);
	}
}

void ScintillaGTK::ClipboardGetSelection(GtkClipboard *, GtkSelectionData *selection_data, guint info, void *data) {
1570
	GetSelection(selection_data, info, static_cast<SelectionText *>(data));
1571 1572 1573
}

void ScintillaGTK::ClipboardClearSelection(GtkClipboard *, void *data) {
1574
	SelectionText *obj = static_cast<SelectionText *>(data);
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
	delete obj;
}

void ScintillaGTK::UnclaimSelection(GdkEventSelection *selection_event) {
	try {
		//Platform::DebugPrintf("UnclaimSelection\n");
		if (selection_event->selection == GDK_SELECTION_PRIMARY) {
			//Platform::DebugPrintf("UnclaimPrimarySelection\n");
			if (!OwnPrimarySelection()) {
				primary.Clear();
				primarySelection = false;
				FullPaint();
			}
		}
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
}

void ScintillaGTK::PrimarySelection(GtkWidget *, GtkSelectionData *selection_data, guint info, guint, ScintillaGTK *sciThis) {
	try {
		if (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY) {
			if (sciThis->primary.Empty()) {
				sciThis->CopySelectionRange(&sciThis->primary);
			}
			sciThis->GetSelection(selection_data, info, &sciThis->primary);
		}
	} catch (...) {
		sciThis->errorStatus = SC_STATUS_FAILURE;
	}
}

1607
gboolean ScintillaGTK::PrimaryClear(GtkWidget *widget, GdkEventSelection *event, ScintillaGTK *sciThis) {
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
	sciThis->UnclaimSelection(event);
	if (GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event) {
		return GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event(widget, event);
	}
	return TRUE;
}

void ScintillaGTK::Resize(int width, int height) {
	//Platform::DebugPrintf("Resize %d %d\n", width, height);
	//printf("Resize %d %d\n", width, height);

	// GTK+ 3 warns when we allocate smaller than the minimum allocation,
	// so we use these variables to store the minimum scrollbar lengths.
	int minVScrollBarHeight, minHScrollBarWidth;

	// Not always needed, but some themes can have different sizes of scrollbars
#if GTK_CHECK_VERSION(3,0,0)
	GtkRequisition minimum, requisition;
	gtk_widget_get_preferred_size(PWidget(scrollbarv), &minimum, &requisition);
	minVScrollBarHeight = minimum.height;
	verticalScrollBarWidth = requisition.width;
	gtk_widget_get_preferred_size(PWidget(scrollbarh), &minimum, &requisition);
	minHScrollBarWidth = minimum.width;
	horizontalScrollBarHeight = requisition.height;
#else
	minVScrollBarHeight = minHScrollBarWidth = 1;
	verticalScrollBarWidth = GTK_WIDGET(PWidget(scrollbarv))->requisition.width;
	horizontalScrollBarHeight = GTK_WIDGET(PWidget(scrollbarh))->requisition.height;
#endif

	// These allocations should never produce negative sizes as they would wrap around to huge
	// unsigned numbers inside GTK+ causing warnings.
1640
	const bool showSBHorizontal = horizontalScrollBarVisible && !Wrapping();
1641

1642
	GtkAllocation alloc = {};
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
	if (showSBHorizontal) {
		gtk_widget_show(GTK_WIDGET(PWidget(scrollbarh)));
		alloc.x = 0;
		alloc.y = height - horizontalScrollBarHeight;
		alloc.width = std::max(minHScrollBarWidth, width - verticalScrollBarWidth);
		alloc.height = horizontalScrollBarHeight;
		gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarh)), &alloc);
	} else {
		gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarh)));
		horizontalScrollBarHeight = 0; // in case horizontalScrollBarVisible is true.
	}

	if (verticalScrollBarVisible) {
		gtk_widget_show(GTK_WIDGET(PWidget(scrollbarv)));
		alloc.x = width - verticalScrollBarWidth;
		alloc.y = 0;
		alloc.width = verticalScrollBarWidth;
		alloc.height = std::max(minVScrollBarHeight, height - horizontalScrollBarHeight);
		gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarv)), &alloc);
	} else {
		gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarv)));
		verticalScrollBarWidth = 0;
	}
	if (IS_WIDGET_MAPPED(PWidget(wMain))) {
		ChangeSize();
	}

	alloc.x = 0;
	alloc.y = 0;
	alloc.width = 1;
	alloc.height = 1;
#if GTK_CHECK_VERSION(3, 0, 0)
	// please GTK 3.20 and ask wText what size it wants, although we know it doesn't really need
	// anything special as it's ours.
1677
	gtk_widget_get_preferred_size(PWidget(wText), &requisition, nullptr);
1678 1679 1680 1681 1682 1683 1684 1685
	alloc.width = requisition.width;
	alloc.height = requisition.height;
#endif
	alloc.width = std::max(alloc.width, width - verticalScrollBarWidth);
	alloc.height = std::max(alloc.height, height - horizontalScrollBarHeight);
	gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc);
}

1686 1687 1688
namespace {

void SetAdjustmentValue(GtkAdjustment *object, int value) {
1689
	GtkAdjustment *adjustment = GTK_ADJUSTMENT(object);
1690 1691
	const int maxValue = static_cast<int>(
				     gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size(adjustment));
1692 1693 1694 1695 1696 1697 1698 1699

	if (value > maxValue)
		value = maxValue;
	if (value < 0)
		value = 0;
	gtk_adjustment_set_value(adjustment, value);
}

1700
int modifierTranslated(int sciModifier) noexcept {
1701
	switch (sciModifier) {
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
	case SCMOD_SHIFT:
		return GDK_SHIFT_MASK;
	case SCMOD_CTRL:
		return GDK_CONTROL_MASK;
	case SCMOD_ALT:
		return GDK_MOD1_MASK;
	case SCMOD_SUPER:
		return GDK_MOD4_MASK;
	default:
		return 0;
1712 1713 1714
	}
}

1715 1716 1717 1718 1719 1720 1721 1722
Point PointOfEvent(const GdkEventButton *event) noexcept {
	// Use floor as want to round in the same direction (-infinity) so
	// there is no stickiness crossing 0.0.
	return Point(static_cast<XYPOSITION>(std::floor(event->x)), static_cast<XYPOSITION>(std::floor(event->y)));
}

}

1723 1724 1725 1726 1727 1728 1729 1730
gint ScintillaGTK::PressThis(GdkEventButton *event) {
	try {
		//Platform::DebugPrintf("Press %x time=%d state = %x button = %x\n",this,event->time, event->state, event->button);
		// Do not use GTK+ double click events as Scintilla has its own double click detection
		if (event->type != GDK_BUTTON_PRESS)
			return FALSE;

		if (evbtn) {
1731
			gdk_event_free(evbtn);
1732
		}
1733 1734
		evbtn = gdk_event_copy(reinterpret_cast<GdkEvent *>(event));
		buttonMouse = event->button;
1735 1736
		const Point pt = PointOfEvent(event);
		const PRectangle rcClient = GetClientRectangle();
1737 1738 1739 1740 1741 1742 1743
		//Platform::DebugPrintf("Press %0d,%0d in %0d,%0d %0d,%0d\n",
		//	pt.x, pt.y, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
		if ((pt.x > rcClient.right) || (pt.y > rcClient.bottom)) {
			Platform::DebugPrintf("Bad location\n");
			return FALSE;
		}

1744
		const bool shift = (event->state & GDK_SHIFT_MASK) != 0;
1745 1746 1747 1748
		bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
		// On X, instead of sending literal modifiers use the user specified
		// modifier, defaulting to control instead of alt.
		// This is because most X window managers grab alt + click for moving
1749
		const bool alt = (event->state & modifierTranslated(rectangularSelectionModifier)) != 0;
1750 1751 1752 1753

		gtk_widget_grab_focus(PWidget(wMain));
		if (event->button == 1) {
#if PLAT_GTK_MACOSX
1754
			const bool meta = ctrl;
1755 1756 1757 1758
			// GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
			// not GDK_META_MASK like in key events.
			ctrl = (event->state & GDK_MOD2_MASK) != 0;
#else
1759
			const bool meta = false;
1760 1761 1762 1763
#endif
			ButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
		} else if (event->button == 2) {
			// Grab the primary selection if it exists
1764
			const SelectionPosition pos = SPositionFromLocation(pt, false, false, UserVirtualSpace());
1765 1766 1767 1768 1769
			if (OwnPrimarySelection() && primary.Empty())
				CopySelectionRange(&primary);

			sel.Clear();
			SetSelection(pos, pos);
1770
			RequestSelection(GDK_SELECTION_PRIMARY);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
		} else if (event->button == 3) {
			if (!PointInSelection(pt))
				SetEmptySelection(PositionFromLocation(pt));
			if (ShouldDisplayPopup(pt)) {
				// PopUp menu
				// Convert to screen
				int ox = 0;
				int oy = 0;
				gdk_window_get_origin(PWindow(wMain), &ox, &oy);
				ContextMenu(Point(pt.x + ox, pt.y + oy));
			} else {
#if PLAT_GTK_MACOSX
1783
				const bool meta = ctrl;
1784 1785 1786 1787
				// GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
				// not GDK_META_MASK like in key events.
				ctrl = (event->state & GDK_MOD2_MASK) != 0;
#else
1788
				const bool meta = false;
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
#endif
				RightButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
				return FALSE;
			}
		} else if (event->button == 4) {
			// Wheel scrolling up (only GTK 1.x does it this way)
			if (ctrl)
				SetAdjustmentValue(adjustmenth, xOffset - 6);
			else
				SetAdjustmentValue(adjustmentv, topLine - 3);
		} else if (event->button == 5) {
			// Wheel scrolling down (only GTK 1.x does it this way)
			if (ctrl)
				SetAdjustmentValue(adjustmenth, xOffset + 6);
			else
				SetAdjustmentValue(adjustmentv, topLine + 3);
		}
	} catch (...) {
		errorStatus = SC_STATUS_FAILURE;
	}
	return TRUE;
}

gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) {
	if (event->window != WindowFromWidget(widget))
		return FALSE;
	ScintillaGTK *sciThis = FromWidget(widget);
	return sciThis->PressThis(event);
}

gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
	ScintillaGTK *sciThis = FromWidget(widget);
	try {
		//Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state);
		if (!sciThis->HaveMouseCapture())
			return FALSE;
		if (event->button == 1) {
1826
			Point pt = PointOfEvent(event);
1827 1828 1829 1830 1831 1832 1833
			//Platform::DebugPrintf("Up %x %x %d %d %d\n",
			//	sciThis,event->window,event->time, pt.x, pt.y);
			if (event->window != PWindow(sciThis->wMain))
				// If mouse released on scroll bar then the position is relative to the
				// scrollbar, not the drawing window so just repeat the most recent point.
				pt = sciThis->ptMouseLast;
			const int modifiers = ModifierFlags(
1834 1835 1836
						      (event->state & GDK_SHIFT_MASK) != 0,
						      (event->state & GDK_CONTROL_MASK) != 0,
						      (event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) != 0);
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
			sciThis->ButtonUpWithModifiers(pt, event->time, modifiers);
		}
	} catch (...) {
		sciThis->errorStatus = SC_STATUS_FAILURE;
	}
	return FALSE;
}

// win32gtk and GTK >= 2 use SCROLL_* events instead of passing the
// button4/5/6/7 events to the GTK app
gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
	ScintillaGTK *sciThis = FromWidget(widget);
	try {

1851
		if (widget == nullptr || event == nullptr)
1852 1853 1854 1855 1856 1857 1858 1859
			return FALSE;

#if defined(GDK_WINDOWING_WAYLAND)
		if (event->direction == GDK_SCROLL_SMOOTH && GDK_IS_WAYLAND_WINDOW(event->window)) {
			const int smoothScrollFactor = 4;
			sciThis->smoothScrollY += event->delta_y * smoothScrollFactor;
			sciThis->smoothScrollX += event->delta_x * smoothScrollFactor;;
			if (ABS(sciThis->smoothScrollY) >= 1.0) {
1860
				const int scrollLines = std::trunc(sciThis->smoothScrollY);
1861 1862 1863 1864
				sciThis->ScrollTo(sciThis->topLine + scrollLines);
				sciThis->smoothScrollY -= scrollLines;
			}
			if (ABS(sciThis->smoothScrollX) >= 1.0) {
1865
				const int scrollPixels = std::trunc(sciThis->smoothScrollX);
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
				sciThis->HorizontalScrollTo(sciThis->xOffset + scrollPixels);
				sciThis->smoothScrollX -= scrollPixels;
			}
			return TRUE;
		}
#endif

		// Compute amount and direction to scroll (even tho on win32 there is
		// intensity of scrolling info in the native message, gtk doesn't
		// support this so we simulate similarly adaptive scrolling)
		// Note that this is disabled on OS X (Darwin) with the X11 backend
		// where the X11 server already has an adaptive scrolling algorithm
		// that fights with this one
		int cLineScroll;
#if defined(__APPLE__) && !defined(GDK_WINDOWING_QUARTZ)
		cLineScroll = sciThis->linesPerScroll;
		if (cLineScroll == 0)
			cLineScroll = 4;
		sciThis->wheelMouseIntensity = cLineScroll;
#else
		int timeDelta = 1000000;
		GTimeVal curTime;
		g_get_current_time(&curTime);
		if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec)
			timeDelta = curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec;
		else if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec + 1)
			timeDelta = 1000000 + (curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec);
		if ((event->direction == sciThis->lastWheelMouseDirection) && (timeDelta < 250000)) {
			if (sciThis->wheelMouseIntensity < 12)
				sciThis->wheelMouseIntensity++;
			cLineScroll = sciThis->wheelMouseIntensity;
		} else {
			cLineScroll = sciThis->linesPerScroll;
			if (cLineScroll == 0)
				cLineScroll = 4;
			sciThis->wheelMouseIntensity = cLineScroll;
		}
#endif
		if (event->direction == GDK_SCROLL_UP || event->direction == GDK_SCROLL_LEFT) {
			cLineScroll *= -1;
		}
		g_get_current_time(&sciThis->lastWheelMouseTime);
		sciThis->lastWheelMouseDirection = event->direction;

		// Note:  Unpatched versions of win32gtk don't set the 'state' value so
		// only regular scrolling is supported there.  Also, unpatched win32gtk
		// issues spurious button 2 mouse events during wheeling, which can cause
		// problems (a patch for both was submitted by archaeopteryx.com on 13Jun2001)

		// Data zoom not supported
		if (event->state & GDK_SHIFT_MASK) {
			return FALSE;
		}

#if GTK_CHECK_VERSION(3,4,0)
		// Smooth scrolling not supported
		if (event->direction == GDK_SCROLL_SMOOTH) {
			return FALSE;
		}
#endif

		// Horizontal scrolling
		if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) {
			sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll);

			// Text font size zoom
		} else if (event->state & GDK_CONTROL_MASK) {
			if (cLineScroll < 0) {
				sciThis->KeyCommand(SCI_ZOOMIN);
			} else {
				sciThis->KeyCommand(SCI_ZOOMOUT);
			}

			// Regular scrolling
		} else {
			sciThis->ScrollTo(sciThis->topLine + cLineScroll);
		}
		return TRUE;
	} catch (...) {
		sciThis->errorStatus = SC_STATUS_FAILURE;
	}
	return FALSE;
}

gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
	ScintillaGTK *sciThis = FromWidget(widget);
	try {
		//Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time);
		if (event->window != WindowFromWidget(widget))
			return FALSE;
		int x = 0;
		int y = 0;
		GdkModifierType state;
		if (event->is_hint) {
#if GTK_CHECK_VERSION(3,0,0)
			gdk_window_get_device_position(event->window,
1962
						       event->device, &x, &y, &state);
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
#else
			gdk_window_get_pointer(event->window, &x, &y, &state);
#endif
		} else {
			x = static_cast<int>(event->x);
			y = static_cast<int>(event->y);
			state = static_cast<GdkModifierType>(event->state);
		}
		//Platform::DebugPrintf("Move %x %x %d %c %d %d\n",
		//	sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y);
1973
		const Point pt(static_cast<XYPOSITION>(x), static_cast<XYPOSITION>(y));
1974
		const int modifiers = ModifierFlags(
1975 1976 1977
					      (event->state & GDK_SHIFT_MASK) != 0,
					      (event->state & GDK_CONTROL_MASK) != 0,
					      (event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) != 0);
1978 1979 1980 1981 1982 1983 1984 1985