GTK: Fix auto-completion popup sizing code for GTK 3.20
[geany-mirror.git] / scintilla / gtk / ScintillaGTK.cxx
blob4c0688855a0d366f275bae4ef7c58f5666e7fa6a
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 = 1;
1773 alloc.height = 1;
1774 #if GTK_CHECK_VERSION(3, 0, 0)
1775 // please GTK 3.20 and ask wText what size it wants, although we know it doesn't really need
1776 // anything special as it's ours.
1777 gtk_widget_get_preferred_size(PWidget(wText), &requisition, NULL);
1778 alloc.width = requisition.width;
1779 alloc.height = requisition.height;
1780 #endif
1781 alloc.width = Platform::Maximum(alloc.width, width - verticalScrollBarWidth);
1782 alloc.height = Platform::Maximum(alloc.height, height - horizontalScrollBarHeight);
1783 gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc);
1786 static void SetAdjustmentValue(GtkAdjustment *object, int value) {
1787 GtkAdjustment *adjustment = GTK_ADJUSTMENT(object);
1788 int maxValue = static_cast<int>(
1789 gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size(adjustment));
1791 if (value > maxValue)
1792 value = maxValue;
1793 if (value < 0)
1794 value = 0;
1795 gtk_adjustment_set_value(adjustment, value);
1798 static int modifierTranslated(int sciModifier) {
1799 switch (sciModifier) {
1800 case SCMOD_SHIFT:
1801 return GDK_SHIFT_MASK;
1802 case SCMOD_CTRL:
1803 return GDK_CONTROL_MASK;
1804 case SCMOD_ALT:
1805 return GDK_MOD1_MASK;
1806 case SCMOD_SUPER:
1807 return GDK_MOD4_MASK;
1808 default:
1809 return 0;
1813 gint ScintillaGTK::PressThis(GdkEventButton *event) {
1814 try {
1815 //Platform::DebugPrintf("Press %x time=%d state = %x button = %x\n",this,event->time, event->state, event->button);
1816 // Do not use GTK+ double click events as Scintilla has its own double click detection
1817 if (event->type != GDK_BUTTON_PRESS)
1818 return FALSE;
1820 if (evbtn) {
1821 gdk_event_free(reinterpret_cast<GdkEvent *>(evbtn));
1822 evbtn = 0;
1824 evbtn = reinterpret_cast<GdkEventButton *>(gdk_event_copy(reinterpret_cast<GdkEvent *>(event)));
1825 Point pt;
1826 pt.x = int(event->x);
1827 pt.y = int(event->y);
1828 PRectangle rcClient = GetClientRectangle();
1829 //Platform::DebugPrintf("Press %0d,%0d in %0d,%0d %0d,%0d\n",
1830 // pt.x, pt.y, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
1831 if ((pt.x > rcClient.right) || (pt.y > rcClient.bottom)) {
1832 Platform::DebugPrintf("Bad location\n");
1833 return FALSE;
1836 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
1837 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
1838 // On X, instead of sending literal modifiers use the user specified
1839 // modifier, defaulting to control instead of alt.
1840 // This is because most X window managers grab alt + click for moving
1841 bool alt = (event->state & modifierTranslated(rectangularSelectionModifier)) != 0;
1843 gtk_widget_grab_focus(PWidget(wMain));
1844 if (event->button == 1) {
1845 #if PLAT_GTK_MACOSX
1846 bool meta = ctrl;
1847 // GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
1848 // not GDK_META_MASK like in key events.
1849 ctrl = (event->state & GDK_MOD2_MASK) != 0;
1850 #else
1851 bool meta = false;
1852 #endif
1853 ButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
1854 } else if (event->button == 2) {
1855 // Grab the primary selection if it exists
1856 SelectionPosition pos = SPositionFromLocation(pt, false, false, UserVirtualSpace());
1857 if (OwnPrimarySelection() && primary.Empty())
1858 CopySelectionRange(&primary);
1860 sel.Clear();
1861 SetSelection(pos, pos);
1862 atomSought = atomUTF8;
1863 gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_PRIMARY,
1864 atomSought, event->time);
1865 } else if (event->button == 3) {
1866 if (!PointInSelection(pt))
1867 SetEmptySelection(PositionFromLocation(pt));
1868 if (displayPopupMenu) {
1869 // PopUp menu
1870 // Convert to screen
1871 int ox = 0;
1872 int oy = 0;
1873 gdk_window_get_origin(PWindow(wMain), &ox, &oy);
1874 ContextMenu(Point(pt.x + ox, pt.y + oy));
1875 } else {
1876 return FALSE;
1878 } else if (event->button == 4) {
1879 // Wheel scrolling up (only GTK 1.x does it this way)
1880 if (ctrl)
1881 SetAdjustmentValue(adjustmenth, xOffset - 6);
1882 else
1883 SetAdjustmentValue(adjustmentv, topLine - 3);
1884 } else if (event->button == 5) {
1885 // Wheel scrolling down (only GTK 1.x does it this way)
1886 if (ctrl)
1887 SetAdjustmentValue(adjustmenth, xOffset + 6);
1888 else
1889 SetAdjustmentValue(adjustmentv, topLine + 3);
1891 } catch (...) {
1892 errorStatus = SC_STATUS_FAILURE;
1894 return TRUE;
1897 gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) {
1898 if (event->window != WindowFromWidget(widget))
1899 return FALSE;
1900 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1901 return sciThis->PressThis(event);
1904 gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
1905 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1906 try {
1907 //Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state);
1908 if (!sciThis->HaveMouseCapture())
1909 return FALSE;
1910 if (event->button == 1) {
1911 Point pt;
1912 pt.x = int(event->x);
1913 pt.y = int(event->y);
1914 //Platform::DebugPrintf("Up %x %x %d %d %d\n",
1915 // sciThis,event->window,event->time, pt.x, pt.y);
1916 if (event->window != PWindow(sciThis->wMain))
1917 // If mouse released on scroll bar then the position is relative to the
1918 // scrollbar, not the drawing window so just repeat the most recent point.
1919 pt = sciThis->ptMouseLast;
1920 sciThis->ButtonUp(pt, event->time, (event->state & GDK_CONTROL_MASK) != 0);
1922 } catch (...) {
1923 sciThis->errorStatus = SC_STATUS_FAILURE;
1925 return FALSE;
1928 // win32gtk and GTK >= 2 use SCROLL_* events instead of passing the
1929 // button4/5/6/7 events to the GTK app
1930 gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
1931 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1932 try {
1934 if (widget == NULL || event == NULL)
1935 return FALSE;
1937 // Compute amount and direction to scroll (even tho on win32 there is
1938 // intensity of scrolling info in the native message, gtk doesn't
1939 // support this so we simulate similarly adaptive scrolling)
1940 // Note that this is disabled on OS X (Darwin) with the X11 backend
1941 // where the X11 server already has an adaptive scrolling algorithm
1942 // that fights with this one
1943 int cLineScroll;
1944 #if defined(__APPLE__) && !defined(GDK_WINDOWING_QUARTZ)
1945 cLineScroll = sciThis->linesPerScroll;
1946 if (cLineScroll == 0)
1947 cLineScroll = 4;
1948 sciThis->wheelMouseIntensity = cLineScroll;
1949 #else
1950 int timeDelta = 1000000;
1951 GTimeVal curTime;
1952 g_get_current_time(&curTime);
1953 if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec)
1954 timeDelta = curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec;
1955 else if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec + 1)
1956 timeDelta = 1000000 + (curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec);
1957 if ((event->direction == sciThis->lastWheelMouseDirection) && (timeDelta < 250000)) {
1958 if (sciThis->wheelMouseIntensity < 12)
1959 sciThis->wheelMouseIntensity++;
1960 cLineScroll = sciThis->wheelMouseIntensity;
1961 } else {
1962 cLineScroll = sciThis->linesPerScroll;
1963 if (cLineScroll == 0)
1964 cLineScroll = 4;
1965 sciThis->wheelMouseIntensity = cLineScroll;
1967 #endif
1968 if (event->direction == GDK_SCROLL_UP || event->direction == GDK_SCROLL_LEFT) {
1969 cLineScroll *= -1;
1971 g_get_current_time(&sciThis->lastWheelMouseTime);
1972 sciThis->lastWheelMouseDirection = event->direction;
1974 // Note: Unpatched versions of win32gtk don't set the 'state' value so
1975 // only regular scrolling is supported there. Also, unpatched win32gtk
1976 // issues spurious button 2 mouse events during wheeling, which can cause
1977 // problems (a patch for both was submitted by archaeopteryx.com on 13Jun2001)
1979 // Data zoom not supported
1980 if (event->state & GDK_SHIFT_MASK) {
1981 return FALSE;
1984 #if GTK_CHECK_VERSION(3,4,0)
1985 // Smooth scrolling not supported
1986 if (event->direction == GDK_SCROLL_SMOOTH) {
1987 return FALSE;
1989 #endif
1991 // Horizontal scrolling
1992 if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) {
1993 sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll);
1995 // Text font size zoom
1996 } else if (event->state & GDK_CONTROL_MASK) {
1997 if (cLineScroll < 0) {
1998 sciThis->KeyCommand(SCI_ZOOMIN);
1999 } else {
2000 sciThis->KeyCommand(SCI_ZOOMOUT);
2003 // Regular scrolling
2004 } else {
2005 sciThis->ScrollTo(sciThis->topLine + cLineScroll);
2007 return TRUE;
2008 } catch (...) {
2009 sciThis->errorStatus = SC_STATUS_FAILURE;
2011 return FALSE;
2014 gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
2015 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2016 try {
2017 //Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time);
2018 if (event->window != WindowFromWidget(widget))
2019 return FALSE;
2020 int x = 0;
2021 int y = 0;
2022 GdkModifierType state;
2023 if (event->is_hint) {
2024 #if GTK_CHECK_VERSION(3,0,0)
2025 gdk_window_get_device_position(event->window,
2026 event->device, &x, &y, &state);
2027 #else
2028 gdk_window_get_pointer(event->window, &x, &y, &state);
2029 #endif
2030 } else {
2031 x = static_cast<int>(event->x);
2032 y = static_cast<int>(event->y);
2033 state = static_cast<GdkModifierType>(event->state);
2035 //Platform::DebugPrintf("Move %x %x %d %c %d %d\n",
2036 // sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y);
2037 Point pt(x, y);
2038 int modifiers = ((event->state & GDK_SHIFT_MASK) != 0 ? SCI_SHIFT : 0) |
2039 ((event->state & GDK_CONTROL_MASK) != 0 ? SCI_CTRL : 0) |
2040 ((event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) != 0 ? SCI_ALT : 0);
2041 sciThis->ButtonMoveWithModifiers(pt, modifiers);
2042 } catch (...) {
2043 sciThis->errorStatus = SC_STATUS_FAILURE;
2045 return FALSE;
2048 // Map the keypad keys to their equivalent functions
2049 static int KeyTranslate(int keyIn) {
2050 switch (keyIn) {
2051 #if GTK_CHECK_VERSION(3,0,0)
2052 case GDK_KEY_ISO_Left_Tab:
2053 return SCK_TAB;
2054 case GDK_KEY_KP_Down:
2055 return SCK_DOWN;
2056 case GDK_KEY_KP_Up:
2057 return SCK_UP;
2058 case GDK_KEY_KP_Left:
2059 return SCK_LEFT;
2060 case GDK_KEY_KP_Right:
2061 return SCK_RIGHT;
2062 case GDK_KEY_KP_Home:
2063 return SCK_HOME;
2064 case GDK_KEY_KP_End:
2065 return SCK_END;
2066 case GDK_KEY_KP_Page_Up:
2067 return SCK_PRIOR;
2068 case GDK_KEY_KP_Page_Down:
2069 return SCK_NEXT;
2070 case GDK_KEY_KP_Delete:
2071 return SCK_DELETE;
2072 case GDK_KEY_KP_Insert:
2073 return SCK_INSERT;
2074 case GDK_KEY_KP_Enter:
2075 return SCK_RETURN;
2077 case GDK_KEY_Down:
2078 return SCK_DOWN;
2079 case GDK_KEY_Up:
2080 return SCK_UP;
2081 case GDK_KEY_Left:
2082 return SCK_LEFT;
2083 case GDK_KEY_Right:
2084 return SCK_RIGHT;
2085 case GDK_KEY_Home:
2086 return SCK_HOME;
2087 case GDK_KEY_End:
2088 return SCK_END;
2089 case GDK_KEY_Page_Up:
2090 return SCK_PRIOR;
2091 case GDK_KEY_Page_Down:
2092 return SCK_NEXT;
2093 case GDK_KEY_Delete:
2094 return SCK_DELETE;
2095 case GDK_KEY_Insert:
2096 return SCK_INSERT;
2097 case GDK_KEY_Escape:
2098 return SCK_ESCAPE;
2099 case GDK_KEY_BackSpace:
2100 return SCK_BACK;
2101 case GDK_KEY_Tab:
2102 return SCK_TAB;
2103 case GDK_KEY_Return:
2104 return SCK_RETURN;
2105 case GDK_KEY_KP_Add:
2106 return SCK_ADD;
2107 case GDK_KEY_KP_Subtract:
2108 return SCK_SUBTRACT;
2109 case GDK_KEY_KP_Divide:
2110 return SCK_DIVIDE;
2111 case GDK_KEY_Super_L:
2112 return SCK_WIN;
2113 case GDK_KEY_Super_R:
2114 return SCK_RWIN;
2115 case GDK_KEY_Menu:
2116 return SCK_MENU;
2118 #else
2120 case GDK_ISO_Left_Tab:
2121 return SCK_TAB;
2122 case GDK_KP_Down:
2123 return SCK_DOWN;
2124 case GDK_KP_Up:
2125 return SCK_UP;
2126 case GDK_KP_Left:
2127 return SCK_LEFT;
2128 case GDK_KP_Right:
2129 return SCK_RIGHT;
2130 case GDK_KP_Home:
2131 return SCK_HOME;
2132 case GDK_KP_End:
2133 return SCK_END;
2134 case GDK_KP_Page_Up:
2135 return SCK_PRIOR;
2136 case GDK_KP_Page_Down:
2137 return SCK_NEXT;
2138 case GDK_KP_Delete:
2139 return SCK_DELETE;
2140 case GDK_KP_Insert:
2141 return SCK_INSERT;
2142 case GDK_KP_Enter:
2143 return SCK_RETURN;
2145 case GDK_Down:
2146 return SCK_DOWN;
2147 case GDK_Up:
2148 return SCK_UP;
2149 case GDK_Left:
2150 return SCK_LEFT;
2151 case GDK_Right:
2152 return SCK_RIGHT;
2153 case GDK_Home:
2154 return SCK_HOME;
2155 case GDK_End:
2156 return SCK_END;
2157 case GDK_Page_Up:
2158 return SCK_PRIOR;
2159 case GDK_Page_Down:
2160 return SCK_NEXT;
2161 case GDK_Delete:
2162 return SCK_DELETE;
2163 case GDK_Insert:
2164 return SCK_INSERT;
2165 case GDK_Escape:
2166 return SCK_ESCAPE;
2167 case GDK_BackSpace:
2168 return SCK_BACK;
2169 case GDK_Tab:
2170 return SCK_TAB;
2171 case GDK_Return:
2172 return SCK_RETURN;
2173 case GDK_KP_Add:
2174 return SCK_ADD;
2175 case GDK_KP_Subtract:
2176 return SCK_SUBTRACT;
2177 case GDK_KP_Divide:
2178 return SCK_DIVIDE;
2179 case GDK_Super_L:
2180 return SCK_WIN;
2181 case GDK_Super_R:
2182 return SCK_RWIN;
2183 case GDK_Menu:
2184 return SCK_MENU;
2185 #endif
2186 default:
2187 return keyIn;
2191 gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
2192 try {
2193 //fprintf(stderr, "SC-key: %d %x [%s]\n",
2194 // event->keyval, event->state, (event->length > 0) ? event->string : "empty");
2195 if (gtk_im_context_filter_keypress(im_context, event)) {
2196 return 1;
2198 if (!event->keyval) {
2199 return true;
2202 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
2203 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
2204 bool alt = (event->state & GDK_MOD1_MASK) != 0;
2205 bool super = (event->state & GDK_MOD4_MASK) != 0;
2206 guint key = event->keyval;
2207 if ((ctrl || alt) && (key < 128))
2208 key = toupper(key);
2209 #if GTK_CHECK_VERSION(3,0,0)
2210 else if (!ctrl && (key >= GDK_KEY_KP_Multiply && key <= GDK_KEY_KP_9))
2211 #else
2212 else if (!ctrl && (key >= GDK_KP_Multiply && key <= GDK_KP_9))
2213 #endif
2214 key &= 0x7F;
2215 // Hack for keys over 256 and below command keys but makes Hungarian work.
2216 // This will have to change for Unicode
2217 else if (key >= 0xFE00)
2218 key = KeyTranslate(key);
2220 bool consumed = false;
2221 #if !(PLAT_GTK_MACOSX)
2222 bool meta = false;
2223 #else
2224 bool meta = ctrl;
2225 ctrl = (event->state & GDK_META_MASK) != 0;
2226 #endif
2227 bool added = KeyDownWithModifiers(key, ModifierFlags(shift, ctrl, alt, meta, super), &consumed) != 0;
2228 if (!consumed)
2229 consumed = added;
2230 //fprintf(stderr, "SK-key: %d %x %x\n",event->keyval, event->state, consumed);
2231 if (event->keyval == 0xffffff && event->length > 0) {
2232 ClearSelection();
2233 const int lengthInserted = pdoc->InsertString(CurrentPosition(), event->string, strlen(event->string));
2234 if (lengthInserted > 0) {
2235 MovePositionTo(CurrentPosition() + lengthInserted);
2238 return consumed;
2239 } catch (...) {
2240 errorStatus = SC_STATUS_FAILURE;
2242 return FALSE;
2245 gboolean ScintillaGTK::KeyPress(GtkWidget *widget, GdkEventKey *event) {
2246 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2247 return sciThis->KeyThis(event);
2250 gboolean ScintillaGTK::KeyRelease(GtkWidget *widget, GdkEventKey *event) {
2251 //Platform::DebugPrintf("SC-keyrel: %d %x %3s\n",event->keyval, event->state, event->string);
2252 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2253 if (gtk_im_context_filter_keypress(sciThis->im_context, event)) {
2254 return TRUE;
2256 return FALSE;
2259 #if GTK_CHECK_VERSION(3,0,0)
2261 gboolean ScintillaGTK::DrawPreeditThis(GtkWidget *widget, cairo_t *cr) {
2262 try {
2263 PreEditString pes(im_context);
2264 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2265 pango_layout_set_attributes(layout, pes.attrs);
2267 cairo_move_to(cr, 0, 0);
2268 pango_cairo_show_layout(cr, layout);
2270 g_object_unref(layout);
2271 } catch (...) {
2272 errorStatus = SC_STATUS_FAILURE;
2274 return TRUE;
2277 gboolean ScintillaGTK::DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis) {
2278 return sciThis->DrawPreeditThis(widget, cr);
2281 #else
2283 gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose) {
2284 try {
2285 PreEditString pes(im_context);
2286 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2287 pango_layout_set_attributes(layout, pes.attrs);
2289 cairo_t *context = gdk_cairo_create(reinterpret_cast<GdkDrawable *>(WindowFromWidget(widget)));
2290 cairo_move_to(context, 0, 0);
2291 pango_cairo_show_layout(context, layout);
2292 cairo_destroy(context);
2293 g_object_unref(layout);
2294 } catch (...) {
2295 errorStatus = SC_STATUS_FAILURE;
2297 return TRUE;
2300 gboolean ScintillaGTK::ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2301 return sciThis->ExposePreeditThis(widget, ose);
2304 #endif
2306 bool ScintillaGTK::KoreanIME() {
2307 PreEditString pes(im_context);
2308 if (pes.pscript != PANGO_SCRIPT_COMMON)
2309 lastNonCommonScript = pes.pscript;
2310 return lastNonCommonScript == PANGO_SCRIPT_HANGUL;
2313 void ScintillaGTK::MoveImeCarets(int pos) {
2314 // Move carets relatively by bytes
2315 for (size_t r=0; r<sel.Count(); r++) {
2316 int positionInsert = sel.Range(r).Start().Position();
2317 sel.Range(r).caret.SetPosition(positionInsert + pos);
2318 sel.Range(r).anchor.SetPosition(positionInsert + pos);
2322 void ScintillaGTK::DrawImeIndicator(int indicator, int len) {
2323 // Emulate the visual style of IME characters with indicators.
2324 // Draw an indicator on the character before caret by the character bytes of len
2325 // so it should be called after addCharUTF().
2326 // It does not affect caret positions.
2327 if (indicator < 8 || indicator > INDIC_MAX) {
2328 return;
2330 pdoc->decorations.SetCurrentIndicator(indicator);
2331 for (size_t r=0; r<sel.Count(); r++) {
2332 int positionInsert = sel.Range(r).Start().Position();
2333 pdoc->DecorationFillRange(positionInsert - len, 1, len);
2337 static std::vector<int> MapImeIndicators(PangoAttrList *attrs, const char *u8Str) {
2338 // Map input style to scintilla ime indicator.
2339 // Attrs position points between UTF-8 bytes.
2340 // Indicator index to be returned is character based though.
2341 glong charactersLen = g_utf8_strlen(u8Str, strlen(u8Str));
2342 std::vector<int> indicator(charactersLen, SC_INDICATOR_UNKNOWN);
2344 PangoAttrIterator *iterunderline = pango_attr_list_get_iterator(attrs);
2345 if (iterunderline) {
2346 do {
2347 PangoAttribute *attrunderline = pango_attr_iterator_get(iterunderline, PANGO_ATTR_UNDERLINE);
2348 if (attrunderline) {
2349 glong start = g_utf8_strlen(u8Str, attrunderline->start_index);
2350 glong end = g_utf8_strlen(u8Str, attrunderline->end_index);
2351 PangoUnderline uline = (PangoUnderline)((PangoAttrInt *)attrunderline)->value;
2352 for (glong i=start; i < end; ++i) {
2353 switch (uline) {
2354 case PANGO_UNDERLINE_NONE:
2355 indicator[i] = SC_INDICATOR_UNKNOWN;
2356 break;
2357 case PANGO_UNDERLINE_SINGLE: // normal input
2358 indicator[i] = SC_INDICATOR_INPUT;
2359 break;
2360 case PANGO_UNDERLINE_DOUBLE:
2361 case PANGO_UNDERLINE_LOW:
2362 case PANGO_UNDERLINE_ERROR:
2363 break;
2367 } while (pango_attr_iterator_next(iterunderline));
2368 pango_attr_iterator_destroy(iterunderline);
2371 PangoAttrIterator *itercolor = pango_attr_list_get_iterator(attrs);
2372 if (itercolor) {
2373 do {
2374 PangoAttribute *backcolor = pango_attr_iterator_get(itercolor, PANGO_ATTR_BACKGROUND);
2375 if (backcolor) {
2376 glong start = g_utf8_strlen(u8Str, backcolor->start_index);
2377 glong end = g_utf8_strlen(u8Str, backcolor->end_index);
2378 for (glong i=start; i < end; ++i) {
2379 indicator[i] = SC_INDICATOR_TARGET; // target converted
2382 } while (pango_attr_iterator_next(itercolor));
2383 pango_attr_iterator_destroy(itercolor);
2385 return indicator;
2388 void ScintillaGTK::SetCandidateWindowPos() {
2389 // Composition box accompanies candidate box.
2390 Point pt = PointMainCaret();
2391 GdkRectangle imeBox = {0}; // No need to set width
2392 imeBox.x = pt.x; // Only need positiion
2393 imeBox.y = pt.y + vs.lineHeight; // underneath the first charater
2394 gtk_im_context_set_cursor_location(im_context, &imeBox);
2397 void ScintillaGTK::CommitThis(char *commitStr) {
2398 try {
2399 //~ fprintf(stderr, "Commit '%s'\n", commitStr);
2400 view.imeCaretBlockOverride = false;
2402 if (pdoc->TentativeActive()) {
2403 pdoc->TentativeUndo();
2406 const char *charSetSource = CharacterSetID();
2408 glong uniStrLen = 0;
2409 gunichar *uniStr = g_utf8_to_ucs4_fast(commitStr, strlen(commitStr), &uniStrLen);
2410 for (glong i = 0; i < uniStrLen; i++) {
2411 gchar u8Char[UTF8MaxBytes+2] = {0};
2412 gint u8CharLen = g_unichar_to_utf8(uniStr[i], u8Char);
2413 std::string docChar = u8Char;
2414 if (!IsUnicodeMode())
2415 docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
2417 AddCharUTF(docChar.c_str(), docChar.size());
2419 g_free(uniStr);
2420 ShowCaretAtCurrentPosition();
2421 } catch (...) {
2422 errorStatus = SC_STATUS_FAILURE;
2426 void ScintillaGTK::Commit(GtkIMContext *, char *str, ScintillaGTK *sciThis) {
2427 sciThis->CommitThis(str);
2430 void ScintillaGTK::PreeditChangedInlineThis() {
2431 // Copy & paste by johnsonj with a lot of helps of Neil
2432 // Great thanks for my foreruners, jiniya and BLUEnLIVE
2433 try {
2434 if (pdoc->IsReadOnly() || SelectionContainsProtected()) {
2435 gtk_im_context_reset(im_context);
2436 return;
2439 view.imeCaretBlockOverride = false; // If backspace.
2441 if (pdoc->TentativeActive()) {
2442 pdoc->TentativeUndo();
2443 } else {
2444 // No tentative undo means start of this composition so
2445 // fill in any virtual spaces.
2446 ClearBeforeTentativeStart();
2449 PreEditString preeditStr(im_context);
2450 const char *charSetSource = CharacterSetID();
2452 if (!preeditStr.validUTF8 || (charSetSource == NULL)) {
2453 ShowCaretAtCurrentPosition();
2454 return;
2457 if (preeditStr.uniStrLen == 0 || preeditStr.uniStrLen > maxLenInputIME) {
2458 //fprintf(stderr, "Do not allow over 200 chars: %i\n", preeditStr.uniStrLen);
2459 ShowCaretAtCurrentPosition();
2460 return;
2463 pdoc->TentativeStart(); // TentativeActive() from now on
2465 std::vector<int> indicator = MapImeIndicators(preeditStr.attrs, preeditStr.str);
2467 bool tmpRecordingMacro = recordingMacro;
2468 recordingMacro = false;
2469 for (glong i = 0; i < preeditStr.uniStrLen; i++) {
2470 gchar u8Char[UTF8MaxBytes+2] = {0};
2471 gint u8CharLen = g_unichar_to_utf8(preeditStr.uniStr[i], u8Char);
2472 std::string docChar = u8Char;
2473 if (!IsUnicodeMode())
2474 docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
2476 AddCharUTF(docChar.c_str(), docChar.size());
2478 DrawImeIndicator(indicator[i], docChar.size());
2480 recordingMacro = tmpRecordingMacro;
2482 // Move caret to ime cursor position.
2483 int imeEndToImeCaretU32 = preeditStr.cursor_pos - preeditStr.uniStrLen;
2484 int imeCaretPosDoc = pdoc->GetRelativePosition(CurrentPosition(), imeEndToImeCaretU32);
2486 MoveImeCarets(- CurrentPosition() + imeCaretPosDoc);
2488 if (KoreanIME()) {
2489 #if !PLAT_GTK_WIN32
2490 if (preeditStr.cursor_pos > 0) {
2491 int oneCharBefore = pdoc->GetRelativePosition(CurrentPosition(), -1);
2492 MoveImeCarets(- CurrentPosition() + oneCharBefore);
2494 #endif
2495 view.imeCaretBlockOverride = true;
2498 EnsureCaretVisible();
2499 SetCandidateWindowPos();
2500 ShowCaretAtCurrentPosition();
2501 } catch (...) {
2502 errorStatus = SC_STATUS_FAILURE;
2506 void ScintillaGTK::PreeditChangedWindowedThis() {
2507 try {
2508 PreEditString pes(im_context);
2509 if (strlen(pes.str) > 0) {
2510 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2511 pango_layout_set_attributes(layout, pes.attrs);
2513 gint w, h;
2514 pango_layout_get_pixel_size(layout, &w, &h);
2515 g_object_unref(layout);
2517 gint x, y;
2518 gdk_window_get_origin(PWindow(wText), &x, &y);
2520 Point pt = PointMainCaret();
2521 if (pt.x < 0)
2522 pt.x = 0;
2523 if (pt.y < 0)
2524 pt.y = 0;
2526 gtk_window_move(GTK_WINDOW(PWidget(wPreedit)), x + pt.x, y + pt.y);
2527 gtk_window_resize(GTK_WINDOW(PWidget(wPreedit)), w, h);
2528 gtk_widget_show(PWidget(wPreedit));
2529 gtk_widget_queue_draw_area(PWidget(wPreeditDraw), 0, 0, w, h);
2530 } else {
2531 gtk_widget_hide(PWidget(wPreedit));
2533 } catch (...) {
2534 errorStatus = SC_STATUS_FAILURE;
2538 void ScintillaGTK::PreeditChanged(GtkIMContext *, ScintillaGTK *sciThis) {
2539 if ((sciThis->imeInteraction == imeInline) || (sciThis->KoreanIME())) {
2540 sciThis->PreeditChangedInlineThis();
2541 } else {
2542 sciThis->PreeditChangedWindowedThis();
2546 void ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) {
2547 RealizeText(widget, NULL);
2550 void ScintillaGTK::RealizeText(GtkWidget *widget, void*) {
2551 // Set NULL background to avoid automatic clearing so Scintilla responsible for all drawing
2552 if (WindowFromWidget(widget)) {
2553 #if GTK_CHECK_VERSION(3,0,0)
2554 gdk_window_set_background_pattern(WindowFromWidget(widget), NULL);
2555 #else
2556 gdk_window_set_back_pixmap(WindowFromWidget(widget), NULL, FALSE);
2557 #endif
2561 static GObjectClass *scintilla_class_parent_class;
2563 void ScintillaGTK::Dispose(GObject *object) {
2564 try {
2565 ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(object);
2566 ScintillaGTK *sciThis = reinterpret_cast<ScintillaGTK *>(scio->pscin);
2568 if (PWidget(sciThis->scrollbarv)) {
2569 gtk_widget_unparent(PWidget(sciThis->scrollbarv));
2570 sciThis->scrollbarv = NULL;
2573 if (PWidget(sciThis->scrollbarh)) {
2574 gtk_widget_unparent(PWidget(sciThis->scrollbarh));
2575 sciThis->scrollbarh = NULL;
2578 scintilla_class_parent_class->dispose(object);
2579 } catch (...) {
2580 // Its dying so nowhere to save the status
2584 void ScintillaGTK::Destroy(GObject *object) {
2585 try {
2586 ScintillaObject *scio = SCINTILLA(object);
2588 // This avoids a double destruction
2589 if (!scio->pscin)
2590 return;
2591 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(scio->pscin);
2592 //Platform::DebugPrintf("Destroying %x %x\n", sciThis, object);
2593 sciThis->Finalise();
2595 delete sciThis;
2596 scio->pscin = 0;
2597 scintilla_class_parent_class->finalize(object);
2598 } catch (...) {
2599 // Its dead so nowhere to save the status
2603 #if GTK_CHECK_VERSION(3,0,0)
2605 gboolean ScintillaGTK::DrawTextThis(cairo_t *cr) {
2606 try {
2607 paintState = painting;
2608 repaintFullWindow = false;
2610 rcPaint = GetClientRectangle();
2612 PLATFORM_ASSERT(rgnUpdate == NULL);
2613 rgnUpdate = cairo_copy_clip_rectangle_list(cr);
2614 if (rgnUpdate && rgnUpdate->status != CAIRO_STATUS_SUCCESS) {
2615 // If not successful then ignore
2616 fprintf(stderr, "DrawTextThis failed to copy update region %d [%d]\n", rgnUpdate->status, rgnUpdate->num_rectangles);
2617 cairo_rectangle_list_destroy(rgnUpdate);
2618 rgnUpdate = 0;
2621 double x1, y1, x2, y2;
2622 cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
2623 rcPaint.left = x1;
2624 rcPaint.top = y1;
2625 rcPaint.right = x2;
2626 rcPaint.bottom = y2;
2627 PRectangle rcClient = GetClientRectangle();
2628 paintingAllText = rcPaint.Contains(rcClient);
2629 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2630 if (surfaceWindow) {
2631 surfaceWindow->Init(cr, PWidget(wText));
2632 Paint(surfaceWindow, rcPaint);
2633 surfaceWindow->Release();
2634 delete surfaceWindow;
2636 if ((paintState == paintAbandoned) || repaintFullWindow) {
2637 // Painting area was insufficient to cover new styling or brace highlight positions
2638 FullPaint();
2640 paintState = notPainting;
2641 repaintFullWindow = false;
2643 if (rgnUpdate) {
2644 cairo_rectangle_list_destroy(rgnUpdate);
2646 rgnUpdate = 0;
2647 paintState = notPainting;
2648 } catch (...) {
2649 errorStatus = SC_STATUS_FAILURE;
2652 return FALSE;
2655 gboolean ScintillaGTK::DrawText(GtkWidget *, cairo_t *cr, ScintillaGTK *sciThis) {
2656 return sciThis->DrawTextThis(cr);
2659 gboolean ScintillaGTK::DrawThis(cairo_t *cr) {
2660 try {
2661 #ifdef GTK_STYLE_CLASS_SCROLLBARS_JUNCTION /* GTK >= 3.4 */
2662 // if both scrollbars are visible, paint the little square on the bottom right corner
2663 if (verticalScrollBarVisible && horizontalScrollBarVisible && !Wrapping()) {
2664 GtkStyleContext *styleContext = gtk_widget_get_style_context(PWidget(wMain));
2665 PRectangle rc = GetClientRectangle();
2667 gtk_style_context_save(styleContext);
2668 gtk_style_context_add_class(styleContext, GTK_STYLE_CLASS_SCROLLBARS_JUNCTION);
2670 gtk_render_background(styleContext, cr, rc.right, rc.bottom,
2671 verticalScrollBarWidth, horizontalScrollBarHeight);
2672 gtk_render_frame(styleContext, cr, rc.right, rc.bottom,
2673 verticalScrollBarWidth, horizontalScrollBarHeight);
2675 gtk_style_context_restore(styleContext);
2677 #endif
2679 gtk_container_propagate_draw(
2680 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), cr);
2681 gtk_container_propagate_draw(
2682 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), cr);
2683 // Starting from the following version, the expose event are not propagated
2684 // for double buffered non native windows, so we need to call it ourselves
2685 // or keep the default handler
2686 #if GTK_CHECK_VERSION(3,0,0)
2687 // we want to forward on any >= 3.9.2 runtime
2688 if (gtk_check_version(3,9,2) == NULL) {
2689 gtk_container_propagate_draw(
2690 GTK_CONTAINER(PWidget(wMain)), PWidget(wText), cr);
2692 #endif
2693 } catch (...) {
2694 errorStatus = SC_STATUS_FAILURE;
2696 return FALSE;
2699 gboolean ScintillaGTK::DrawMain(GtkWidget *widget, cairo_t *cr) {
2700 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2701 return sciThis->DrawThis(cr);
2704 #else
2706 gboolean ScintillaGTK::ExposeTextThis(GtkWidget * /*widget*/, GdkEventExpose *ose) {
2707 try {
2708 paintState = painting;
2710 rcPaint.left = ose->area.x;
2711 rcPaint.top = ose->area.y;
2712 rcPaint.right = ose->area.x + ose->area.width;
2713 rcPaint.bottom = ose->area.y + ose->area.height;
2715 PLATFORM_ASSERT(rgnUpdate == NULL);
2716 rgnUpdate = gdk_region_copy(ose->region);
2717 PRectangle rcClient = GetClientRectangle();
2718 paintingAllText = rcPaint.Contains(rcClient);
2719 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2720 if (surfaceWindow) {
2721 cairo_t *cr = gdk_cairo_create(PWindow(wText));
2722 surfaceWindow->Init(cr, PWidget(wText));
2723 Paint(surfaceWindow, rcPaint);
2724 surfaceWindow->Release();
2725 delete surfaceWindow;
2726 cairo_destroy(cr);
2728 if (paintState == paintAbandoned) {
2729 // Painting area was insufficient to cover new styling or brace highlight positions
2730 FullPaint();
2732 paintState = notPainting;
2734 if (rgnUpdate) {
2735 gdk_region_destroy(rgnUpdate);
2737 rgnUpdate = 0;
2738 } catch (...) {
2739 errorStatus = SC_STATUS_FAILURE;
2742 return FALSE;
2745 gboolean ScintillaGTK::ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2746 return sciThis->ExposeTextThis(widget, ose);
2749 gboolean ScintillaGTK::ExposeMain(GtkWidget *widget, GdkEventExpose *ose) {
2750 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2751 //Platform::DebugPrintf("Expose Main %0d,%0d %0d,%0d\n",
2752 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2753 return sciThis->Expose(widget, ose);
2756 gboolean ScintillaGTK::Expose(GtkWidget *, GdkEventExpose *ose) {
2757 try {
2758 //fprintf(stderr, "Expose %0d,%0d %0d,%0d\n",
2759 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2761 // The text is painted in ExposeText
2762 gtk_container_propagate_expose(
2763 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), ose);
2764 gtk_container_propagate_expose(
2765 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), ose);
2767 } catch (...) {
2768 errorStatus = SC_STATUS_FAILURE;
2770 return FALSE;
2773 #endif
2775 void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2776 try {
2777 sciThis->ScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)), false);
2778 } catch (...) {
2779 sciThis->errorStatus = SC_STATUS_FAILURE;
2783 void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2784 try {
2785 sciThis->HorizontalScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)));
2786 } catch (...) {
2787 sciThis->errorStatus = SC_STATUS_FAILURE;
2791 void ScintillaGTK::SelectionReceived(GtkWidget *widget,
2792 GtkSelectionData *selection_data, guint) {
2793 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2794 //Platform::DebugPrintf("Selection received\n");
2795 sciThis->ReceivedSelection(selection_data);
2798 void ScintillaGTK::SelectionGet(GtkWidget *widget,
2799 GtkSelectionData *selection_data, guint info, guint) {
2800 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2801 try {
2802 //Platform::DebugPrintf("Selection get\n");
2803 if (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY) {
2804 if (sciThis->primary.Empty()) {
2805 sciThis->CopySelectionRange(&sciThis->primary);
2807 sciThis->GetSelection(selection_data, info, &sciThis->primary);
2809 } catch (...) {
2810 sciThis->errorStatus = SC_STATUS_FAILURE;
2814 gint ScintillaGTK::SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event) {
2815 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2816 //Platform::DebugPrintf("Selection clear\n");
2817 sciThis->UnclaimSelection(selection_event);
2818 if (GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event) {
2819 return GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event(widget, selection_event);
2821 return TRUE;
2824 gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context,
2825 gint x, gint y, guint dragtime) {
2826 try {
2827 Point npt(x, y);
2828 SetDragPosition(SPositionFromLocation(npt, false, false, UserVirtualSpace()));
2829 #if GTK_CHECK_VERSION(2,22,0)
2830 GdkDragAction preferredAction = gdk_drag_context_get_suggested_action(context);
2831 GdkDragAction actions = gdk_drag_context_get_actions(context);
2832 #else
2833 GdkDragAction preferredAction = context->suggested_action;
2834 GdkDragAction actions = context->actions;
2835 #endif
2836 SelectionPosition pos = SPositionFromLocation(npt);
2837 if ((inDragDrop == ddDragging) && (PositionInSelection(pos.Position()))) {
2838 // Avoid dragging selection onto itself as that produces a move
2839 // with no real effect but which creates undo actions.
2840 preferredAction = static_cast<GdkDragAction>(0);
2841 } else if (actions == static_cast<GdkDragAction>
2842 (GDK_ACTION_COPY | GDK_ACTION_MOVE)) {
2843 preferredAction = GDK_ACTION_MOVE;
2845 gdk_drag_status(context, preferredAction, dragtime);
2846 } catch (...) {
2847 errorStatus = SC_STATUS_FAILURE;
2849 return FALSE;
2852 gboolean ScintillaGTK::DragMotion(GtkWidget *widget, GdkDragContext *context,
2853 gint x, gint y, guint dragtime) {
2854 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2855 return sciThis->DragMotionThis(context, x, y, dragtime);
2858 void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, guint) {
2859 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2860 try {
2861 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2862 //Platform::DebugPrintf("DragLeave %x\n", sciThis);
2863 } catch (...) {
2864 sciThis->errorStatus = SC_STATUS_FAILURE;
2868 void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) {
2869 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2870 try {
2871 // If drag did not result in drop here or elsewhere
2872 if (!sciThis->dragWasDropped)
2873 sciThis->SetEmptySelection(sciThis->posDrag);
2874 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2875 //Platform::DebugPrintf("DragEnd %x %d\n", sciThis, sciThis->dragWasDropped);
2876 sciThis->inDragDrop = ddNone;
2877 } catch (...) {
2878 sciThis->errorStatus = SC_STATUS_FAILURE;
2882 gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/,
2883 gint, gint, guint) {
2884 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2885 try {
2886 //Platform::DebugPrintf("Drop %x\n", sciThis);
2887 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2888 } catch (...) {
2889 sciThis->errorStatus = SC_STATUS_FAILURE;
2891 return FALSE;
2894 void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*context*/,
2895 gint, gint, GtkSelectionData *selection_data, guint /*info*/, guint) {
2896 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2897 try {
2898 sciThis->ReceivedDrop(selection_data);
2899 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2900 } catch (...) {
2901 sciThis->errorStatus = SC_STATUS_FAILURE;
2905 void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context,
2906 GtkSelectionData *selection_data, guint info, guint) {
2907 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2908 try {
2909 sciThis->dragWasDropped = true;
2910 if (!sciThis->sel.Empty()) {
2911 sciThis->GetSelection(selection_data, info, &sciThis->drag);
2913 #if GTK_CHECK_VERSION(2,22,0)
2914 GdkDragAction action = gdk_drag_context_get_selected_action(context);
2915 #else
2916 GdkDragAction action = context->action;
2917 #endif
2918 if (action == GDK_ACTION_MOVE) {
2919 for (size_t r=0; r<sciThis->sel.Count(); r++) {
2920 if (sciThis->posDrop >= sciThis->sel.Range(r).Start()) {
2921 if (sciThis->posDrop > sciThis->sel.Range(r).End()) {
2922 sciThis->posDrop.Add(-sciThis->sel.Range(r).Length());
2923 } else {
2924 sciThis->posDrop.Add(-SelectionRange(sciThis->posDrop, sciThis->sel.Range(r).Start()).Length());
2928 sciThis->ClearSelection();
2930 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2931 } catch (...) {
2932 sciThis->errorStatus = SC_STATUS_FAILURE;
2936 int ScintillaGTK::TimeOut(gpointer ptt) {
2937 TimeThunk *tt = static_cast<TimeThunk *>(ptt);
2938 tt->scintilla->TickFor(tt->reason);
2939 return 1;
2942 gboolean ScintillaGTK::IdleCallback(gpointer pSci) {
2943 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
2944 // Idler will be automatically stopped, if there is nothing
2945 // to do while idle.
2946 bool ret = sciThis->Idle();
2947 if (ret == false) {
2948 // FIXME: This will remove the idler from GTK, we don't want to
2949 // remove it as it is removed automatically when this function
2950 // returns false (although, it should be harmless).
2951 sciThis->SetIdle(false);
2953 return ret;
2956 gboolean ScintillaGTK::StyleIdle(gpointer pSci) {
2957 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
2958 sciThis->IdleWork();
2959 // Idler will be automatically stopped
2960 return FALSE;
2963 void ScintillaGTK::QueueIdleWork(WorkNeeded::workItems items, int upTo) {
2964 Editor::QueueIdleWork(items, upTo);
2965 if (!workNeeded.active) {
2966 // Only allow one style needed to be queued
2967 workNeeded.active = true;
2968 gdk_threads_add_idle_full(G_PRIORITY_HIGH_IDLE, StyleIdle, this, NULL);
2972 void ScintillaGTK::PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis) {
2973 guint action = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(menuItem), "CmdNum"));
2974 if (action) {
2975 sciThis->Command(action);
2979 gboolean ScintillaGTK::PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis) {
2980 try {
2981 if (event->window != WindowFromWidget(widget))
2982 return FALSE;
2983 if (event->type != GDK_BUTTON_PRESS)
2984 return FALSE;
2985 Point pt;
2986 pt.x = int(event->x);
2987 pt.y = int(event->y);
2988 sciThis->ct.MouseClick(pt);
2989 sciThis->CallTipClick();
2990 } catch (...) {
2992 return TRUE;
2995 #if GTK_CHECK_VERSION(3,0,0)
2997 gboolean ScintillaGTK::DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip) {
2998 try {
2999 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
3000 if (surfaceWindow) {
3001 surfaceWindow->Init(cr, widget);
3002 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
3003 surfaceWindow->SetDBCSMode(ctip->codePage);
3004 ctip->PaintCT(surfaceWindow);
3005 surfaceWindow->Release();
3006 delete surfaceWindow;
3008 } catch (...) {
3009 // No pointer back to Scintilla to save status
3011 return TRUE;
3014 #else
3016 gboolean ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, CallTip *ctip) {
3017 try {
3018 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
3019 if (surfaceWindow) {
3020 cairo_t *cr = gdk_cairo_create(WindowFromWidget(widget));
3021 surfaceWindow->Init(cr, widget);
3022 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
3023 surfaceWindow->SetDBCSMode(ctip->codePage);
3024 ctip->PaintCT(surfaceWindow);
3025 surfaceWindow->Release();
3026 delete surfaceWindow;
3027 cairo_destroy(cr);
3029 } catch (...) {
3030 // No pointer back to Scintilla to save status
3032 return TRUE;
3035 #endif
3037 sptr_t ScintillaGTK::DirectFunction(
3038 sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3039 return reinterpret_cast<ScintillaGTK *>(ptr)->WndProc(iMessage, wParam, lParam);
3042 /* legacy name for scintilla_object_send_message */
3043 GEANY_API_SYMBOL
3044 sptr_t scintilla_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3045 ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
3046 return psci->WndProc(iMessage, wParam, lParam);
3049 GEANY_API_SYMBOL
3050 gintptr scintilla_object_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3051 return scintilla_send_message(sci, iMessage, wParam, lParam);
3054 static void scintilla_class_init(ScintillaClass *klass);
3055 static void scintilla_init(ScintillaObject *sci);
3057 extern void Platform_Initialise();
3058 extern void Platform_Finalise();
3060 /* legacy name for scintilla_object_get_type */
3061 GEANY_API_SYMBOL
3062 GType scintilla_get_type() {
3063 static GType scintilla_type = 0;
3064 try {
3066 if (!scintilla_type) {
3067 scintilla_type = g_type_from_name("ScintillaObject");
3068 if (!scintilla_type) {
3069 static GTypeInfo scintilla_info = {
3070 (guint16) sizeof (ScintillaObjectClass),
3071 NULL, //(GBaseInitFunc)
3072 NULL, //(GBaseFinalizeFunc)
3073 (GClassInitFunc) scintilla_class_init,
3074 NULL, //(GClassFinalizeFunc)
3075 NULL, //gconstpointer data
3076 (guint16) sizeof (ScintillaObject),
3077 0, //n_preallocs
3078 (GInstanceInitFunc) scintilla_init,
3079 NULL //(GTypeValueTable*)
3081 scintilla_type = g_type_register_static(
3082 GTK_TYPE_CONTAINER, "ScintillaObject", &scintilla_info, (GTypeFlags) 0);
3086 } catch (...) {
3088 return scintilla_type;
3091 GEANY_API_SYMBOL
3092 GType scintilla_object_get_type() {
3093 return scintilla_get_type();
3096 void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class) {
3097 Platform_Initialise();
3098 #ifdef SCI_LEXER
3099 Scintilla_LinkLexers();
3100 #endif
3101 atomClipboard = gdk_atom_intern("CLIPBOARD", FALSE);
3102 atomUTF8 = gdk_atom_intern("UTF8_STRING", FALSE);
3103 atomString = GDK_SELECTION_TYPE_STRING;
3104 atomUriList = gdk_atom_intern("text/uri-list", FALSE);
3105 atomDROPFILES_DND = gdk_atom_intern("DROPFILES_DND", FALSE);
3107 // Define default signal handlers for the class: Could move more
3108 // of the signal handlers here (those that currently attached to wDraw
3109 // in Initialise() may require coordinate translation?)
3111 object_class->dispose = Dispose;
3112 object_class->finalize = Destroy;
3113 #if GTK_CHECK_VERSION(3,0,0)
3114 widget_class->get_preferred_width = GetPreferredWidth;
3115 widget_class->get_preferred_height = GetPreferredHeight;
3116 #else
3117 widget_class->size_request = SizeRequest;
3118 #endif
3119 widget_class->size_allocate = SizeAllocate;
3120 #if GTK_CHECK_VERSION(3,0,0)
3121 widget_class->draw = DrawMain;
3122 #else
3123 widget_class->expose_event = ExposeMain;
3124 #endif
3125 widget_class->motion_notify_event = Motion;
3126 widget_class->button_press_event = Press;
3127 widget_class->button_release_event = MouseRelease;
3128 widget_class->scroll_event = ScrollEvent;
3129 widget_class->key_press_event = KeyPress;
3130 widget_class->key_release_event = KeyRelease;
3131 widget_class->focus_in_event = FocusIn;
3132 widget_class->focus_out_event = FocusOut;
3133 widget_class->selection_received = SelectionReceived;
3134 widget_class->selection_get = SelectionGet;
3135 widget_class->selection_clear_event = SelectionClear;
3137 widget_class->drag_data_received = DragDataReceived;
3138 widget_class->drag_motion = DragMotion;
3139 widget_class->drag_leave = DragLeave;
3140 widget_class->drag_end = DragEnd;
3141 widget_class->drag_drop = Drop;
3142 widget_class->drag_data_get = DragDataGet;
3144 widget_class->realize = Realize;
3145 widget_class->unrealize = UnRealize;
3146 widget_class->map = Map;
3147 widget_class->unmap = UnMap;
3149 container_class->forall = MainForAll;
3152 #define SIG_MARSHAL scintilla_marshal_NONE__INT_POINTER
3153 #define MARSHAL_ARGUMENTS G_TYPE_INT, G_TYPE_POINTER
3155 static void scintilla_class_init(ScintillaClass *klass) {
3156 try {
3157 OBJECT_CLASS *object_class = (OBJECT_CLASS*) klass;
3158 GtkWidgetClass *widget_class = (GtkWidgetClass*) klass;
3159 GtkContainerClass *container_class = (GtkContainerClass*) klass;
3161 GSignalFlags sigflags = GSignalFlags(G_SIGNAL_ACTION | G_SIGNAL_RUN_LAST);
3162 scintilla_signals[COMMAND_SIGNAL] = g_signal_new(
3163 "command",
3164 G_TYPE_FROM_CLASS(object_class),
3165 sigflags,
3166 G_STRUCT_OFFSET(ScintillaClass, command),
3167 NULL, //(GSignalAccumulator)
3168 NULL, //(gpointer)
3169 SIG_MARSHAL,
3170 G_TYPE_NONE,
3171 2, MARSHAL_ARGUMENTS);
3173 scintilla_signals[NOTIFY_SIGNAL] = g_signal_new(
3174 SCINTILLA_NOTIFY,
3175 G_TYPE_FROM_CLASS(object_class),
3176 sigflags,
3177 G_STRUCT_OFFSET(ScintillaClass, notify),
3178 NULL,
3179 NULL,
3180 SIG_MARSHAL,
3181 G_TYPE_NONE,
3182 2, MARSHAL_ARGUMENTS);
3184 klass->command = NULL;
3185 klass->notify = NULL;
3186 scintilla_class_parent_class = G_OBJECT_CLASS(g_type_class_peek_parent(klass));
3187 ScintillaGTK::ClassInit(object_class, widget_class, container_class);
3188 } catch (...) {
3192 static void scintilla_init(ScintillaObject *sci) {
3193 try {
3194 gtk_widget_set_can_focus(GTK_WIDGET(sci), TRUE);
3195 sci->pscin = new ScintillaGTK(sci);
3196 } catch (...) {
3200 /* legacy name for scintilla_object_new */
3201 GEANY_API_SYMBOL
3202 GtkWidget* scintilla_new() {
3203 GtkWidget *widget = GTK_WIDGET(g_object_new(scintilla_get_type(), NULL));
3204 gtk_widget_set_direction(widget, GTK_TEXT_DIR_LTR);
3206 return widget;
3209 GEANY_API_SYMBOL
3210 GtkWidget *scintilla_object_new() {
3211 return scintilla_new();
3214 void scintilla_set_id(ScintillaObject *sci, uptr_t id) {
3215 ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
3216 psci->ctrlID = id;
3219 void scintilla_release_resources(void) {
3220 try {
3221 Platform_Finalise();
3222 } catch (...) {