Update Scintilla to version 3.6.5
[geany-mirror.git] / scintilla / gtk / ScintillaGTK.cxx
blob7f192942088d27f7a0ea31574d40ef693bc04a8b
1 // Scintilla source code edit control
2 // ScintillaGTK.cxx - GTK+ specific subclass of ScintillaBase
3 // Copyright 1998-2004 by Neil Hodgson <neilh@scintilla.org>
4 // The License.txt file describes the conditions under which this software may be distributed.
6 #include <stdlib.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <time.h>
10 #include <assert.h>
11 #include <ctype.h>
13 #include <stdexcept>
14 #include <new>
15 #include <string>
16 #include <vector>
17 #include <map>
18 #include <algorithm>
20 #include <glib.h>
21 #include <gmodule.h>
22 #include <gdk/gdk.h>
23 #include <gtk/gtk.h>
24 #include <gdk/gdkkeysyms.h>
26 #if defined(__WIN32__) || defined(_MSC_VER)
27 #include <windows.h>
28 #endif
30 #include "Platform.h"
32 #include "ILexer.h"
33 #include "Scintilla.h"
34 #include "ScintillaWidget.h"
35 #ifdef SCI_LEXER
36 #include "SciLexer.h"
37 #endif
38 #include "StringCopy.h"
39 #ifdef SCI_LEXER
40 #include "LexerModule.h"
41 #endif
42 #include "Position.h"
43 #include "SplitVector.h"
44 #include "Partitioning.h"
45 #include "RunStyles.h"
46 #include "ContractionState.h"
47 #include "CellBuffer.h"
48 #include "CallTip.h"
49 #include "KeyMap.h"
50 #include "Indicator.h"
51 #include "XPM.h"
52 #include "LineMarker.h"
53 #include "Style.h"
54 #include "ViewStyle.h"
55 #include "CharClassify.h"
56 #include "Decoration.h"
57 #include "CaseFolder.h"
58 #include "Document.h"
59 #include "CaseConvert.h"
60 #include "UniConversion.h"
61 #include "UnicodeFromUTF8.h"
62 #include "Selection.h"
63 #include "PositionCache.h"
64 #include "EditModel.h"
65 #include "MarginView.h"
66 #include "EditView.h"
67 #include "Editor.h"
68 #include "AutoComplete.h"
69 #include "ScintillaBase.h"
71 #ifdef SCI_LEXER
72 #include "ExternalLexer.h"
73 #endif
75 #include "scintilla-marshal.h"
77 #include "Converter.h"
79 #if defined(__clang__)
80 // Clang 3.0 incorrectly displays sentinel warnings. Fixed by clang 3.1.
81 #pragma GCC diagnostic ignored "-Wsentinel"
82 #endif
84 #if GTK_CHECK_VERSION(2,20,0)
85 #define IS_WIDGET_REALIZED(w) (gtk_widget_get_realized(GTK_WIDGET(w)))
86 #define IS_WIDGET_MAPPED(w) (gtk_widget_get_mapped(GTK_WIDGET(w)))
87 #else
88 #define IS_WIDGET_REALIZED(w) (GTK_WIDGET_REALIZED(w))
89 #define IS_WIDGET_MAPPED(w) (GTK_WIDGET_MAPPED(w))
90 #endif
92 #define SC_INDICATOR_INPUT INDIC_IME
93 #define SC_INDICATOR_TARGET INDIC_IME+1
94 #define SC_INDICATOR_CONVERTED INDIC_IME+2
95 #define SC_INDICATOR_UNKNOWN INDIC_IME_MAX
97 static GdkWindow *WindowFromWidget(GtkWidget *w) {
98 return gtk_widget_get_window(w);
101 #ifdef _MSC_VER
102 // Constant conditional expressions are because of GTK+ headers
103 #pragma warning(disable: 4127)
104 // Ignore unreferenced local functions in GTK+ headers
105 #pragma warning(disable: 4505)
106 #endif
108 #define OBJECT_CLASS GObjectClass
110 #ifdef SCI_NAMESPACE
111 using namespace Scintilla;
112 #endif
114 static GdkWindow *PWindow(const Window &w) {
115 GtkWidget *widget = static_cast<GtkWidget *>(w.GetID());
116 return gtk_widget_get_window(widget);
119 extern std::string UTF8FromLatin1(const char *s, int len);
121 class ScintillaGTK : public ScintillaBase {
122 _ScintillaObject *sci;
123 Window wText;
124 Window scrollbarv;
125 Window scrollbarh;
126 GtkAdjustment *adjustmentv;
127 GtkAdjustment *adjustmenth;
128 int verticalScrollBarWidth;
129 int horizontalScrollBarHeight;
131 SelectionText primary;
133 GdkEventButton *evbtn;
134 bool capturedMouse;
135 bool dragWasDropped;
136 int lastKey;
137 int rectangularSelectionModifier;
139 GtkWidgetClass *parentClass;
141 static GdkAtom atomClipboard;
142 static GdkAtom atomUTF8;
143 static GdkAtom atomString;
144 static GdkAtom atomUriList;
145 static GdkAtom atomDROPFILES_DND;
146 GdkAtom atomSought;
148 #if PLAT_GTK_WIN32
149 CLIPFORMAT cfColumnSelect;
150 #endif
152 Window wPreedit;
153 Window wPreeditDraw;
154 GtkIMContext *im_context;
155 PangoScript lastNonCommonScript;
157 // Wheel mouse support
158 unsigned int linesPerScroll;
159 GTimeVal lastWheelMouseTime;
160 gint lastWheelMouseDirection;
161 gint wheelMouseIntensity;
163 #if GTK_CHECK_VERSION(3,0,0)
164 cairo_rectangle_list_t *rgnUpdate;
165 #else
166 GdkRegion *rgnUpdate;
167 #endif
168 bool repaintFullWindow;
170 // Private so ScintillaGTK objects can not be copied
171 ScintillaGTK(const ScintillaGTK &);
172 ScintillaGTK &operator=(const ScintillaGTK &);
174 public:
175 explicit ScintillaGTK(_ScintillaObject *sci_);
176 virtual ~ScintillaGTK();
177 static void ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class);
178 private:
179 virtual void Initialise();
180 virtual void Finalise();
181 virtual bool AbandonPaint();
182 virtual void DisplayCursor(Window::Cursor c);
183 virtual bool DragThreshold(Point ptStart, Point ptNow);
184 virtual void StartDrag();
185 int TargetAsUTF8(char *text);
186 int EncodedFromUTF8(char *utf8, char *encoded) const;
187 virtual bool ValidCodePage(int codePage) const;
188 public: // Public for scintilla_send_message
189 virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
190 private:
191 virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
192 struct TimeThunk {
193 TickReason reason;
194 ScintillaGTK *scintilla;
195 guint timer;
196 TimeThunk() : reason(tickCaret), scintilla(NULL), timer(0) {}
198 TimeThunk timers[tickDwell+1];
199 virtual bool FineTickerAvailable();
200 virtual bool FineTickerRunning(TickReason reason);
201 virtual void FineTickerStart(TickReason reason, int millis, int tolerance);
202 virtual void FineTickerCancel(TickReason reason);
203 virtual bool SetIdle(bool on);
204 virtual void SetMouseCapture(bool on);
205 virtual bool HaveMouseCapture();
206 virtual bool PaintContains(PRectangle rc);
207 void FullPaint();
208 virtual PRectangle GetClientRectangle() const;
209 virtual void ScrollText(int linesToMove);
210 virtual void SetVerticalScrollPos();
211 virtual void SetHorizontalScrollPos();
212 virtual bool ModifyScrollBars(int nMax, int nPage);
213 void ReconfigureScrollBars();
214 virtual void NotifyChange();
215 virtual void NotifyFocus(bool focus);
216 virtual void NotifyParent(SCNotification scn);
217 void NotifyKey(int key, int modifiers);
218 void NotifyURIDropped(const char *list);
219 const char *CharacterSetID() const;
220 virtual CaseFolder *CaseFolderForEncoding();
221 virtual std::string CaseMapString(const std::string &s, int caseMapping);
222 virtual int KeyDefault(int key, int modifiers);
223 virtual void CopyToClipboard(const SelectionText &selectedText);
224 virtual void Copy();
225 virtual void Paste();
226 virtual void CreateCallTipWindow(PRectangle rc);
227 virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
228 bool OwnPrimarySelection();
229 virtual void ClaimSelection();
230 void GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText);
231 void ReceivedSelection(GtkSelectionData *selection_data);
232 void ReceivedDrop(GtkSelectionData *selection_data);
233 static void GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *selected);
234 void StoreOnClipboard(SelectionText *clipText);
235 static void ClipboardGetSelection(GtkClipboard* clip, GtkSelectionData *selection_data, guint info, void *data);
236 static void ClipboardClearSelection(GtkClipboard* clip, void *data);
238 void UnclaimSelection(GdkEventSelection *selection_event);
239 void Resize(int width, int height);
241 // Callback functions
242 void RealizeThis(GtkWidget *widget);
243 static void Realize(GtkWidget *widget);
244 void UnRealizeThis(GtkWidget *widget);
245 static void UnRealize(GtkWidget *widget);
246 void MapThis();
247 static void Map(GtkWidget *widget);
248 void UnMapThis();
249 static void UnMap(GtkWidget *widget);
250 gint FocusInThis(GtkWidget *widget);
251 static gint FocusIn(GtkWidget *widget, GdkEventFocus *event);
252 gint FocusOutThis(GtkWidget *widget);
253 static gint FocusOut(GtkWidget *widget, GdkEventFocus *event);
254 static void SizeRequest(GtkWidget *widget, GtkRequisition *requisition);
255 #if GTK_CHECK_VERSION(3,0,0)
256 static void GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth);
257 static void GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight);
258 #endif
259 static void SizeAllocate(GtkWidget *widget, GtkAllocation *allocation);
260 #if GTK_CHECK_VERSION(3,0,0)
261 gboolean DrawTextThis(cairo_t *cr);
262 static gboolean DrawText(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
263 gboolean DrawThis(cairo_t *cr);
264 static gboolean DrawMain(GtkWidget *widget, cairo_t *cr);
265 #else
266 gboolean ExposeTextThis(GtkWidget *widget, GdkEventExpose *ose);
267 static gboolean ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
268 gboolean Expose(GtkWidget *widget, GdkEventExpose *ose);
269 static gboolean ExposeMain(GtkWidget *widget, GdkEventExpose *ose);
270 #endif
271 void ForAll(GtkCallback callback, gpointer callback_data);
272 static void MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data);
274 static void ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
275 static void ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
276 gint PressThis(GdkEventButton *event);
277 static gint Press(GtkWidget *widget, GdkEventButton *event);
278 static gint MouseRelease(GtkWidget *widget, GdkEventButton *event);
279 static gint ScrollEvent(GtkWidget *widget, GdkEventScroll *event);
280 static gint Motion(GtkWidget *widget, GdkEventMotion *event);
281 gboolean KeyThis(GdkEventKey *event);
282 static gboolean KeyPress(GtkWidget *widget, GdkEventKey *event);
283 static gboolean KeyRelease(GtkWidget *widget, GdkEventKey *event);
284 #if GTK_CHECK_VERSION(3,0,0)
285 gboolean DrawPreeditThis(GtkWidget *widget, cairo_t *cr);
286 static gboolean DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
287 #else
288 gboolean ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose);
289 static gboolean ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
290 #endif
292 bool KoreanIME();
293 void CommitThis(char *str);
294 static void Commit(GtkIMContext *context, char *str, ScintillaGTK *sciThis);
295 void PreeditChangedInlineThis();
296 void PreeditChangedWindowedThis();
297 static void PreeditChanged(GtkIMContext *context, ScintillaGTK *sciThis);
298 void MoveImeCarets(int pos);
299 void DrawImeIndicator(int indicator, int len);
300 void SetCandidateWindowPos();
302 static void StyleSetText(GtkWidget *widget, GtkStyle *previous, void*);
303 static void RealizeText(GtkWidget *widget, void*);
304 static void Dispose(GObject *object);
305 static void Destroy(GObject *object);
306 static void SelectionReceived(GtkWidget *widget, GtkSelectionData *selection_data,
307 guint time);
308 static void ClipboardReceived(GtkClipboard *clipboard, GtkSelectionData *selection_data,
309 gpointer data);
310 static void SelectionGet(GtkWidget *widget, GtkSelectionData *selection_data,
311 guint info, guint time);
312 static gint SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event);
313 gboolean DragMotionThis(GdkDragContext *context, gint x, gint y, guint dragtime);
314 static gboolean DragMotion(GtkWidget *widget, GdkDragContext *context,
315 gint x, gint y, guint dragtime);
316 static void DragLeave(GtkWidget *widget, GdkDragContext *context,
317 guint time);
318 static void DragEnd(GtkWidget *widget, GdkDragContext *context);
319 static gboolean Drop(GtkWidget *widget, GdkDragContext *context,
320 gint x, gint y, guint time);
321 static void DragDataReceived(GtkWidget *widget, GdkDragContext *context,
322 gint x, gint y, GtkSelectionData *selection_data, guint info, guint time);
323 static void DragDataGet(GtkWidget *widget, GdkDragContext *context,
324 GtkSelectionData *selection_data, guint info, guint time);
325 static gboolean TimeOut(gpointer ptt);
326 static gboolean IdleCallback(gpointer pSci);
327 static gboolean StyleIdle(gpointer pSci);
328 virtual void QueueIdleWork(WorkNeeded::workItems items, int upTo);
329 static void PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis);
331 #if GTK_CHECK_VERSION(3,0,0)
332 static gboolean DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip);
333 #else
334 static gboolean ExposeCT(GtkWidget *widget, GdkEventExpose *ose, CallTip *ct);
335 #endif
336 static gboolean PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis);
338 static sptr_t DirectFunction(sptr_t ptr,
339 unsigned int iMessage, uptr_t wParam, sptr_t lParam);
342 enum {
343 COMMAND_SIGNAL,
344 NOTIFY_SIGNAL,
345 LAST_SIGNAL
348 static gint scintilla_signals[LAST_SIGNAL] = { 0 };
350 enum {
351 TARGET_STRING,
352 TARGET_TEXT,
353 TARGET_COMPOUND_TEXT,
354 TARGET_UTF8_STRING,
355 TARGET_URI
358 GdkAtom ScintillaGTK::atomClipboard = 0;
359 GdkAtom ScintillaGTK::atomUTF8 = 0;
360 GdkAtom ScintillaGTK::atomString = 0;
361 GdkAtom ScintillaGTK::atomUriList = 0;
362 GdkAtom ScintillaGTK::atomDROPFILES_DND = 0;
364 static const GtkTargetEntry clipboardCopyTargets[] = {
365 { (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
366 { (gchar *) "STRING", 0, TARGET_STRING },
368 static const gint nClipboardCopyTargets = ELEMENTS(clipboardCopyTargets);
370 static const GtkTargetEntry clipboardPasteTargets[] = {
371 { (gchar *) "text/uri-list", 0, TARGET_URI },
372 { (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
373 { (gchar *) "STRING", 0, TARGET_STRING },
375 static const gint nClipboardPasteTargets = ELEMENTS(clipboardPasteTargets);
377 static GtkWidget *PWidget(Window &w) {
378 return static_cast<GtkWidget *>(w.GetID());
381 static ScintillaGTK *ScintillaFromWidget(GtkWidget *widget) {
382 ScintillaObject *scio = SCINTILLA(widget);
383 return static_cast<ScintillaGTK *>(scio->pscin);
386 ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) :
387 adjustmentv(0), adjustmenth(0),
388 verticalScrollBarWidth(30), horizontalScrollBarHeight(30),
389 evbtn(0), capturedMouse(false), dragWasDropped(false),
390 lastKey(0), rectangularSelectionModifier(SCMOD_CTRL), parentClass(0),
391 im_context(NULL), lastNonCommonScript(PANGO_SCRIPT_INVALID_CODE),
392 lastWheelMouseDirection(0),
393 wheelMouseIntensity(0),
394 rgnUpdate(0),
395 repaintFullWindow(false) {
396 sci = sci_;
397 wMain = GTK_WIDGET(sci);
399 #if PLAT_GTK_WIN32
400 rectangularSelectionModifier = SCMOD_ALT;
401 #else
402 rectangularSelectionModifier = SCMOD_CTRL;
403 #endif
405 #if PLAT_GTK_WIN32
406 // There does not seem to be a real standard for indicating that the clipboard
407 // contains a rectangular selection, so copy Developer Studio.
408 cfColumnSelect = static_cast<CLIPFORMAT>(
409 ::RegisterClipboardFormat("MSDEVColumnSelect"));
411 // Get intellimouse parameters when running on win32; otherwise use
412 // reasonable default
413 #ifndef SPI_GETWHEELSCROLLLINES
414 #define SPI_GETWHEELSCROLLLINES 104
415 #endif
416 ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
417 #else
418 linesPerScroll = 4;
419 #endif
420 lastWheelMouseTime.tv_sec = 0;
421 lastWheelMouseTime.tv_usec = 0;
423 Initialise();
426 ScintillaGTK::~ScintillaGTK() {
427 g_source_remove_by_user_data(this);
428 if (evbtn) {
429 gdk_event_free(reinterpret_cast<GdkEvent *>(evbtn));
430 evbtn = 0;
432 wPreedit.Destroy();
435 static void UnRefCursor(GdkCursor *cursor) {
436 #if GTK_CHECK_VERSION(3,0,0)
437 g_object_unref(cursor);
438 #else
439 gdk_cursor_unref(cursor);
440 #endif
443 void ScintillaGTK::RealizeThis(GtkWidget *widget) {
444 //Platform::DebugPrintf("ScintillaGTK::realize this\n");
445 #if GTK_CHECK_VERSION(2,20,0)
446 gtk_widget_set_realized(widget, TRUE);
447 #else
448 GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
449 #endif
450 GdkWindowAttr attrs;
451 attrs.window_type = GDK_WINDOW_CHILD;
452 GtkAllocation allocation;
453 gtk_widget_get_allocation(widget, &allocation);
454 attrs.x = allocation.x;
455 attrs.y = allocation.y;
456 attrs.width = allocation.width;
457 attrs.height = allocation.height;
458 attrs.wclass = GDK_INPUT_OUTPUT;
459 attrs.visual = gtk_widget_get_visual(widget);
460 #if !GTK_CHECK_VERSION(3,0,0)
461 attrs.colormap = gtk_widget_get_colormap(widget);
462 #endif
463 attrs.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
464 GdkDisplay *pdisplay = gtk_widget_get_display(widget);
465 GdkCursor *cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
466 attrs.cursor = cursor;
467 #if GTK_CHECK_VERSION(3,0,0)
468 gtk_widget_set_window(widget, gdk_window_new(gtk_widget_get_parent_window(widget), &attrs,
469 GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_CURSOR));
470 #if GTK_CHECK_VERSION(3,8,0)
471 gtk_widget_register_window(widget, gtk_widget_get_window(widget));
472 #else
473 gdk_window_set_user_data(gtk_widget_get_window(widget), widget);
474 #endif
475 gtk_style_context_set_background(gtk_widget_get_style_context(widget),
476 gtk_widget_get_window(widget));
477 gdk_window_show(gtk_widget_get_window(widget));
478 UnRefCursor(cursor);
479 #else
480 widget->window = gdk_window_new(gtk_widget_get_parent_window(widget), &attrs,
481 GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP | GDK_WA_CURSOR);
482 gdk_window_set_user_data(widget->window, widget);
483 widget->style = gtk_style_attach(widget->style, widget->window);
484 gdk_window_set_background(widget->window, &widget->style->bg[GTK_STATE_NORMAL]);
485 gdk_window_show(widget->window);
486 UnRefCursor(cursor);
487 #endif
488 gtk_widget_realize(PWidget(wPreedit));
489 gtk_widget_realize(PWidget(wPreeditDraw));
491 im_context = gtk_im_multicontext_new();
492 g_signal_connect(G_OBJECT(im_context), "commit",
493 G_CALLBACK(Commit), this);
494 g_signal_connect(G_OBJECT(im_context), "preedit_changed",
495 G_CALLBACK(PreeditChanged), this);
496 gtk_im_context_set_client_window(im_context, WindowFromWidget(widget));
497 GtkWidget *widtxt = PWidget(wText); // // No code inside the G_OBJECT macro
498 g_signal_connect_after(G_OBJECT(widtxt), "style_set",
499 G_CALLBACK(ScintillaGTK::StyleSetText), NULL);
500 g_signal_connect_after(G_OBJECT(widtxt), "realize",
501 G_CALLBACK(ScintillaGTK::RealizeText), NULL);
502 gtk_widget_realize(widtxt);
503 gtk_widget_realize(PWidget(scrollbarv));
504 gtk_widget_realize(PWidget(scrollbarh));
506 cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
507 gdk_window_set_cursor(PWindow(wText), cursor);
508 UnRefCursor(cursor);
510 cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
511 gdk_window_set_cursor(PWindow(scrollbarv), cursor);
512 UnRefCursor(cursor);
514 cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
515 gdk_window_set_cursor(PWindow(scrollbarh), cursor);
516 UnRefCursor(cursor);
518 gtk_selection_add_targets(widget, GDK_SELECTION_PRIMARY,
519 clipboardCopyTargets, nClipboardCopyTargets);
522 void ScintillaGTK::Realize(GtkWidget *widget) {
523 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
524 sciThis->RealizeThis(widget);
527 void ScintillaGTK::UnRealizeThis(GtkWidget *widget) {
528 try {
529 gtk_selection_clear_targets(widget, GDK_SELECTION_PRIMARY);
531 if (IS_WIDGET_MAPPED(widget)) {
532 gtk_widget_unmap(widget);
534 #if GTK_CHECK_VERSION(2,20,0)
535 gtk_widget_set_realized(widget, FALSE);
536 #else
537 GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
538 #endif
539 gtk_widget_unrealize(PWidget(wText));
540 gtk_widget_unrealize(PWidget(scrollbarv));
541 gtk_widget_unrealize(PWidget(scrollbarh));
542 gtk_widget_unrealize(PWidget(wPreedit));
543 gtk_widget_unrealize(PWidget(wPreeditDraw));
544 g_object_unref(im_context);
545 im_context = NULL;
546 if (GTK_WIDGET_CLASS(parentClass)->unrealize)
547 GTK_WIDGET_CLASS(parentClass)->unrealize(widget);
549 Finalise();
550 } catch (...) {
551 errorStatus = SC_STATUS_FAILURE;
555 void ScintillaGTK::UnRealize(GtkWidget *widget) {
556 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
557 sciThis->UnRealizeThis(widget);
560 static void MapWidget(GtkWidget *widget) {
561 if (widget &&
562 gtk_widget_get_visible(GTK_WIDGET(widget)) &&
563 !IS_WIDGET_MAPPED(widget)) {
564 gtk_widget_map(widget);
568 void ScintillaGTK::MapThis() {
569 try {
570 //Platform::DebugPrintf("ScintillaGTK::map this\n");
571 #if GTK_CHECK_VERSION(2,20,0)
572 gtk_widget_set_mapped(PWidget(wMain), TRUE);
573 #else
574 GTK_WIDGET_SET_FLAGS(PWidget(wMain), GTK_MAPPED);
575 #endif
576 MapWidget(PWidget(wText));
577 MapWidget(PWidget(scrollbarh));
578 MapWidget(PWidget(scrollbarv));
579 wMain.SetCursor(Window::cursorArrow);
580 scrollbarv.SetCursor(Window::cursorArrow);
581 scrollbarh.SetCursor(Window::cursorArrow);
582 ChangeSize();
583 gdk_window_show(PWindow(wMain));
584 } catch (...) {
585 errorStatus = SC_STATUS_FAILURE;
589 void ScintillaGTK::Map(GtkWidget *widget) {
590 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
591 sciThis->MapThis();
594 void ScintillaGTK::UnMapThis() {
595 try {
596 //Platform::DebugPrintf("ScintillaGTK::unmap this\n");
597 #if GTK_CHECK_VERSION(2,20,0)
598 gtk_widget_set_mapped(PWidget(wMain), FALSE);
599 #else
600 GTK_WIDGET_UNSET_FLAGS(PWidget(wMain), GTK_MAPPED);
601 #endif
602 DropGraphics(false);
603 gdk_window_hide(PWindow(wMain));
604 gtk_widget_unmap(PWidget(wText));
605 gtk_widget_unmap(PWidget(scrollbarh));
606 gtk_widget_unmap(PWidget(scrollbarv));
607 } catch (...) {
608 errorStatus = SC_STATUS_FAILURE;
612 void ScintillaGTK::UnMap(GtkWidget *widget) {
613 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
614 sciThis->UnMapThis();
617 void ScintillaGTK::ForAll(GtkCallback callback, gpointer callback_data) {
618 try {
619 (*callback) (PWidget(wText), callback_data);
620 if (PWidget(scrollbarv))
621 (*callback) (PWidget(scrollbarv), callback_data);
622 if (PWidget(scrollbarh))
623 (*callback) (PWidget(scrollbarh), callback_data);
624 } catch (...) {
625 errorStatus = SC_STATUS_FAILURE;
629 void ScintillaGTK::MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data) {
630 ScintillaGTK *sciThis = ScintillaFromWidget((GtkWidget *)container);
632 if (callback != NULL && include_internals) {
633 sciThis->ForAll(callback, callback_data);
637 namespace {
639 class PreEditString {
640 public:
641 gchar *str;
642 gint cursor_pos;
643 PangoAttrList *attrs;
644 gboolean validUTF8;
645 glong uniStrLen;
646 gunichar *uniStr;
647 PangoScript pscript;
649 explicit PreEditString(GtkIMContext *im_context) {
650 gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
651 validUTF8 = g_utf8_validate(str, strlen(str), NULL);
652 uniStr = g_utf8_to_ucs4_fast(str, strlen(str), &uniStrLen);
653 pscript = pango_script_for_unichar(uniStr[0]);
655 ~PreEditString() {
656 g_free(str);
657 g_free(uniStr);
658 pango_attr_list_unref(attrs);
664 gint ScintillaGTK::FocusInThis(GtkWidget *widget) {
665 try {
666 SetFocusState(true);
667 if (im_context != NULL) {
668 PreEditString pes(im_context);
669 if (PWidget(wPreedit) != NULL) {
670 if (strlen(pes.str) > 0) {
671 gtk_widget_show(PWidget(wPreedit));
672 } else {
673 gtk_widget_hide(PWidget(wPreedit));
676 gtk_im_context_focus_in(im_context);
679 } catch (...) {
680 errorStatus = SC_STATUS_FAILURE;
682 return FALSE;
685 gint ScintillaGTK::FocusIn(GtkWidget *widget, GdkEventFocus * /*event*/) {
686 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
687 return sciThis->FocusInThis(widget);
690 gint ScintillaGTK::FocusOutThis(GtkWidget *widget) {
691 try {
692 SetFocusState(false);
694 if (PWidget(wPreedit) != NULL)
695 gtk_widget_hide(PWidget(wPreedit));
696 if (im_context != NULL)
697 gtk_im_context_focus_out(im_context);
699 } catch (...) {
700 errorStatus = SC_STATUS_FAILURE;
702 return FALSE;
705 gint ScintillaGTK::FocusOut(GtkWidget *widget, GdkEventFocus * /*event*/) {
706 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
707 return sciThis->FocusOutThis(widget);
710 void ScintillaGTK::SizeRequest(GtkWidget *widget, GtkRequisition *requisition) {
711 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
712 requisition->width = 1;
713 requisition->height = 1;
714 GtkRequisition child_requisition;
715 #if GTK_CHECK_VERSION(3,0,0)
716 gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarh), NULL, &child_requisition);
717 gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarv), NULL, &child_requisition);
718 #else
719 gtk_widget_size_request(PWidget(sciThis->scrollbarh), &child_requisition);
720 gtk_widget_size_request(PWidget(sciThis->scrollbarv), &child_requisition);
721 #endif
724 #if GTK_CHECK_VERSION(3,0,0)
726 void ScintillaGTK::GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth) {
727 GtkRequisition requisition;
728 SizeRequest(widget, &requisition);
729 *minimalWidth = *naturalWidth = requisition.width;
732 void ScintillaGTK::GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight) {
733 GtkRequisition requisition;
734 SizeRequest(widget, &requisition);
735 *minimalHeight = *naturalHeight = requisition.height;
738 #endif
740 void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) {
741 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
742 try {
743 gtk_widget_set_allocation(widget, allocation);
744 if (IS_WIDGET_REALIZED(widget))
745 gdk_window_move_resize(WindowFromWidget(widget),
746 allocation->x,
747 allocation->y,
748 allocation->width,
749 allocation->height);
751 sciThis->Resize(allocation->width, allocation->height);
753 } catch (...) {
754 sciThis->errorStatus = SC_STATUS_FAILURE;
758 void ScintillaGTK::Initialise() {
759 //Platform::DebugPrintf("ScintillaGTK::Initialise\n");
760 parentClass = reinterpret_cast<GtkWidgetClass *>(
761 g_type_class_ref(gtk_container_get_type()));
763 gtk_widget_set_can_focus(PWidget(wMain), TRUE);
764 gtk_widget_set_sensitive(PWidget(wMain), TRUE);
765 gtk_widget_set_events(PWidget(wMain),
766 GDK_EXPOSURE_MASK
767 | GDK_SCROLL_MASK
768 | GDK_STRUCTURE_MASK
769 | GDK_KEY_PRESS_MASK
770 | GDK_KEY_RELEASE_MASK
771 | GDK_FOCUS_CHANGE_MASK
772 | GDK_LEAVE_NOTIFY_MASK
773 | GDK_BUTTON_PRESS_MASK
774 | GDK_BUTTON_RELEASE_MASK
775 | GDK_POINTER_MOTION_MASK
776 | GDK_POINTER_MOTION_HINT_MASK);
778 wText = gtk_drawing_area_new();
779 gtk_widget_set_parent(PWidget(wText), PWidget(wMain));
780 GtkWidget *widtxt = PWidget(wText); // No code inside the G_OBJECT macro
781 gtk_widget_show(widtxt);
782 #if GTK_CHECK_VERSION(3,0,0)
783 g_signal_connect(G_OBJECT(widtxt), "draw",
784 G_CALLBACK(ScintillaGTK::DrawText), this);
785 #else
786 g_signal_connect(G_OBJECT(widtxt), "expose_event",
787 G_CALLBACK(ScintillaGTK::ExposeText), this);
788 #endif
789 #if GTK_CHECK_VERSION(3,0,0)
790 // we need a runtime check because we don't want double buffering when
791 // running on >= 3.9.2
792 if (gtk_check_version(3,9,2) != NULL /* on < 3.9.2 */)
793 #endif
795 #if !GTK_CHECK_VERSION(3,14,0)
796 // Avoid background drawing flash/missing redraws
797 gtk_widget_set_double_buffered(widtxt, FALSE);
798 #endif
800 gtk_widget_set_events(widtxt, GDK_EXPOSURE_MASK);
801 gtk_widget_set_size_request(widtxt, 100, 100);
802 adjustmentv = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 201.0, 1.0, 20.0, 20.0));
803 #if GTK_CHECK_VERSION(3,0,0)
804 scrollbarv = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT(adjustmentv));
805 #else
806 scrollbarv = gtk_vscrollbar_new(GTK_ADJUSTMENT(adjustmentv));
807 #endif
808 gtk_widget_set_can_focus(PWidget(scrollbarv), FALSE);
809 g_signal_connect(G_OBJECT(adjustmentv), "value_changed",
810 G_CALLBACK(ScrollSignal), this);
811 gtk_widget_set_parent(PWidget(scrollbarv), PWidget(wMain));
812 gtk_widget_show(PWidget(scrollbarv));
814 adjustmenth = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 101.0, 1.0, 20.0, 20.0));
815 #if GTK_CHECK_VERSION(3,0,0)
816 scrollbarh = gtk_scrollbar_new(GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT(adjustmenth));
817 #else
818 scrollbarh = gtk_hscrollbar_new(GTK_ADJUSTMENT(adjustmenth));
819 #endif
820 gtk_widget_set_can_focus(PWidget(scrollbarh), FALSE);
821 g_signal_connect(G_OBJECT(adjustmenth), "value_changed",
822 G_CALLBACK(ScrollHSignal), this);
823 gtk_widget_set_parent(PWidget(scrollbarh), PWidget(wMain));
824 gtk_widget_show(PWidget(scrollbarh));
826 gtk_widget_grab_focus(PWidget(wMain));
828 gtk_drag_dest_set(GTK_WIDGET(PWidget(wMain)),
829 GTK_DEST_DEFAULT_ALL, clipboardPasteTargets, nClipboardPasteTargets,
830 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE));
832 /* create pre-edit window */
833 wPreedit = gtk_window_new(GTK_WINDOW_POPUP);
834 wPreeditDraw = gtk_drawing_area_new();
835 GtkWidget *predrw = PWidget(wPreeditDraw); // No code inside the G_OBJECT macro
836 #if GTK_CHECK_VERSION(3,0,0)
837 g_signal_connect(G_OBJECT(predrw), "draw",
838 G_CALLBACK(DrawPreedit), this);
839 #else
840 g_signal_connect(G_OBJECT(predrw), "expose_event",
841 G_CALLBACK(ExposePreedit), this);
842 #endif
843 gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw);
844 gtk_widget_show(predrw);
846 // Set caret period based on GTK settings
847 gboolean blinkOn = false;
848 if (g_object_class_find_property(G_OBJECT_GET_CLASS(
849 G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink")) {
850 g_object_get(G_OBJECT(
851 gtk_settings_get_default()), "gtk-cursor-blink", &blinkOn, NULL);
853 if (blinkOn &&
854 g_object_class_find_property(G_OBJECT_GET_CLASS(
855 G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink-time")) {
856 gint value;
857 g_object_get(G_OBJECT(
858 gtk_settings_get_default()), "gtk-cursor-blink-time", &value, NULL);
859 caret.period = gint(value / 1.75);
860 } else {
861 caret.period = 0;
864 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
865 timers[tr].reason = tr;
866 timers[tr].scintilla = this;
868 vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
869 vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
870 vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
871 vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
874 void ScintillaGTK::Finalise() {
875 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
876 FineTickerCancel(tr);
878 ScintillaBase::Finalise();
881 bool ScintillaGTK::AbandonPaint() {
882 if ((paintState == painting) && !paintingAllText) {
883 repaintFullWindow = true;
885 return false;
888 void ScintillaGTK::DisplayCursor(Window::Cursor c) {
889 if (cursorMode == SC_CURSORNORMAL)
890 wText.SetCursor(c);
891 else
892 wText.SetCursor(static_cast<Window::Cursor>(cursorMode));
895 bool ScintillaGTK::DragThreshold(Point ptStart, Point ptNow) {
896 return gtk_drag_check_threshold(GTK_WIDGET(PWidget(wMain)),
897 ptStart.x, ptStart.y, ptNow.x, ptNow.y);
900 void ScintillaGTK::StartDrag() {
901 PLATFORM_ASSERT(evbtn != 0);
902 dragWasDropped = false;
903 inDragDrop = ddDragging;
904 GtkTargetList *tl = gtk_target_list_new(clipboardCopyTargets, nClipboardCopyTargets);
905 #if GTK_CHECK_VERSION(3,10,0)
906 gtk_drag_begin_with_coordinates(GTK_WIDGET(PWidget(wMain)),
908 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
909 evbtn->button,
910 reinterpret_cast<GdkEvent *>(evbtn),
911 -1, -1);
912 #else
913 gtk_drag_begin(GTK_WIDGET(PWidget(wMain)),
915 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
916 evbtn->button,
917 reinterpret_cast<GdkEvent *>(evbtn));
918 #endif
921 static std::string ConvertText(const char *s, size_t len, const char *charSetDest,
922 const char *charSetSource, bool transliterations, bool silent=false) {
923 // s is not const because of different versions of iconv disagreeing about const
924 std::string destForm;
925 Converter conv(charSetDest, charSetSource, transliterations);
926 if (conv) {
927 size_t outLeft = len*3+1;
928 destForm = std::string(outLeft, '\0');
929 // g_iconv does not actually write to its input argument so safe to cast away const
930 char *pin = const_cast<char *>(s);
931 size_t inLeft = len;
932 char *putf = &destForm[0];
933 char *pout = putf;
934 size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
935 if (conversions == ((size_t)(-1))) {
936 if (!silent) {
937 if (len == 1)
938 fprintf(stderr, "iconv %s->%s failed for %0x '%s'\n",
939 charSetSource, charSetDest, (unsigned char)(*s), s);
940 else
941 fprintf(stderr, "iconv %s->%s failed for %s\n",
942 charSetSource, charSetDest, s);
944 destForm = std::string();
945 } else {
946 destForm.resize(pout - putf);
948 } else {
949 fprintf(stderr, "Can not iconv %s %s\n", charSetDest, charSetSource);
951 return destForm;
954 // Returns the target converted to UTF8.
955 // Return the length in bytes.
956 int ScintillaGTK::TargetAsUTF8(char *text) {
957 int targetLength = targetEnd - targetStart;
958 if (IsUnicodeMode()) {
959 if (text) {
960 pdoc->GetCharRange(text, targetStart, targetLength);
962 } else {
963 // Need to convert
964 const char *charSetBuffer = CharacterSetID();
965 if (*charSetBuffer) {
966 std::string s = RangeText(targetStart, targetEnd);
967 std::string tmputf = ConvertText(&s[0], targetLength, "UTF-8", charSetBuffer, false);
968 if (text) {
969 memcpy(text, tmputf.c_str(), tmputf.length());
971 return tmputf.length();
972 } else {
973 if (text) {
974 pdoc->GetCharRange(text, targetStart, targetLength);
978 return targetLength;
981 // Translates a nul terminated UTF8 string into the document encoding.
982 // Return the length of the result in bytes.
983 int ScintillaGTK::EncodedFromUTF8(char *utf8, char *encoded) const {
984 int inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8);
985 if (IsUnicodeMode()) {
986 if (encoded) {
987 memcpy(encoded, utf8, inputLength);
989 return inputLength;
990 } else {
991 // Need to convert
992 const char *charSetBuffer = CharacterSetID();
993 if (*charSetBuffer) {
994 std::string tmpEncoded = ConvertText(utf8, inputLength, charSetBuffer, "UTF-8", true);
995 if (encoded) {
996 memcpy(encoded, tmpEncoded.c_str(), tmpEncoded.length());
998 return tmpEncoded.length();
999 } else {
1000 if (encoded) {
1001 memcpy(encoded, utf8, inputLength);
1003 return inputLength;
1006 // Fail
1007 return 0;
1010 bool ScintillaGTK::ValidCodePage(int codePage) const {
1011 return codePage == 0
1012 || codePage == SC_CP_UTF8
1013 || codePage == 932
1014 || codePage == 936
1015 || codePage == 949
1016 || codePage == 950
1017 || codePage == 1361;
1020 sptr_t ScintillaGTK::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
1021 try {
1022 switch (iMessage) {
1024 case SCI_GRABFOCUS:
1025 gtk_widget_grab_focus(PWidget(wMain));
1026 break;
1028 case SCI_GETDIRECTFUNCTION:
1029 return reinterpret_cast<sptr_t>(DirectFunction);
1031 case SCI_GETDIRECTPOINTER:
1032 return reinterpret_cast<sptr_t>(this);
1034 #ifdef SCI_LEXER
1035 case SCI_LOADLEXERLIBRARY:
1036 LexerManager::GetInstance()->Load(reinterpret_cast<const char*>(lParam));
1037 break;
1038 #endif
1039 case SCI_TARGETASUTF8:
1040 return TargetAsUTF8(reinterpret_cast<char*>(lParam));
1042 case SCI_ENCODEDFROMUTF8:
1043 return EncodedFromUTF8(reinterpret_cast<char*>(wParam),
1044 reinterpret_cast<char*>(lParam));
1046 case SCI_SETRECTANGULARSELECTIONMODIFIER:
1047 rectangularSelectionModifier = wParam;
1048 break;
1050 case SCI_GETRECTANGULARSELECTIONMODIFIER:
1051 return rectangularSelectionModifier;
1053 default:
1054 return ScintillaBase::WndProc(iMessage, wParam, lParam);
1056 } catch (std::bad_alloc&) {
1057 errorStatus = SC_STATUS_BADALLOC;
1058 } catch (...) {
1059 errorStatus = SC_STATUS_FAILURE;
1061 return 0l;
1064 sptr_t ScintillaGTK::DefWndProc(unsigned int, uptr_t, sptr_t) {
1065 return 0;
1069 * Report that this Editor subclass has a working implementation of FineTickerStart.
1071 bool ScintillaGTK::FineTickerAvailable() {
1072 return true;
1075 bool ScintillaGTK::FineTickerRunning(TickReason reason) {
1076 return timers[reason].timer != 0;
1079 void ScintillaGTK::FineTickerStart(TickReason reason, int millis, int /* tolerance */) {
1080 FineTickerCancel(reason);
1081 timers[reason].timer = gdk_threads_add_timeout(millis, TimeOut, &timers[reason]);
1084 void ScintillaGTK::FineTickerCancel(TickReason reason) {
1085 if (timers[reason].timer) {
1086 g_source_remove(timers[reason].timer);
1087 timers[reason].timer = 0;
1091 bool ScintillaGTK::SetIdle(bool on) {
1092 if (on) {
1093 // Start idler, if it's not running.
1094 if (!idler.state) {
1095 idler.state = true;
1096 idler.idlerID = reinterpret_cast<IdlerID>(
1097 gdk_threads_add_idle_full(G_PRIORITY_DEFAULT_IDLE, IdleCallback, this, NULL));
1099 } else {
1100 // Stop idler, if it's running
1101 if (idler.state) {
1102 idler.state = false;
1103 g_source_remove(GPOINTER_TO_UINT(idler.idlerID));
1106 return true;
1109 void ScintillaGTK::SetMouseCapture(bool on) {
1110 if (mouseDownCaptures) {
1111 if (on) {
1112 gtk_grab_add(GTK_WIDGET(PWidget(wMain)));
1113 } else {
1114 gtk_grab_remove(GTK_WIDGET(PWidget(wMain)));
1117 capturedMouse = on;
1120 bool ScintillaGTK::HaveMouseCapture() {
1121 return capturedMouse;
1124 #if GTK_CHECK_VERSION(3,0,0)
1126 // Is crcTest completely in crcContainer?
1127 static bool CRectContains(const cairo_rectangle_t &crcContainer, const cairo_rectangle_t &crcTest) {
1128 return
1129 (crcTest.x >= crcContainer.x) && ((crcTest.x + crcTest.width) <= (crcContainer.x + crcContainer.width)) &&
1130 (crcTest.y >= crcContainer.y) && ((crcTest.y + crcTest.height) <= (crcContainer.y + crcContainer.height));
1133 // Is crcTest completely in crcListContainer?
1134 // May incorrectly return false if complex shape
1135 static bool CRectListContains(const cairo_rectangle_list_t *crcListContainer, const cairo_rectangle_t &crcTest) {
1136 for (int r=0; r<crcListContainer->num_rectangles; r++) {
1137 if (CRectContains(crcListContainer->rectangles[r], crcTest))
1138 return true;
1140 return false;
1143 #endif
1145 bool ScintillaGTK::PaintContains(PRectangle rc) {
1146 // This allows optimization when a rectangle is completely in the update region.
1147 // It is OK to return false when too difficult to determine as that just performs extra drawing
1148 bool contains = true;
1149 if (paintState == painting) {
1150 if (!rcPaint.Contains(rc)) {
1151 contains = false;
1152 } else if (rgnUpdate) {
1153 #if GTK_CHECK_VERSION(3,0,0)
1154 cairo_rectangle_t grc = {rc.left, rc.top,
1155 rc.right - rc.left, rc.bottom - rc.top};
1156 contains = CRectListContains(rgnUpdate, grc);
1157 #else
1158 GdkRectangle grc = {static_cast<gint>(rc.left), static_cast<gint>(rc.top),
1159 static_cast<gint>(rc.right - rc.left), static_cast<gint>(rc.bottom - rc.top)};
1160 if (gdk_region_rect_in(rgnUpdate, &grc) != GDK_OVERLAP_RECTANGLE_IN) {
1161 contains = false;
1163 #endif
1166 return contains;
1169 // Redraw all of text area. This paint will not be abandoned.
1170 void ScintillaGTK::FullPaint() {
1171 wText.InvalidateAll();
1174 PRectangle ScintillaGTK::GetClientRectangle() const {
1175 Window &win = const_cast<Window &>(wMain);
1176 PRectangle rc = win.GetClientPosition();
1177 if (verticalScrollBarVisible)
1178 rc.right -= verticalScrollBarWidth;
1179 if (horizontalScrollBarVisible && !Wrapping())
1180 rc.bottom -= horizontalScrollBarHeight;
1181 // Move to origin
1182 rc.right -= rc.left;
1183 rc.bottom -= rc.top;
1184 if (rc.bottom < 0)
1185 rc.bottom = 0;
1186 if (rc.right < 0)
1187 rc.right = 0;
1188 rc.left = 0;
1189 rc.top = 0;
1190 return rc;
1193 void ScintillaGTK::ScrollText(int linesToMove) {
1194 int diff = vs.lineHeight * -linesToMove;
1195 //Platform::DebugPrintf("ScintillaGTK::ScrollText %d %d %0d,%0d %0d,%0d\n", linesToMove, diff,
1196 // rc.left, rc.top, rc.right, rc.bottom);
1197 GtkWidget *wi = PWidget(wText);
1198 NotifyUpdateUI();
1200 if (IS_WIDGET_REALIZED(wi)) {
1201 gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
1202 gdk_window_process_updates(WindowFromWidget(wi), FALSE);
1206 void ScintillaGTK::SetVerticalScrollPos() {
1207 DwellEnd(true);
1208 gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmentv), topLine);
1211 void ScintillaGTK::SetHorizontalScrollPos() {
1212 DwellEnd(true);
1213 gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset);
1216 bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) {
1217 bool modified = false;
1218 int pageScroll = LinesToScroll();
1220 if (gtk_adjustment_get_upper(adjustmentv) != (nMax + 1) ||
1221 gtk_adjustment_get_page_size(adjustmentv) != nPage ||
1222 gtk_adjustment_get_page_increment(adjustmentv) != pageScroll) {
1223 gtk_adjustment_set_upper(adjustmentv, nMax + 1);
1224 gtk_adjustment_set_page_size(adjustmentv, nPage);
1225 gtk_adjustment_set_page_increment(adjustmentv, pageScroll);
1226 gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv));
1227 modified = true;
1230 PRectangle rcText = GetTextRectangle();
1231 int horizEndPreferred = scrollWidth;
1232 if (horizEndPreferred < 0)
1233 horizEndPreferred = 0;
1234 unsigned int pageWidth = rcText.Width();
1235 unsigned int pageIncrement = pageWidth / 3;
1236 unsigned int charWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
1237 if (gtk_adjustment_get_upper(adjustmenth) != horizEndPreferred ||
1238 gtk_adjustment_get_page_size(adjustmenth) != pageWidth ||
1239 gtk_adjustment_get_page_increment(adjustmenth) != pageIncrement ||
1240 gtk_adjustment_get_step_increment(adjustmenth) != charWidth) {
1241 gtk_adjustment_set_upper(adjustmenth, horizEndPreferred);
1242 gtk_adjustment_set_page_size(adjustmenth, pageWidth);
1243 gtk_adjustment_set_page_increment(adjustmenth, pageIncrement);
1244 gtk_adjustment_set_step_increment(adjustmenth, charWidth);
1245 gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth));
1246 modified = true;
1248 if (modified && (paintState == painting)) {
1249 repaintFullWindow = true;
1252 return modified;
1255 void ScintillaGTK::ReconfigureScrollBars() {
1256 PRectangle rc = wMain.GetClientPosition();
1257 Resize(rc.Width(), rc.Height());
1260 void ScintillaGTK::NotifyChange() {
1261 g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1262 Platform::LongFromTwoShorts(GetCtrlID(), SCEN_CHANGE), PWidget(wMain));
1265 void ScintillaGTK::NotifyFocus(bool focus) {
1266 g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1267 Platform::LongFromTwoShorts
1268 (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), PWidget(wMain));
1269 Editor::NotifyFocus(focus);
1272 void ScintillaGTK::NotifyParent(SCNotification scn) {
1273 scn.nmhdr.hwndFrom = PWidget(wMain);
1274 scn.nmhdr.idFrom = GetCtrlID();
1275 g_signal_emit(G_OBJECT(sci), scintilla_signals[NOTIFY_SIGNAL], 0,
1276 GetCtrlID(), &scn);
1279 void ScintillaGTK::NotifyKey(int key, int modifiers) {
1280 SCNotification scn = {};
1281 scn.nmhdr.code = SCN_KEY;
1282 scn.ch = key;
1283 scn.modifiers = modifiers;
1285 NotifyParent(scn);
1288 void ScintillaGTK::NotifyURIDropped(const char *list) {
1289 SCNotification scn = {};
1290 scn.nmhdr.code = SCN_URIDROPPED;
1291 scn.text = list;
1293 NotifyParent(scn);
1296 const char *CharacterSetID(int characterSet);
1298 const char *ScintillaGTK::CharacterSetID() const {
1299 return ::CharacterSetID(vs.styles[STYLE_DEFAULT].characterSet);
1302 class CaseFolderDBCS : public CaseFolderTable {
1303 const char *charSet;
1304 public:
1305 explicit CaseFolderDBCS(const char *charSet_) : charSet(charSet_) {
1306 StandardASCII();
1308 virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
1309 if ((lenMixed == 1) && (sizeFolded > 0)) {
1310 folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
1311 return 1;
1312 } else if (*charSet) {
1313 std::string sUTF8 = ConvertText(mixed, lenMixed,
1314 "UTF-8", charSet, false);
1315 if (!sUTF8.empty()) {
1316 gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
1317 size_t lenMapped = strlen(mapped);
1318 if (lenMapped < sizeFolded) {
1319 memcpy(folded, mapped, lenMapped);
1320 } else {
1321 folded[0] = '\0';
1322 lenMapped = 1;
1324 g_free(mapped);
1325 return lenMapped;
1328 // Something failed so return a single NUL byte
1329 folded[0] = '\0';
1330 return 1;
1334 CaseFolder *ScintillaGTK::CaseFolderForEncoding() {
1335 if (pdoc->dbcsCodePage == SC_CP_UTF8) {
1336 return new CaseFolderUnicode();
1337 } else {
1338 const char *charSetBuffer = CharacterSetID();
1339 if (charSetBuffer) {
1340 if (pdoc->dbcsCodePage == 0) {
1341 CaseFolderTable *pcf = new CaseFolderTable();
1342 pcf->StandardASCII();
1343 // Only for single byte encodings
1344 for (int i=0x80; i<0x100; i++) {
1345 char sCharacter[2] = "A";
1346 sCharacter[0] = i;
1347 // Silent as some bytes have no assigned character
1348 std::string sUTF8 = ConvertText(sCharacter, 1,
1349 "UTF-8", charSetBuffer, false, true);
1350 if (!sUTF8.empty()) {
1351 gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
1352 if (mapped) {
1353 std::string mappedBack = ConvertText(mapped, strlen(mapped),
1354 charSetBuffer, "UTF-8", false, true);
1355 if ((mappedBack.length() == 1) && (mappedBack[0] != sCharacter[0])) {
1356 pcf->SetTranslation(sCharacter[0], mappedBack[0]);
1358 g_free(mapped);
1362 return pcf;
1363 } else {
1364 return new CaseFolderDBCS(charSetBuffer);
1367 return 0;
1371 namespace {
1373 struct CaseMapper {
1374 gchar *mapped; // Must be freed with g_free
1375 CaseMapper(const std::string &sUTF8, bool toUpperCase) {
1376 if (toUpperCase) {
1377 mapped = g_utf8_strup(sUTF8.c_str(), sUTF8.length());
1378 } else {
1379 mapped = g_utf8_strdown(sUTF8.c_str(), sUTF8.length());
1382 ~CaseMapper() {
1383 g_free(mapped);
1389 std::string ScintillaGTK::CaseMapString(const std::string &s, int caseMapping) {
1390 if ((s.size() == 0) || (caseMapping == cmSame))
1391 return s;
1393 if (IsUnicodeMode()) {
1394 std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
1395 size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
1396 (caseMapping == cmUpper) ? CaseConversionUpper : CaseConversionLower);
1397 retMapped.resize(lenMapped);
1398 return retMapped;
1401 const char *charSetBuffer = CharacterSetID();
1403 if (!*charSetBuffer) {
1404 CaseMapper mapper(s, caseMapping == cmUpper);
1405 return std::string(mapper.mapped, strlen(mapper.mapped));
1406 } else {
1407 // Change text to UTF-8
1408 std::string sUTF8 = ConvertText(s.c_str(), s.length(),
1409 "UTF-8", charSetBuffer, false);
1410 CaseMapper mapper(sUTF8, caseMapping == cmUpper);
1411 return ConvertText(mapper.mapped, strlen(mapper.mapped), charSetBuffer, "UTF-8", false);
1415 int ScintillaGTK::KeyDefault(int key, int modifiers) {
1416 // Pass up to container in case it is an accelerator
1417 NotifyKey(key, modifiers);
1418 return 0;
1421 void ScintillaGTK::CopyToClipboard(const SelectionText &selectedText) {
1422 SelectionText *clipText = new SelectionText();
1423 clipText->Copy(selectedText);
1424 StoreOnClipboard(clipText);
1427 void ScintillaGTK::Copy() {
1428 if (!sel.Empty()) {
1429 SelectionText *clipText = new SelectionText();
1430 CopySelectionRange(clipText);
1431 StoreOnClipboard(clipText);
1432 #if PLAT_GTK_WIN32
1433 if (sel.IsRectangular()) {
1434 ::OpenClipboard(NULL);
1435 ::SetClipboardData(cfColumnSelect, 0);
1436 ::CloseClipboard();
1438 #endif
1442 void ScintillaGTK::ClipboardReceived(GtkClipboard *clipboard, GtkSelectionData *selection_data, gpointer data) {
1443 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(data);
1444 sciThis->ReceivedSelection(selection_data);
1447 void ScintillaGTK::Paste() {
1448 atomSought = atomUTF8;
1449 GtkClipboard *clipBoard =
1450 gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard);
1451 if (clipBoard == NULL)
1452 return;
1453 gtk_clipboard_request_contents(clipBoard, atomSought, ClipboardReceived, this);
1456 void ScintillaGTK::CreateCallTipWindow(PRectangle rc) {
1457 if (!ct.wCallTip.Created()) {
1458 ct.wCallTip = gtk_window_new(GTK_WINDOW_POPUP);
1459 ct.wDraw = gtk_drawing_area_new();
1460 GtkWidget *widcdrw = PWidget(ct.wDraw); // // No code inside the G_OBJECT macro
1461 gtk_container_add(GTK_CONTAINER(PWidget(ct.wCallTip)), widcdrw);
1462 #if GTK_CHECK_VERSION(3,0,0)
1463 g_signal_connect(G_OBJECT(widcdrw), "draw",
1464 G_CALLBACK(ScintillaGTK::DrawCT), &ct);
1465 #else
1466 g_signal_connect(G_OBJECT(widcdrw), "expose_event",
1467 G_CALLBACK(ScintillaGTK::ExposeCT), &ct);
1468 #endif
1469 g_signal_connect(G_OBJECT(widcdrw), "button_press_event",
1470 G_CALLBACK(ScintillaGTK::PressCT), static_cast<void *>(this));
1471 gtk_widget_set_events(widcdrw,
1472 GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK);
1474 gtk_widget_set_size_request(PWidget(ct.wDraw), rc.Width(), rc.Height());
1475 ct.wDraw.Show();
1476 if (PWindow(ct.wCallTip)) {
1477 gdk_window_resize(PWindow(ct.wCallTip), rc.Width(), rc.Height());
1481 void ScintillaGTK::AddToPopUp(const char *label, int cmd, bool enabled) {
1482 GtkWidget *menuItem;
1483 if (label[0])
1484 menuItem = gtk_menu_item_new_with_label(label);
1485 else
1486 menuItem = gtk_separator_menu_item_new();
1487 gtk_menu_shell_append(GTK_MENU_SHELL(popup.GetID()), menuItem);
1488 g_object_set_data(G_OBJECT(menuItem), "CmdNum", GINT_TO_POINTER(cmd));
1489 g_signal_connect(G_OBJECT(menuItem),"activate", G_CALLBACK(PopUpCB), this);
1491 if (cmd) {
1492 if (menuItem)
1493 gtk_widget_set_sensitive(menuItem, enabled);
1497 bool ScintillaGTK::OwnPrimarySelection() {
1498 return ((gdk_selection_owner_get(GDK_SELECTION_PRIMARY)
1499 == PWindow(wMain)) &&
1500 (PWindow(wMain) != NULL));
1503 void ScintillaGTK::ClaimSelection() {
1504 // X Windows has a 'primary selection' as well as the clipboard.
1505 // Whenever the user selects some text, we become the primary selection
1506 if (!sel.Empty() && IS_WIDGET_REALIZED(GTK_WIDGET(PWidget(wMain)))) {
1507 primarySelection = true;
1508 gtk_selection_owner_set(GTK_WIDGET(PWidget(wMain)),
1509 GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1510 primary.Clear();
1511 } else if (OwnPrimarySelection()) {
1512 primarySelection = true;
1513 if (primary.Empty())
1514 gtk_selection_owner_set(NULL, GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1515 } else {
1516 primarySelection = false;
1517 primary.Clear();
1521 static const guchar *DataOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data(sd); }
1522 static gint LengthOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_length(sd); }
1523 static GdkAtom TypeOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data_type(sd); }
1524 static GdkAtom SelectionOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_selection(sd); }
1526 // Detect rectangular text, convert line ends to current mode, convert from or to UTF-8
1527 void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText) {
1528 const char *data = reinterpret_cast<const char *>(DataOfGSD(selectionData));
1529 int len = LengthOfGSD(selectionData);
1530 GdkAtom selectionTypeData = TypeOfGSD(selectionData);
1532 // Return empty string if selection is not a string
1533 if ((selectionTypeData != GDK_TARGET_STRING) && (selectionTypeData != atomUTF8)) {
1534 selText.Clear();
1535 return;
1538 // Check for "\n\0" ending to string indicating that selection is rectangular
1539 bool isRectangular;
1540 #if PLAT_GTK_WIN32
1541 isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
1542 #else
1543 isRectangular = ((len > 2) && (data[len - 1] == 0 && data[len - 2] == '\n'));
1544 if (isRectangular)
1545 len--; // Forget the extra '\0'
1546 #endif
1548 #if PLAT_GTK_WIN32
1549 // Win32 includes an ending '\0' byte in 'len' for clipboard text from
1550 // external applications; ignore it.
1551 if ((len > 0) && (data[len - 1] == '\0'))
1552 len--;
1553 #endif
1555 std::string dest(data, len);
1556 if (selectionTypeData == GDK_TARGET_STRING) {
1557 if (IsUnicodeMode()) {
1558 // Unknown encoding so assume in Latin1
1559 dest = UTF8FromLatin1(dest.c_str(), dest.length());
1560 selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
1561 } else {
1562 // Assume buffer is in same encoding as selection
1563 selText.Copy(dest, pdoc->dbcsCodePage,
1564 vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1566 } else { // UTF-8
1567 const char *charSetBuffer = CharacterSetID();
1568 if (!IsUnicodeMode() && *charSetBuffer) {
1569 // Convert to locale
1570 dest = ConvertText(dest.c_str(), dest.length(), charSetBuffer, "UTF-8", true);
1571 selText.Copy(dest, pdoc->dbcsCodePage,
1572 vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1573 } else {
1574 selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
1579 void ScintillaGTK::ReceivedSelection(GtkSelectionData *selection_data) {
1580 try {
1581 if ((SelectionOfGSD(selection_data) == atomClipboard) ||
1582 (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY)) {
1583 if ((atomSought == atomUTF8) && (LengthOfGSD(selection_data) <= 0)) {
1584 atomSought = atomString;
1585 gtk_selection_convert(GTK_WIDGET(PWidget(wMain)),
1586 SelectionOfGSD(selection_data), atomSought, GDK_CURRENT_TIME);
1587 } else if ((LengthOfGSD(selection_data) > 0) &&
1588 ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8))) {
1589 SelectionText selText;
1590 GetGtkSelectionText(selection_data, selText);
1592 UndoGroup ug(pdoc);
1593 if (SelectionOfGSD(selection_data) != GDK_SELECTION_PRIMARY) {
1594 ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
1597 InsertPasteShape(selText.Data(), selText.Length(),
1598 selText.rectangular ? pasteRectangular : pasteStream);
1599 EnsureCaretVisible();
1602 // else fprintf(stderr, "Target non string %d %d\n", (int)(selection_data->type),
1603 // (int)(atomUTF8));
1604 Redraw();
1605 } catch (...) {
1606 errorStatus = SC_STATUS_FAILURE;
1610 void ScintillaGTK::ReceivedDrop(GtkSelectionData *selection_data) {
1611 dragWasDropped = true;
1612 if (TypeOfGSD(selection_data) == atomUriList || TypeOfGSD(selection_data) == atomDROPFILES_DND) {
1613 const char *data = reinterpret_cast<const char *>(DataOfGSD(selection_data));
1614 std::vector<char> drop(data, data + LengthOfGSD(selection_data));
1615 drop.push_back('\0');
1616 NotifyURIDropped(&drop[0]);
1617 } else if ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8)) {
1618 if (LengthOfGSD(selection_data) > 0) {
1619 SelectionText selText;
1620 GetGtkSelectionText(selection_data, selText);
1621 DropAt(posDrop, selText.Data(), selText.Length(), false, selText.rectangular);
1623 } else if (LengthOfGSD(selection_data) > 0) {
1624 //~ fprintf(stderr, "ReceivedDrop other %p\n", static_cast<void *>(selection_data->type));
1626 Redraw();
1631 void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *text) {
1632 #if PLAT_GTK_WIN32
1633 // GDK on Win32 expands any \n into \r\n, so make a copy of
1634 // the clip text now with newlines converted to \n. Use { } to hide symbols
1635 // from code below
1636 SelectionText *newline_normalized = NULL;
1638 std::string tmpstr = Document::TransformLineEnds(text->Data(), text->Length(), SC_EOL_LF);
1639 newline_normalized = new SelectionText();
1640 newline_normalized->Copy(tmpstr, SC_CP_UTF8, 0, text->rectangular, false);
1641 text = newline_normalized;
1643 #endif
1645 // Convert text to utf8 if it isn't already
1646 SelectionText *converted = 0;
1647 if ((text->codePage != SC_CP_UTF8) && (info == TARGET_UTF8_STRING)) {
1648 const char *charSet = ::CharacterSetID(text->characterSet);
1649 if (*charSet) {
1650 std::string tmputf = ConvertText(text->Data(), text->Length(), "UTF-8", charSet, false);
1651 converted = new SelectionText();
1652 converted->Copy(tmputf, SC_CP_UTF8, 0, text->rectangular, false);
1653 text = converted;
1657 // Here is a somewhat evil kludge.
1658 // As I can not work out how to store data on the clipboard in multiple formats
1659 // and need some way to mark the clipping as being stream or rectangular,
1660 // the terminating \0 is included in the length for rectangular clippings.
1661 // All other tested aplications behave benignly by ignoring the \0.
1662 // The #if is here because on Windows cfColumnSelect clip entry is used
1663 // instead as standard indicator of rectangularness (so no need to kludge)
1664 const char *textData = text->Data();
1665 int len = text->Length();
1666 #if PLAT_GTK_WIN32 == 0
1667 if (text->rectangular)
1668 len++;
1669 #endif
1671 if (info == TARGET_UTF8_STRING) {
1672 gtk_selection_data_set_text(selection_data, textData, len);
1673 } else {
1674 gtk_selection_data_set(selection_data,
1675 static_cast<GdkAtom>(GDK_SELECTION_TYPE_STRING),
1676 8, reinterpret_cast<const unsigned char *>(textData), len);
1678 delete converted;
1680 #if PLAT_GTK_WIN32
1681 delete newline_normalized;
1682 #endif
1685 void ScintillaGTK::StoreOnClipboard(SelectionText *clipText) {
1686 GtkClipboard *clipBoard =
1687 gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard);
1688 if (clipBoard == NULL) // Occurs if widget isn't in a toplevel
1689 return;
1691 if (gtk_clipboard_set_with_data(clipBoard, clipboardCopyTargets, nClipboardCopyTargets,
1692 ClipboardGetSelection, ClipboardClearSelection, clipText)) {
1693 gtk_clipboard_set_can_store(clipBoard, clipboardCopyTargets, nClipboardCopyTargets);
1697 void ScintillaGTK::ClipboardGetSelection(GtkClipboard *, GtkSelectionData *selection_data, guint info, void *data) {
1698 GetSelection(selection_data, info, static_cast<SelectionText*>(data));
1701 void ScintillaGTK::ClipboardClearSelection(GtkClipboard *, void *data) {
1702 SelectionText *obj = static_cast<SelectionText*>(data);
1703 delete obj;
1706 void ScintillaGTK::UnclaimSelection(GdkEventSelection *selection_event) {
1707 try {
1708 //Platform::DebugPrintf("UnclaimSelection\n");
1709 if (selection_event->selection == GDK_SELECTION_PRIMARY) {
1710 //Platform::DebugPrintf("UnclaimPrimarySelection\n");
1711 if (!OwnPrimarySelection()) {
1712 primary.Clear();
1713 primarySelection = false;
1714 FullPaint();
1717 } catch (...) {
1718 errorStatus = SC_STATUS_FAILURE;
1722 void ScintillaGTK::Resize(int width, int height) {
1723 //Platform::DebugPrintf("Resize %d %d\n", width, height);
1724 //printf("Resize %d %d\n", width, height);
1726 // Not always needed, but some themes can have different sizes of scrollbars
1727 #if GTK_CHECK_VERSION(3,0,0)
1728 GtkRequisition requisition;
1729 gtk_widget_get_preferred_size(PWidget(scrollbarv), NULL, &requisition);
1730 verticalScrollBarWidth = requisition.width;
1731 gtk_widget_get_preferred_size(PWidget(scrollbarh), NULL, &requisition);
1732 horizontalScrollBarHeight = requisition.height;
1733 #else
1734 verticalScrollBarWidth = GTK_WIDGET(PWidget(scrollbarv))->requisition.width;
1735 horizontalScrollBarHeight = GTK_WIDGET(PWidget(scrollbarh))->requisition.height;
1736 #endif
1738 // These allocations should never produce negative sizes as they would wrap around to huge
1739 // unsigned numbers inside GTK+ causing warnings.
1740 bool showSBHorizontal = horizontalScrollBarVisible && !Wrapping();
1742 GtkAllocation alloc;
1743 if (showSBHorizontal) {
1744 gtk_widget_show(GTK_WIDGET(PWidget(scrollbarh)));
1745 alloc.x = 0;
1746 alloc.y = height - horizontalScrollBarHeight;
1747 alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
1748 alloc.height = horizontalScrollBarHeight;
1749 gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarh)), &alloc);
1750 } else {
1751 gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarh)));
1752 horizontalScrollBarHeight = 0; // in case horizontalScrollBarVisible is true.
1755 if (verticalScrollBarVisible) {
1756 gtk_widget_show(GTK_WIDGET(PWidget(scrollbarv)));
1757 alloc.x = width - verticalScrollBarWidth;
1758 alloc.y = 0;
1759 alloc.width = verticalScrollBarWidth;
1760 alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
1761 gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarv)), &alloc);
1762 } else {
1763 gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarv)));
1764 verticalScrollBarWidth = 0;
1766 if (IS_WIDGET_MAPPED(PWidget(wMain))) {
1767 ChangeSize();
1770 alloc.x = 0;
1771 alloc.y = 0;
1772 alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
1773 alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
1774 gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc);
1777 static void SetAdjustmentValue(GtkAdjustment *object, int value) {
1778 GtkAdjustment *adjustment = GTK_ADJUSTMENT(object);
1779 int maxValue = static_cast<int>(
1780 gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size(adjustment));
1782 if (value > maxValue)
1783 value = maxValue;
1784 if (value < 0)
1785 value = 0;
1786 gtk_adjustment_set_value(adjustment, value);
1789 static int modifierTranslated(int sciModifier) {
1790 switch (sciModifier) {
1791 case SCMOD_SHIFT:
1792 return GDK_SHIFT_MASK;
1793 case SCMOD_CTRL:
1794 return GDK_CONTROL_MASK;
1795 case SCMOD_ALT:
1796 return GDK_MOD1_MASK;
1797 case SCMOD_SUPER:
1798 return GDK_MOD4_MASK;
1799 default:
1800 return 0;
1804 gint ScintillaGTK::PressThis(GdkEventButton *event) {
1805 try {
1806 //Platform::DebugPrintf("Press %x time=%d state = %x button = %x\n",this,event->time, event->state, event->button);
1807 // Do not use GTK+ double click events as Scintilla has its own double click detection
1808 if (event->type != GDK_BUTTON_PRESS)
1809 return FALSE;
1811 if (evbtn) {
1812 gdk_event_free(reinterpret_cast<GdkEvent *>(evbtn));
1813 evbtn = 0;
1815 evbtn = reinterpret_cast<GdkEventButton *>(gdk_event_copy(reinterpret_cast<GdkEvent *>(event)));
1816 Point pt;
1817 pt.x = int(event->x);
1818 pt.y = int(event->y);
1819 PRectangle rcClient = GetClientRectangle();
1820 //Platform::DebugPrintf("Press %0d,%0d in %0d,%0d %0d,%0d\n",
1821 // pt.x, pt.y, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
1822 if ((pt.x > rcClient.right) || (pt.y > rcClient.bottom)) {
1823 Platform::DebugPrintf("Bad location\n");
1824 return FALSE;
1827 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
1828 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
1829 // On X, instead of sending literal modifiers use the user specified
1830 // modifier, defaulting to control instead of alt.
1831 // This is because most X window managers grab alt + click for moving
1832 bool alt = (event->state & modifierTranslated(rectangularSelectionModifier)) != 0;
1834 gtk_widget_grab_focus(PWidget(wMain));
1835 if (event->button == 1) {
1836 #if PLAT_GTK_MACOSX
1837 bool meta = ctrl;
1838 // GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
1839 // not GDK_META_MASK like in key events.
1840 ctrl = (event->state & GDK_MOD2_MASK) != 0;
1841 #else
1842 bool meta = false;
1843 #endif
1844 ButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
1845 } else if (event->button == 2) {
1846 // Grab the primary selection if it exists
1847 SelectionPosition pos = SPositionFromLocation(pt, false, false, UserVirtualSpace());
1848 if (OwnPrimarySelection() && primary.Empty())
1849 CopySelectionRange(&primary);
1851 sel.Clear();
1852 SetSelection(pos, pos);
1853 atomSought = atomUTF8;
1854 gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_PRIMARY,
1855 atomSought, event->time);
1856 } else if (event->button == 3) {
1857 if (!PointInSelection(pt))
1858 SetEmptySelection(PositionFromLocation(pt));
1859 if (displayPopupMenu) {
1860 // PopUp menu
1861 // Convert to screen
1862 int ox = 0;
1863 int oy = 0;
1864 gdk_window_get_origin(PWindow(wMain), &ox, &oy);
1865 ContextMenu(Point(pt.x + ox, pt.y + oy));
1866 } else {
1867 return FALSE;
1869 } else if (event->button == 4) {
1870 // Wheel scrolling up (only GTK 1.x does it this way)
1871 if (ctrl)
1872 SetAdjustmentValue(adjustmenth, xOffset - 6);
1873 else
1874 SetAdjustmentValue(adjustmentv, topLine - 3);
1875 } else if (event->button == 5) {
1876 // Wheel scrolling down (only GTK 1.x does it this way)
1877 if (ctrl)
1878 SetAdjustmentValue(adjustmenth, xOffset + 6);
1879 else
1880 SetAdjustmentValue(adjustmentv, topLine + 3);
1882 } catch (...) {
1883 errorStatus = SC_STATUS_FAILURE;
1885 return TRUE;
1888 gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) {
1889 if (event->window != WindowFromWidget(widget))
1890 return FALSE;
1891 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1892 return sciThis->PressThis(event);
1895 gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
1896 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1897 try {
1898 //Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state);
1899 if (!sciThis->HaveMouseCapture())
1900 return FALSE;
1901 if (event->button == 1) {
1902 Point pt;
1903 pt.x = int(event->x);
1904 pt.y = int(event->y);
1905 //Platform::DebugPrintf("Up %x %x %d %d %d\n",
1906 // sciThis,event->window,event->time, pt.x, pt.y);
1907 if (event->window != PWindow(sciThis->wMain))
1908 // If mouse released on scroll bar then the position is relative to the
1909 // scrollbar, not the drawing window so just repeat the most recent point.
1910 pt = sciThis->ptMouseLast;
1911 sciThis->ButtonUp(pt, event->time, (event->state & GDK_CONTROL_MASK) != 0);
1913 } catch (...) {
1914 sciThis->errorStatus = SC_STATUS_FAILURE;
1916 return FALSE;
1919 // win32gtk and GTK >= 2 use SCROLL_* events instead of passing the
1920 // button4/5/6/7 events to the GTK app
1921 gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
1922 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1923 try {
1925 if (widget == NULL || event == NULL)
1926 return FALSE;
1928 // Compute amount and direction to scroll (even tho on win32 there is
1929 // intensity of scrolling info in the native message, gtk doesn't
1930 // support this so we simulate similarly adaptive scrolling)
1931 // Note that this is disabled on OS X (Darwin) with the X11 backend
1932 // where the X11 server already has an adaptive scrolling algorithm
1933 // that fights with this one
1934 int cLineScroll;
1935 #if defined(__APPLE__) && !defined(GDK_WINDOWING_QUARTZ)
1936 cLineScroll = sciThis->linesPerScroll;
1937 if (cLineScroll == 0)
1938 cLineScroll = 4;
1939 sciThis->wheelMouseIntensity = cLineScroll;
1940 #else
1941 int timeDelta = 1000000;
1942 GTimeVal curTime;
1943 g_get_current_time(&curTime);
1944 if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec)
1945 timeDelta = curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec;
1946 else if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec + 1)
1947 timeDelta = 1000000 + (curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec);
1948 if ((event->direction == sciThis->lastWheelMouseDirection) && (timeDelta < 250000)) {
1949 if (sciThis->wheelMouseIntensity < 12)
1950 sciThis->wheelMouseIntensity++;
1951 cLineScroll = sciThis->wheelMouseIntensity;
1952 } else {
1953 cLineScroll = sciThis->linesPerScroll;
1954 if (cLineScroll == 0)
1955 cLineScroll = 4;
1956 sciThis->wheelMouseIntensity = cLineScroll;
1958 #endif
1959 if (event->direction == GDK_SCROLL_UP || event->direction == GDK_SCROLL_LEFT) {
1960 cLineScroll *= -1;
1962 g_get_current_time(&sciThis->lastWheelMouseTime);
1963 sciThis->lastWheelMouseDirection = event->direction;
1965 // Note: Unpatched versions of win32gtk don't set the 'state' value so
1966 // only regular scrolling is supported there. Also, unpatched win32gtk
1967 // issues spurious button 2 mouse events during wheeling, which can cause
1968 // problems (a patch for both was submitted by archaeopteryx.com on 13Jun2001)
1970 // Data zoom not supported
1971 if (event->state & GDK_SHIFT_MASK) {
1972 return FALSE;
1975 #if GTK_CHECK_VERSION(3,4,0)
1976 // Smooth scrolling not supported
1977 if (event->direction == GDK_SCROLL_SMOOTH) {
1978 return FALSE;
1980 #endif
1982 // Horizontal scrolling
1983 if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) {
1984 sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll);
1986 // Text font size zoom
1987 } else if (event->state & GDK_CONTROL_MASK) {
1988 if (cLineScroll < 0) {
1989 sciThis->KeyCommand(SCI_ZOOMIN);
1990 } else {
1991 sciThis->KeyCommand(SCI_ZOOMOUT);
1994 // Regular scrolling
1995 } else {
1996 sciThis->ScrollTo(sciThis->topLine + cLineScroll);
1998 return TRUE;
1999 } catch (...) {
2000 sciThis->errorStatus = SC_STATUS_FAILURE;
2002 return FALSE;
2005 gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
2006 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2007 try {
2008 //Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time);
2009 if (event->window != WindowFromWidget(widget))
2010 return FALSE;
2011 int x = 0;
2012 int y = 0;
2013 GdkModifierType state;
2014 if (event->is_hint) {
2015 #if GTK_CHECK_VERSION(3,0,0)
2016 gdk_window_get_device_position(event->window,
2017 event->device, &x, &y, &state);
2018 #else
2019 gdk_window_get_pointer(event->window, &x, &y, &state);
2020 #endif
2021 } else {
2022 x = static_cast<int>(event->x);
2023 y = static_cast<int>(event->y);
2024 state = static_cast<GdkModifierType>(event->state);
2026 //Platform::DebugPrintf("Move %x %x %d %c %d %d\n",
2027 // sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y);
2028 Point pt(x, y);
2029 int modifiers = ((event->state & GDK_SHIFT_MASK) != 0 ? SCI_SHIFT : 0) |
2030 ((event->state & GDK_CONTROL_MASK) != 0 ? SCI_CTRL : 0) |
2031 ((event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) != 0 ? SCI_ALT : 0);
2032 sciThis->ButtonMoveWithModifiers(pt, modifiers);
2033 } catch (...) {
2034 sciThis->errorStatus = SC_STATUS_FAILURE;
2036 return FALSE;
2039 // Map the keypad keys to their equivalent functions
2040 static int KeyTranslate(int keyIn) {
2041 switch (keyIn) {
2042 #if GTK_CHECK_VERSION(3,0,0)
2043 case GDK_KEY_ISO_Left_Tab:
2044 return SCK_TAB;
2045 case GDK_KEY_KP_Down:
2046 return SCK_DOWN;
2047 case GDK_KEY_KP_Up:
2048 return SCK_UP;
2049 case GDK_KEY_KP_Left:
2050 return SCK_LEFT;
2051 case GDK_KEY_KP_Right:
2052 return SCK_RIGHT;
2053 case GDK_KEY_KP_Home:
2054 return SCK_HOME;
2055 case GDK_KEY_KP_End:
2056 return SCK_END;
2057 case GDK_KEY_KP_Page_Up:
2058 return SCK_PRIOR;
2059 case GDK_KEY_KP_Page_Down:
2060 return SCK_NEXT;
2061 case GDK_KEY_KP_Delete:
2062 return SCK_DELETE;
2063 case GDK_KEY_KP_Insert:
2064 return SCK_INSERT;
2065 case GDK_KEY_KP_Enter:
2066 return SCK_RETURN;
2068 case GDK_KEY_Down:
2069 return SCK_DOWN;
2070 case GDK_KEY_Up:
2071 return SCK_UP;
2072 case GDK_KEY_Left:
2073 return SCK_LEFT;
2074 case GDK_KEY_Right:
2075 return SCK_RIGHT;
2076 case GDK_KEY_Home:
2077 return SCK_HOME;
2078 case GDK_KEY_End:
2079 return SCK_END;
2080 case GDK_KEY_Page_Up:
2081 return SCK_PRIOR;
2082 case GDK_KEY_Page_Down:
2083 return SCK_NEXT;
2084 case GDK_KEY_Delete:
2085 return SCK_DELETE;
2086 case GDK_KEY_Insert:
2087 return SCK_INSERT;
2088 case GDK_KEY_Escape:
2089 return SCK_ESCAPE;
2090 case GDK_KEY_BackSpace:
2091 return SCK_BACK;
2092 case GDK_KEY_Tab:
2093 return SCK_TAB;
2094 case GDK_KEY_Return:
2095 return SCK_RETURN;
2096 case GDK_KEY_KP_Add:
2097 return SCK_ADD;
2098 case GDK_KEY_KP_Subtract:
2099 return SCK_SUBTRACT;
2100 case GDK_KEY_KP_Divide:
2101 return SCK_DIVIDE;
2102 case GDK_KEY_Super_L:
2103 return SCK_WIN;
2104 case GDK_KEY_Super_R:
2105 return SCK_RWIN;
2106 case GDK_KEY_Menu:
2107 return SCK_MENU;
2109 #else
2111 case GDK_ISO_Left_Tab:
2112 return SCK_TAB;
2113 case GDK_KP_Down:
2114 return SCK_DOWN;
2115 case GDK_KP_Up:
2116 return SCK_UP;
2117 case GDK_KP_Left:
2118 return SCK_LEFT;
2119 case GDK_KP_Right:
2120 return SCK_RIGHT;
2121 case GDK_KP_Home:
2122 return SCK_HOME;
2123 case GDK_KP_End:
2124 return SCK_END;
2125 case GDK_KP_Page_Up:
2126 return SCK_PRIOR;
2127 case GDK_KP_Page_Down:
2128 return SCK_NEXT;
2129 case GDK_KP_Delete:
2130 return SCK_DELETE;
2131 case GDK_KP_Insert:
2132 return SCK_INSERT;
2133 case GDK_KP_Enter:
2134 return SCK_RETURN;
2136 case GDK_Down:
2137 return SCK_DOWN;
2138 case GDK_Up:
2139 return SCK_UP;
2140 case GDK_Left:
2141 return SCK_LEFT;
2142 case GDK_Right:
2143 return SCK_RIGHT;
2144 case GDK_Home:
2145 return SCK_HOME;
2146 case GDK_End:
2147 return SCK_END;
2148 case GDK_Page_Up:
2149 return SCK_PRIOR;
2150 case GDK_Page_Down:
2151 return SCK_NEXT;
2152 case GDK_Delete:
2153 return SCK_DELETE;
2154 case GDK_Insert:
2155 return SCK_INSERT;
2156 case GDK_Escape:
2157 return SCK_ESCAPE;
2158 case GDK_BackSpace:
2159 return SCK_BACK;
2160 case GDK_Tab:
2161 return SCK_TAB;
2162 case GDK_Return:
2163 return SCK_RETURN;
2164 case GDK_KP_Add:
2165 return SCK_ADD;
2166 case GDK_KP_Subtract:
2167 return SCK_SUBTRACT;
2168 case GDK_KP_Divide:
2169 return SCK_DIVIDE;
2170 case GDK_Super_L:
2171 return SCK_WIN;
2172 case GDK_Super_R:
2173 return SCK_RWIN;
2174 case GDK_Menu:
2175 return SCK_MENU;
2176 #endif
2177 default:
2178 return keyIn;
2182 gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
2183 try {
2184 //fprintf(stderr, "SC-key: %d %x [%s]\n",
2185 // event->keyval, event->state, (event->length > 0) ? event->string : "empty");
2186 if (gtk_im_context_filter_keypress(im_context, event)) {
2187 return 1;
2189 if (!event->keyval) {
2190 return true;
2193 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
2194 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
2195 bool alt = (event->state & GDK_MOD1_MASK) != 0;
2196 bool super = (event->state & GDK_MOD4_MASK) != 0;
2197 guint key = event->keyval;
2198 if ((ctrl || alt) && (key < 128))
2199 key = toupper(key);
2200 #if GTK_CHECK_VERSION(3,0,0)
2201 else if (!ctrl && (key >= GDK_KEY_KP_Multiply && key <= GDK_KEY_KP_9))
2202 #else
2203 else if (!ctrl && (key >= GDK_KP_Multiply && key <= GDK_KP_9))
2204 #endif
2205 key &= 0x7F;
2206 // Hack for keys over 256 and below command keys but makes Hungarian work.
2207 // This will have to change for Unicode
2208 else if (key >= 0xFE00)
2209 key = KeyTranslate(key);
2211 bool consumed = false;
2212 #if !(PLAT_GTK_MACOSX)
2213 bool meta = false;
2214 #else
2215 bool meta = ctrl;
2216 ctrl = (event->state & GDK_META_MASK) != 0;
2217 #endif
2218 bool added = KeyDownWithModifiers(key, ModifierFlags(shift, ctrl, alt, meta, super), &consumed) != 0;
2219 if (!consumed)
2220 consumed = added;
2221 //fprintf(stderr, "SK-key: %d %x %x\n",event->keyval, event->state, consumed);
2222 if (event->keyval == 0xffffff && event->length > 0) {
2223 ClearSelection();
2224 const int lengthInserted = pdoc->InsertString(CurrentPosition(), event->string, strlen(event->string));
2225 if (lengthInserted > 0) {
2226 MovePositionTo(CurrentPosition() + lengthInserted);
2229 return consumed;
2230 } catch (...) {
2231 errorStatus = SC_STATUS_FAILURE;
2233 return FALSE;
2236 gboolean ScintillaGTK::KeyPress(GtkWidget *widget, GdkEventKey *event) {
2237 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2238 return sciThis->KeyThis(event);
2241 gboolean ScintillaGTK::KeyRelease(GtkWidget *widget, GdkEventKey *event) {
2242 //Platform::DebugPrintf("SC-keyrel: %d %x %3s\n",event->keyval, event->state, event->string);
2243 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2244 if (gtk_im_context_filter_keypress(sciThis->im_context, event)) {
2245 return TRUE;
2247 return FALSE;
2250 #if GTK_CHECK_VERSION(3,0,0)
2252 gboolean ScintillaGTK::DrawPreeditThis(GtkWidget *widget, cairo_t *cr) {
2253 try {
2254 PreEditString pes(im_context);
2255 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2256 pango_layout_set_attributes(layout, pes.attrs);
2258 cairo_move_to(cr, 0, 0);
2259 pango_cairo_show_layout(cr, layout);
2261 g_object_unref(layout);
2262 } catch (...) {
2263 errorStatus = SC_STATUS_FAILURE;
2265 return TRUE;
2268 gboolean ScintillaGTK::DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis) {
2269 return sciThis->DrawPreeditThis(widget, cr);
2272 #else
2274 gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose) {
2275 try {
2276 PreEditString pes(im_context);
2277 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2278 pango_layout_set_attributes(layout, pes.attrs);
2280 cairo_t *context = gdk_cairo_create(reinterpret_cast<GdkDrawable *>(WindowFromWidget(widget)));
2281 cairo_move_to(context, 0, 0);
2282 pango_cairo_show_layout(context, layout);
2283 cairo_destroy(context);
2284 g_object_unref(layout);
2285 } catch (...) {
2286 errorStatus = SC_STATUS_FAILURE;
2288 return TRUE;
2291 gboolean ScintillaGTK::ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2292 return sciThis->ExposePreeditThis(widget, ose);
2295 #endif
2297 bool ScintillaGTK::KoreanIME() {
2298 PreEditString pes(im_context);
2299 if (pes.pscript != PANGO_SCRIPT_COMMON)
2300 lastNonCommonScript = pes.pscript;
2301 return lastNonCommonScript == PANGO_SCRIPT_HANGUL;
2304 void ScintillaGTK::MoveImeCarets(int pos) {
2305 // Move carets relatively by bytes
2306 for (size_t r=0; r<sel.Count(); r++) {
2307 int positionInsert = sel.Range(r).Start().Position();
2308 sel.Range(r).caret.SetPosition(positionInsert + pos);
2309 sel.Range(r).anchor.SetPosition(positionInsert + pos);
2313 void ScintillaGTK::DrawImeIndicator(int indicator, int len) {
2314 // Emulate the visual style of IME characters with indicators.
2315 // Draw an indicator on the character before caret by the character bytes of len
2316 // so it should be called after addCharUTF().
2317 // It does not affect caret positions.
2318 if (indicator < 8 || indicator > INDIC_MAX) {
2319 return;
2321 pdoc->decorations.SetCurrentIndicator(indicator);
2322 for (size_t r=0; r<sel.Count(); r++) {
2323 int positionInsert = sel.Range(r).Start().Position();
2324 pdoc->DecorationFillRange(positionInsert - len, 1, len);
2328 static std::vector<int> MapImeIndicators(PangoAttrList *attrs, const char *u8Str) {
2329 // Map input style to scintilla ime indicator.
2330 // Attrs position points between UTF-8 bytes.
2331 // Indicator index to be returned is character based though.
2332 glong charactersLen = g_utf8_strlen(u8Str, strlen(u8Str));
2333 std::vector<int> indicator(charactersLen, SC_INDICATOR_UNKNOWN);
2335 PangoAttrIterator *iterunderline = pango_attr_list_get_iterator(attrs);
2336 if (iterunderline) {
2337 do {
2338 PangoAttribute *attrunderline = pango_attr_iterator_get(iterunderline, PANGO_ATTR_UNDERLINE);
2339 if (attrunderline) {
2340 glong start = g_utf8_strlen(u8Str, attrunderline->start_index);
2341 glong end = g_utf8_strlen(u8Str, attrunderline->end_index);
2342 PangoUnderline uline = (PangoUnderline)((PangoAttrInt *)attrunderline)->value;
2343 for (glong i=start; i < end; ++i) {
2344 switch (uline) {
2345 case PANGO_UNDERLINE_NONE:
2346 indicator[i] = SC_INDICATOR_UNKNOWN;
2347 break;
2348 case PANGO_UNDERLINE_SINGLE: // normal input
2349 indicator[i] = SC_INDICATOR_INPUT;
2350 break;
2351 case PANGO_UNDERLINE_DOUBLE:
2352 case PANGO_UNDERLINE_LOW:
2353 case PANGO_UNDERLINE_ERROR:
2354 break;
2358 } while (pango_attr_iterator_next(iterunderline));
2359 pango_attr_iterator_destroy(iterunderline);
2362 PangoAttrIterator *itercolor = pango_attr_list_get_iterator(attrs);
2363 if (itercolor) {
2364 do {
2365 PangoAttribute *backcolor = pango_attr_iterator_get(itercolor, PANGO_ATTR_BACKGROUND);
2366 if (backcolor) {
2367 glong start = g_utf8_strlen(u8Str, backcolor->start_index);
2368 glong end = g_utf8_strlen(u8Str, backcolor->end_index);
2369 for (glong i=start; i < end; ++i) {
2370 indicator[i] = SC_INDICATOR_TARGET; // target converted
2373 } while (pango_attr_iterator_next(itercolor));
2374 pango_attr_iterator_destroy(itercolor);
2376 return indicator;
2379 void ScintillaGTK::SetCandidateWindowPos() {
2380 // Composition box accompanies candidate box.
2381 Point pt = PointMainCaret();
2382 GdkRectangle imeBox = {0}; // No need to set width
2383 imeBox.x = pt.x; // Only need positiion
2384 imeBox.y = pt.y + vs.lineHeight; // underneath the first charater
2385 gtk_im_context_set_cursor_location(im_context, &imeBox);
2388 void ScintillaGTK::CommitThis(char *commitStr) {
2389 try {
2390 //~ fprintf(stderr, "Commit '%s'\n", commitStr);
2391 view.imeCaretBlockOverride = false;
2393 if (pdoc->TentativeActive()) {
2394 pdoc->TentativeUndo();
2397 const char *charSetSource = CharacterSetID();
2399 glong uniStrLen = 0;
2400 gunichar *uniStr = g_utf8_to_ucs4_fast(commitStr, strlen(commitStr), &uniStrLen);
2401 for (glong i = 0; i < uniStrLen; i++) {
2402 gchar u8Char[UTF8MaxBytes+2] = {0};
2403 gint u8CharLen = g_unichar_to_utf8(uniStr[i], u8Char);
2404 std::string docChar = u8Char;
2405 if (!IsUnicodeMode())
2406 docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
2408 AddCharUTF(docChar.c_str(), docChar.size());
2410 g_free(uniStr);
2411 ShowCaretAtCurrentPosition();
2412 } catch (...) {
2413 errorStatus = SC_STATUS_FAILURE;
2417 void ScintillaGTK::Commit(GtkIMContext *, char *str, ScintillaGTK *sciThis) {
2418 sciThis->CommitThis(str);
2421 void ScintillaGTK::PreeditChangedInlineThis() {
2422 // Copy & paste by johnsonj with a lot of helps of Neil
2423 // Great thanks for my foreruners, jiniya and BLUEnLIVE
2424 try {
2425 if (pdoc->IsReadOnly() || SelectionContainsProtected()) {
2426 gtk_im_context_reset(im_context);
2427 return;
2430 view.imeCaretBlockOverride = false; // If backspace.
2432 if (pdoc->TentativeActive()) {
2433 pdoc->TentativeUndo();
2434 } else {
2435 // No tentative undo means start of this composition so
2436 // fill in any virtual spaces.
2437 ClearBeforeTentativeStart();
2440 PreEditString preeditStr(im_context);
2441 const char *charSetSource = CharacterSetID();
2443 if (!preeditStr.validUTF8 || (charSetSource == NULL)) {
2444 ShowCaretAtCurrentPosition();
2445 return;
2448 if (preeditStr.uniStrLen == 0 || preeditStr.uniStrLen > maxLenInputIME) {
2449 //fprintf(stderr, "Do not allow over 200 chars: %i\n", preeditStr.uniStrLen);
2450 ShowCaretAtCurrentPosition();
2451 return;
2454 pdoc->TentativeStart(); // TentativeActive() from now on
2456 std::vector<int> indicator = MapImeIndicators(preeditStr.attrs, preeditStr.str);
2458 bool tmpRecordingMacro = recordingMacro;
2459 recordingMacro = false;
2460 for (glong i = 0; i < preeditStr.uniStrLen; i++) {
2461 gchar u8Char[UTF8MaxBytes+2] = {0};
2462 gint u8CharLen = g_unichar_to_utf8(preeditStr.uniStr[i], u8Char);
2463 std::string docChar = u8Char;
2464 if (!IsUnicodeMode())
2465 docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
2467 AddCharUTF(docChar.c_str(), docChar.size());
2469 DrawImeIndicator(indicator[i], docChar.size());
2471 recordingMacro = tmpRecordingMacro;
2473 // Move caret to ime cursor position.
2474 int imeEndToImeCaretU32 = preeditStr.cursor_pos - preeditStr.uniStrLen;
2475 int imeCaretPosDoc = pdoc->GetRelativePosition(CurrentPosition(), imeEndToImeCaretU32);
2477 MoveImeCarets(- CurrentPosition() + imeCaretPosDoc);
2479 if (KoreanIME()) {
2480 #if !PLAT_GTK_WIN32
2481 if (preeditStr.cursor_pos > 0) {
2482 int oneCharBefore = pdoc->GetRelativePosition(CurrentPosition(), -1);
2483 MoveImeCarets(- CurrentPosition() + oneCharBefore);
2485 #endif
2486 view.imeCaretBlockOverride = true;
2489 EnsureCaretVisible();
2490 SetCandidateWindowPos();
2491 ShowCaretAtCurrentPosition();
2492 } catch (...) {
2493 errorStatus = SC_STATUS_FAILURE;
2497 void ScintillaGTK::PreeditChangedWindowedThis() {
2498 try {
2499 PreEditString pes(im_context);
2500 if (strlen(pes.str) > 0) {
2501 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2502 pango_layout_set_attributes(layout, pes.attrs);
2504 gint w, h;
2505 pango_layout_get_pixel_size(layout, &w, &h);
2506 g_object_unref(layout);
2508 gint x, y;
2509 gdk_window_get_origin(PWindow(wText), &x, &y);
2511 Point pt = PointMainCaret();
2512 if (pt.x < 0)
2513 pt.x = 0;
2514 if (pt.y < 0)
2515 pt.y = 0;
2517 gtk_window_move(GTK_WINDOW(PWidget(wPreedit)), x + pt.x, y + pt.y);
2518 gtk_window_resize(GTK_WINDOW(PWidget(wPreedit)), w, h);
2519 gtk_widget_show(PWidget(wPreedit));
2520 gtk_widget_queue_draw_area(PWidget(wPreeditDraw), 0, 0, w, h);
2521 } else {
2522 gtk_widget_hide(PWidget(wPreedit));
2524 } catch (...) {
2525 errorStatus = SC_STATUS_FAILURE;
2529 void ScintillaGTK::PreeditChanged(GtkIMContext *, ScintillaGTK *sciThis) {
2530 if ((sciThis->imeInteraction == imeInline) || (sciThis->KoreanIME())) {
2531 sciThis->PreeditChangedInlineThis();
2532 } else {
2533 sciThis->PreeditChangedWindowedThis();
2537 void ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) {
2538 RealizeText(widget, NULL);
2541 void ScintillaGTK::RealizeText(GtkWidget *widget, void*) {
2542 // Set NULL background to avoid automatic clearing so Scintilla responsible for all drawing
2543 if (WindowFromWidget(widget)) {
2544 #if GTK_CHECK_VERSION(3,0,0)
2545 gdk_window_set_background_pattern(WindowFromWidget(widget), NULL);
2546 #else
2547 gdk_window_set_back_pixmap(WindowFromWidget(widget), NULL, FALSE);
2548 #endif
2552 static GObjectClass *scintilla_class_parent_class;
2554 void ScintillaGTK::Dispose(GObject *object) {
2555 try {
2556 ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(object);
2557 ScintillaGTK *sciThis = reinterpret_cast<ScintillaGTK *>(scio->pscin);
2559 if (PWidget(sciThis->scrollbarv)) {
2560 gtk_widget_unparent(PWidget(sciThis->scrollbarv));
2561 sciThis->scrollbarv = NULL;
2564 if (PWidget(sciThis->scrollbarh)) {
2565 gtk_widget_unparent(PWidget(sciThis->scrollbarh));
2566 sciThis->scrollbarh = NULL;
2569 scintilla_class_parent_class->dispose(object);
2570 } catch (...) {
2571 // Its dying so nowhere to save the status
2575 void ScintillaGTK::Destroy(GObject *object) {
2576 try {
2577 ScintillaObject *scio = SCINTILLA(object);
2579 // This avoids a double destruction
2580 if (!scio->pscin)
2581 return;
2582 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(scio->pscin);
2583 //Platform::DebugPrintf("Destroying %x %x\n", sciThis, object);
2584 sciThis->Finalise();
2586 delete sciThis;
2587 scio->pscin = 0;
2588 scintilla_class_parent_class->finalize(object);
2589 } catch (...) {
2590 // Its dead so nowhere to save the status
2594 #if GTK_CHECK_VERSION(3,0,0)
2596 gboolean ScintillaGTK::DrawTextThis(cairo_t *cr) {
2597 try {
2598 paintState = painting;
2599 repaintFullWindow = false;
2601 rcPaint = GetClientRectangle();
2603 PLATFORM_ASSERT(rgnUpdate == NULL);
2604 rgnUpdate = cairo_copy_clip_rectangle_list(cr);
2605 if (rgnUpdate && rgnUpdate->status != CAIRO_STATUS_SUCCESS) {
2606 // If not successful then ignore
2607 fprintf(stderr, "DrawTextThis failed to copy update region %d [%d]\n", rgnUpdate->status, rgnUpdate->num_rectangles);
2608 cairo_rectangle_list_destroy(rgnUpdate);
2609 rgnUpdate = 0;
2612 double x1, y1, x2, y2;
2613 cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
2614 rcPaint.left = x1;
2615 rcPaint.top = y1;
2616 rcPaint.right = x2;
2617 rcPaint.bottom = y2;
2618 PRectangle rcClient = GetClientRectangle();
2619 paintingAllText = rcPaint.Contains(rcClient);
2620 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2621 if (surfaceWindow) {
2622 surfaceWindow->Init(cr, PWidget(wText));
2623 Paint(surfaceWindow, rcPaint);
2624 surfaceWindow->Release();
2625 delete surfaceWindow;
2627 if ((paintState == paintAbandoned) || repaintFullWindow) {
2628 // Painting area was insufficient to cover new styling or brace highlight positions
2629 FullPaint();
2631 paintState = notPainting;
2632 repaintFullWindow = false;
2634 if (rgnUpdate) {
2635 cairo_rectangle_list_destroy(rgnUpdate);
2637 rgnUpdate = 0;
2638 paintState = notPainting;
2639 } catch (...) {
2640 errorStatus = SC_STATUS_FAILURE;
2643 return FALSE;
2646 gboolean ScintillaGTK::DrawText(GtkWidget *, cairo_t *cr, ScintillaGTK *sciThis) {
2647 return sciThis->DrawTextThis(cr);
2650 gboolean ScintillaGTK::DrawThis(cairo_t *cr) {
2651 try {
2652 #ifdef GTK_STYLE_CLASS_SCROLLBARS_JUNCTION /* GTK >= 3.4 */
2653 // if both scrollbars are visible, paint the little square on the bottom right corner
2654 if (verticalScrollBarVisible && horizontalScrollBarVisible && !Wrapping()) {
2655 GtkStyleContext *styleContext = gtk_widget_get_style_context(PWidget(wMain));
2656 PRectangle rc = GetClientRectangle();
2658 gtk_style_context_save(styleContext);
2659 gtk_style_context_add_class(styleContext, GTK_STYLE_CLASS_SCROLLBARS_JUNCTION);
2661 gtk_render_background(styleContext, cr, rc.right, rc.bottom,
2662 verticalScrollBarWidth, horizontalScrollBarHeight);
2663 gtk_render_frame(styleContext, cr, rc.right, rc.bottom,
2664 verticalScrollBarWidth, horizontalScrollBarHeight);
2666 gtk_style_context_restore(styleContext);
2668 #endif
2670 gtk_container_propagate_draw(
2671 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), cr);
2672 gtk_container_propagate_draw(
2673 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), cr);
2674 // Starting from the following version, the expose event are not propagated
2675 // for double buffered non native windows, so we need to call it ourselves
2676 // or keep the default handler
2677 #if GTK_CHECK_VERSION(3,0,0)
2678 // we want to forward on any >= 3.9.2 runtime
2679 if (gtk_check_version(3,9,2) == NULL) {
2680 gtk_container_propagate_draw(
2681 GTK_CONTAINER(PWidget(wMain)), PWidget(wText), cr);
2683 #endif
2684 } catch (...) {
2685 errorStatus = SC_STATUS_FAILURE;
2687 return FALSE;
2690 gboolean ScintillaGTK::DrawMain(GtkWidget *widget, cairo_t *cr) {
2691 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2692 return sciThis->DrawThis(cr);
2695 #else
2697 gboolean ScintillaGTK::ExposeTextThis(GtkWidget * /*widget*/, GdkEventExpose *ose) {
2698 try {
2699 paintState = painting;
2701 rcPaint.left = ose->area.x;
2702 rcPaint.top = ose->area.y;
2703 rcPaint.right = ose->area.x + ose->area.width;
2704 rcPaint.bottom = ose->area.y + ose->area.height;
2706 PLATFORM_ASSERT(rgnUpdate == NULL);
2707 rgnUpdate = gdk_region_copy(ose->region);
2708 PRectangle rcClient = GetClientRectangle();
2709 paintingAllText = rcPaint.Contains(rcClient);
2710 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2711 if (surfaceWindow) {
2712 cairo_t *cr = gdk_cairo_create(PWindow(wText));
2713 surfaceWindow->Init(cr, PWidget(wText));
2714 Paint(surfaceWindow, rcPaint);
2715 surfaceWindow->Release();
2716 delete surfaceWindow;
2717 cairo_destroy(cr);
2719 if (paintState == paintAbandoned) {
2720 // Painting area was insufficient to cover new styling or brace highlight positions
2721 FullPaint();
2723 paintState = notPainting;
2725 if (rgnUpdate) {
2726 gdk_region_destroy(rgnUpdate);
2728 rgnUpdate = 0;
2729 } catch (...) {
2730 errorStatus = SC_STATUS_FAILURE;
2733 return FALSE;
2736 gboolean ScintillaGTK::ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2737 return sciThis->ExposeTextThis(widget, ose);
2740 gboolean ScintillaGTK::ExposeMain(GtkWidget *widget, GdkEventExpose *ose) {
2741 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2742 //Platform::DebugPrintf("Expose Main %0d,%0d %0d,%0d\n",
2743 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2744 return sciThis->Expose(widget, ose);
2747 gboolean ScintillaGTK::Expose(GtkWidget *, GdkEventExpose *ose) {
2748 try {
2749 //fprintf(stderr, "Expose %0d,%0d %0d,%0d\n",
2750 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2752 // The text is painted in ExposeText
2753 gtk_container_propagate_expose(
2754 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), ose);
2755 gtk_container_propagate_expose(
2756 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), ose);
2758 } catch (...) {
2759 errorStatus = SC_STATUS_FAILURE;
2761 return FALSE;
2764 #endif
2766 void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2767 try {
2768 sciThis->ScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)), false);
2769 } catch (...) {
2770 sciThis->errorStatus = SC_STATUS_FAILURE;
2774 void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2775 try {
2776 sciThis->HorizontalScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)));
2777 } catch (...) {
2778 sciThis->errorStatus = SC_STATUS_FAILURE;
2782 void ScintillaGTK::SelectionReceived(GtkWidget *widget,
2783 GtkSelectionData *selection_data, guint) {
2784 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2785 //Platform::DebugPrintf("Selection received\n");
2786 sciThis->ReceivedSelection(selection_data);
2789 void ScintillaGTK::SelectionGet(GtkWidget *widget,
2790 GtkSelectionData *selection_data, guint info, guint) {
2791 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2792 try {
2793 //Platform::DebugPrintf("Selection get\n");
2794 if (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY) {
2795 if (sciThis->primary.Empty()) {
2796 sciThis->CopySelectionRange(&sciThis->primary);
2798 sciThis->GetSelection(selection_data, info, &sciThis->primary);
2800 } catch (...) {
2801 sciThis->errorStatus = SC_STATUS_FAILURE;
2805 gint ScintillaGTK::SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event) {
2806 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2807 //Platform::DebugPrintf("Selection clear\n");
2808 sciThis->UnclaimSelection(selection_event);
2809 if (GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event) {
2810 return GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event(widget, selection_event);
2812 return TRUE;
2815 gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context,
2816 gint x, gint y, guint dragtime) {
2817 try {
2818 Point npt(x, y);
2819 SetDragPosition(SPositionFromLocation(npt, false, false, UserVirtualSpace()));
2820 #if GTK_CHECK_VERSION(2,22,0)
2821 GdkDragAction preferredAction = gdk_drag_context_get_suggested_action(context);
2822 GdkDragAction actions = gdk_drag_context_get_actions(context);
2823 #else
2824 GdkDragAction preferredAction = context->suggested_action;
2825 GdkDragAction actions = context->actions;
2826 #endif
2827 SelectionPosition pos = SPositionFromLocation(npt);
2828 if ((inDragDrop == ddDragging) && (PositionInSelection(pos.Position()))) {
2829 // Avoid dragging selection onto itself as that produces a move
2830 // with no real effect but which creates undo actions.
2831 preferredAction = static_cast<GdkDragAction>(0);
2832 } else if (actions == static_cast<GdkDragAction>
2833 (GDK_ACTION_COPY | GDK_ACTION_MOVE)) {
2834 preferredAction = GDK_ACTION_MOVE;
2836 gdk_drag_status(context, preferredAction, dragtime);
2837 } catch (...) {
2838 errorStatus = SC_STATUS_FAILURE;
2840 return FALSE;
2843 gboolean ScintillaGTK::DragMotion(GtkWidget *widget, GdkDragContext *context,
2844 gint x, gint y, guint dragtime) {
2845 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2846 return sciThis->DragMotionThis(context, x, y, dragtime);
2849 void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, guint) {
2850 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2851 try {
2852 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2853 //Platform::DebugPrintf("DragLeave %x\n", sciThis);
2854 } catch (...) {
2855 sciThis->errorStatus = SC_STATUS_FAILURE;
2859 void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) {
2860 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2861 try {
2862 // If drag did not result in drop here or elsewhere
2863 if (!sciThis->dragWasDropped)
2864 sciThis->SetEmptySelection(sciThis->posDrag);
2865 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2866 //Platform::DebugPrintf("DragEnd %x %d\n", sciThis, sciThis->dragWasDropped);
2867 sciThis->inDragDrop = ddNone;
2868 } catch (...) {
2869 sciThis->errorStatus = SC_STATUS_FAILURE;
2873 gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/,
2874 gint, gint, guint) {
2875 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2876 try {
2877 //Platform::DebugPrintf("Drop %x\n", sciThis);
2878 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2879 } catch (...) {
2880 sciThis->errorStatus = SC_STATUS_FAILURE;
2882 return FALSE;
2885 void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*context*/,
2886 gint, gint, GtkSelectionData *selection_data, guint /*info*/, guint) {
2887 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2888 try {
2889 sciThis->ReceivedDrop(selection_data);
2890 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2891 } catch (...) {
2892 sciThis->errorStatus = SC_STATUS_FAILURE;
2896 void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context,
2897 GtkSelectionData *selection_data, guint info, guint) {
2898 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2899 try {
2900 sciThis->dragWasDropped = true;
2901 if (!sciThis->sel.Empty()) {
2902 sciThis->GetSelection(selection_data, info, &sciThis->drag);
2904 #if GTK_CHECK_VERSION(2,22,0)
2905 GdkDragAction action = gdk_drag_context_get_selected_action(context);
2906 #else
2907 GdkDragAction action = context->action;
2908 #endif
2909 if (action == GDK_ACTION_MOVE) {
2910 for (size_t r=0; r<sciThis->sel.Count(); r++) {
2911 if (sciThis->posDrop >= sciThis->sel.Range(r).Start()) {
2912 if (sciThis->posDrop > sciThis->sel.Range(r).End()) {
2913 sciThis->posDrop.Add(-sciThis->sel.Range(r).Length());
2914 } else {
2915 sciThis->posDrop.Add(-SelectionRange(sciThis->posDrop, sciThis->sel.Range(r).Start()).Length());
2919 sciThis->ClearSelection();
2921 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2922 } catch (...) {
2923 sciThis->errorStatus = SC_STATUS_FAILURE;
2927 int ScintillaGTK::TimeOut(gpointer ptt) {
2928 TimeThunk *tt = static_cast<TimeThunk *>(ptt);
2929 tt->scintilla->TickFor(tt->reason);
2930 return 1;
2933 gboolean ScintillaGTK::IdleCallback(gpointer pSci) {
2934 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
2935 // Idler will be automatically stopped, if there is nothing
2936 // to do while idle.
2937 bool ret = sciThis->Idle();
2938 if (ret == false) {
2939 // FIXME: This will remove the idler from GTK, we don't want to
2940 // remove it as it is removed automatically when this function
2941 // returns false (although, it should be harmless).
2942 sciThis->SetIdle(false);
2944 return ret;
2947 gboolean ScintillaGTK::StyleIdle(gpointer pSci) {
2948 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
2949 sciThis->IdleWork();
2950 // Idler will be automatically stopped
2951 return FALSE;
2954 void ScintillaGTK::QueueIdleWork(WorkNeeded::workItems items, int upTo) {
2955 Editor::QueueIdleWork(items, upTo);
2956 if (!workNeeded.active) {
2957 // Only allow one style needed to be queued
2958 workNeeded.active = true;
2959 gdk_threads_add_idle_full(G_PRIORITY_HIGH_IDLE, StyleIdle, this, NULL);
2963 void ScintillaGTK::PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis) {
2964 guint action = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(menuItem), "CmdNum"));
2965 if (action) {
2966 sciThis->Command(action);
2970 gboolean ScintillaGTK::PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis) {
2971 try {
2972 if (event->window != WindowFromWidget(widget))
2973 return FALSE;
2974 if (event->type != GDK_BUTTON_PRESS)
2975 return FALSE;
2976 Point pt;
2977 pt.x = int(event->x);
2978 pt.y = int(event->y);
2979 sciThis->ct.MouseClick(pt);
2980 sciThis->CallTipClick();
2981 } catch (...) {
2983 return TRUE;
2986 #if GTK_CHECK_VERSION(3,0,0)
2988 gboolean ScintillaGTK::DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip) {
2989 try {
2990 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2991 if (surfaceWindow) {
2992 surfaceWindow->Init(cr, widget);
2993 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
2994 surfaceWindow->SetDBCSMode(ctip->codePage);
2995 ctip->PaintCT(surfaceWindow);
2996 surfaceWindow->Release();
2997 delete surfaceWindow;
2999 } catch (...) {
3000 // No pointer back to Scintilla to save status
3002 return TRUE;
3005 #else
3007 gboolean ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, CallTip *ctip) {
3008 try {
3009 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
3010 if (surfaceWindow) {
3011 cairo_t *cr = gdk_cairo_create(WindowFromWidget(widget));
3012 surfaceWindow->Init(cr, widget);
3013 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
3014 surfaceWindow->SetDBCSMode(ctip->codePage);
3015 ctip->PaintCT(surfaceWindow);
3016 surfaceWindow->Release();
3017 delete surfaceWindow;
3018 cairo_destroy(cr);
3020 } catch (...) {
3021 // No pointer back to Scintilla to save status
3023 return TRUE;
3026 #endif
3028 sptr_t ScintillaGTK::DirectFunction(
3029 sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3030 return reinterpret_cast<ScintillaGTK *>(ptr)->WndProc(iMessage, wParam, lParam);
3033 /* legacy name for scintilla_object_send_message */
3034 GEANY_API_SYMBOL
3035 sptr_t scintilla_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3036 ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
3037 return psci->WndProc(iMessage, wParam, lParam);
3040 GEANY_API_SYMBOL
3041 gintptr scintilla_object_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3042 return scintilla_send_message(sci, iMessage, wParam, lParam);
3045 static void scintilla_class_init(ScintillaClass *klass);
3046 static void scintilla_init(ScintillaObject *sci);
3048 extern void Platform_Initialise();
3049 extern void Platform_Finalise();
3051 /* legacy name for scintilla_object_get_type */
3052 GEANY_API_SYMBOL
3053 GType scintilla_get_type() {
3054 static GType scintilla_type = 0;
3055 try {
3057 if (!scintilla_type) {
3058 scintilla_type = g_type_from_name("ScintillaObject");
3059 if (!scintilla_type) {
3060 static GTypeInfo scintilla_info = {
3061 (guint16) sizeof (ScintillaObjectClass),
3062 NULL, //(GBaseInitFunc)
3063 NULL, //(GBaseFinalizeFunc)
3064 (GClassInitFunc) scintilla_class_init,
3065 NULL, //(GClassFinalizeFunc)
3066 NULL, //gconstpointer data
3067 (guint16) sizeof (ScintillaObject),
3068 0, //n_preallocs
3069 (GInstanceInitFunc) scintilla_init,
3070 NULL //(GTypeValueTable*)
3072 scintilla_type = g_type_register_static(
3073 GTK_TYPE_CONTAINER, "ScintillaObject", &scintilla_info, (GTypeFlags) 0);
3077 } catch (...) {
3079 return scintilla_type;
3082 GEANY_API_SYMBOL
3083 GType scintilla_object_get_type() {
3084 return scintilla_get_type();
3087 void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class) {
3088 Platform_Initialise();
3089 #ifdef SCI_LEXER
3090 Scintilla_LinkLexers();
3091 #endif
3092 atomClipboard = gdk_atom_intern("CLIPBOARD", FALSE);
3093 atomUTF8 = gdk_atom_intern("UTF8_STRING", FALSE);
3094 atomString = GDK_SELECTION_TYPE_STRING;
3095 atomUriList = gdk_atom_intern("text/uri-list", FALSE);
3096 atomDROPFILES_DND = gdk_atom_intern("DROPFILES_DND", FALSE);
3098 // Define default signal handlers for the class: Could move more
3099 // of the signal handlers here (those that currently attached to wDraw
3100 // in Initialise() may require coordinate translation?)
3102 object_class->dispose = Dispose;
3103 object_class->finalize = Destroy;
3104 #if GTK_CHECK_VERSION(3,0,0)
3105 widget_class->get_preferred_width = GetPreferredWidth;
3106 widget_class->get_preferred_height = GetPreferredHeight;
3107 #else
3108 widget_class->size_request = SizeRequest;
3109 #endif
3110 widget_class->size_allocate = SizeAllocate;
3111 #if GTK_CHECK_VERSION(3,0,0)
3112 widget_class->draw = DrawMain;
3113 #else
3114 widget_class->expose_event = ExposeMain;
3115 #endif
3116 widget_class->motion_notify_event = Motion;
3117 widget_class->button_press_event = Press;
3118 widget_class->button_release_event = MouseRelease;
3119 widget_class->scroll_event = ScrollEvent;
3120 widget_class->key_press_event = KeyPress;
3121 widget_class->key_release_event = KeyRelease;
3122 widget_class->focus_in_event = FocusIn;
3123 widget_class->focus_out_event = FocusOut;
3124 widget_class->selection_received = SelectionReceived;
3125 widget_class->selection_get = SelectionGet;
3126 widget_class->selection_clear_event = SelectionClear;
3128 widget_class->drag_data_received = DragDataReceived;
3129 widget_class->drag_motion = DragMotion;
3130 widget_class->drag_leave = DragLeave;
3131 widget_class->drag_end = DragEnd;
3132 widget_class->drag_drop = Drop;
3133 widget_class->drag_data_get = DragDataGet;
3135 widget_class->realize = Realize;
3136 widget_class->unrealize = UnRealize;
3137 widget_class->map = Map;
3138 widget_class->unmap = UnMap;
3140 container_class->forall = MainForAll;
3143 #define SIG_MARSHAL scintilla_marshal_NONE__INT_POINTER
3144 #define MARSHAL_ARGUMENTS G_TYPE_INT, G_TYPE_POINTER
3146 static void scintilla_class_init(ScintillaClass *klass) {
3147 try {
3148 OBJECT_CLASS *object_class = (OBJECT_CLASS*) klass;
3149 GtkWidgetClass *widget_class = (GtkWidgetClass*) klass;
3150 GtkContainerClass *container_class = (GtkContainerClass*) klass;
3152 GSignalFlags sigflags = GSignalFlags(G_SIGNAL_ACTION | G_SIGNAL_RUN_LAST);
3153 scintilla_signals[COMMAND_SIGNAL] = g_signal_new(
3154 "command",
3155 G_TYPE_FROM_CLASS(object_class),
3156 sigflags,
3157 G_STRUCT_OFFSET(ScintillaClass, command),
3158 NULL, //(GSignalAccumulator)
3159 NULL, //(gpointer)
3160 SIG_MARSHAL,
3161 G_TYPE_NONE,
3162 2, MARSHAL_ARGUMENTS);
3164 scintilla_signals[NOTIFY_SIGNAL] = g_signal_new(
3165 SCINTILLA_NOTIFY,
3166 G_TYPE_FROM_CLASS(object_class),
3167 sigflags,
3168 G_STRUCT_OFFSET(ScintillaClass, notify),
3169 NULL,
3170 NULL,
3171 SIG_MARSHAL,
3172 G_TYPE_NONE,
3173 2, MARSHAL_ARGUMENTS);
3175 klass->command = NULL;
3176 klass->notify = NULL;
3177 scintilla_class_parent_class = G_OBJECT_CLASS(g_type_class_peek_parent(klass));
3178 ScintillaGTK::ClassInit(object_class, widget_class, container_class);
3179 } catch (...) {
3183 static void scintilla_init(ScintillaObject *sci) {
3184 try {
3185 gtk_widget_set_can_focus(GTK_WIDGET(sci), TRUE);
3186 sci->pscin = new ScintillaGTK(sci);
3187 } catch (...) {
3191 /* legacy name for scintilla_object_new */
3192 GEANY_API_SYMBOL
3193 GtkWidget* scintilla_new() {
3194 GtkWidget *widget = GTK_WIDGET(g_object_new(scintilla_get_type(), NULL));
3195 gtk_widget_set_direction(widget, GTK_TEXT_DIR_LTR);
3197 return widget;
3200 GEANY_API_SYMBOL
3201 GtkWidget *scintilla_object_new() {
3202 return scintilla_new();
3205 void scintilla_set_id(ScintillaObject *sci, uptr_t id) {
3206 ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
3207 psci->ctrlID = id;
3210 void scintilla_release_resources(void) {
3211 try {
3212 Platform_Finalise();
3213 } catch (...) {