Merge branch 'master' of https://github.com/konsolebox/geany into konsolebox-master
[geany-mirror.git] / scintilla / gtk / ScintillaGTK.cxx
blobcce75ee8b5d7db9f4130c481b7cd87d2eea957f2
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 <gtk/gtk.h>
23 #include <gdk/gdkkeysyms.h>
25 #if defined(__WIN32__) || defined(_MSC_VER)
26 #include <windows.h>
27 #endif
29 #include "Platform.h"
31 #include "ILexer.h"
32 #include "Scintilla.h"
33 #include "ScintillaWidget.h"
34 #ifdef SCI_LEXER
35 #include "SciLexer.h"
36 #endif
37 #include "StringCopy.h"
38 #ifdef SCI_LEXER
39 #include "LexerModule.h"
40 #endif
41 #include "Position.h"
42 #include "SplitVector.h"
43 #include "Partitioning.h"
44 #include "RunStyles.h"
45 #include "ContractionState.h"
46 #include "CellBuffer.h"
47 #include "CallTip.h"
48 #include "KeyMap.h"
49 #include "Indicator.h"
50 #include "XPM.h"
51 #include "LineMarker.h"
52 #include "Style.h"
53 #include "ViewStyle.h"
54 #include "CharClassify.h"
55 #include "Decoration.h"
56 #include "CaseFolder.h"
57 #include "Document.h"
58 #include "CaseConvert.h"
59 #include "UniConversion.h"
60 #include "UnicodeFromUTF8.h"
61 #include "Selection.h"
62 #include "PositionCache.h"
63 #include "EditModel.h"
64 #include "MarginView.h"
65 #include "EditView.h"
66 #include "Editor.h"
67 #include "AutoComplete.h"
68 #include "ScintillaBase.h"
70 #ifdef SCI_LEXER
71 #include "ExternalLexer.h"
72 #endif
74 #include "scintilla-marshal.h"
76 #include "Converter.h"
78 #if defined(__clang__)
79 // Clang 3.0 incorrectly displays sentinel warnings. Fixed by clang 3.1.
80 #pragma GCC diagnostic ignored "-Wsentinel"
81 #endif
83 #if GTK_CHECK_VERSION(2,20,0)
84 #define IS_WIDGET_REALIZED(w) (gtk_widget_get_realized(GTK_WIDGET(w)))
85 #define IS_WIDGET_MAPPED(w) (gtk_widget_get_mapped(GTK_WIDGET(w)))
86 #else
87 #define IS_WIDGET_REALIZED(w) (GTK_WIDGET_REALIZED(w))
88 #define IS_WIDGET_MAPPED(w) (GTK_WIDGET_MAPPED(w))
89 #endif
91 #define SC_INDICATOR_INPUT INDIC_IME
92 #define SC_INDICATOR_TARGET INDIC_IME+1
93 #define SC_INDICATOR_CONVERTED INDIC_IME+2
94 #define SC_INDICATOR_UNKNOWN INDIC_IME_MAX
96 static GdkWindow *WindowFromWidget(GtkWidget *w) {
97 return gtk_widget_get_window(w);
100 #ifdef _MSC_VER
101 // Constant conditional expressions are because of GTK+ headers
102 #pragma warning(disable: 4127)
103 // Ignore unreferenced local functions in GTK+ headers
104 #pragma warning(disable: 4505)
105 #endif
107 #define OBJECT_CLASS GObjectClass
109 #ifdef SCI_NAMESPACE
110 using namespace Scintilla;
111 #endif
113 static GdkWindow *PWindow(const Window &w) {
114 GtkWidget *widget = reinterpret_cast<GtkWidget *>(w.GetID());
115 return gtk_widget_get_window(widget);
118 extern std::string UTF8FromLatin1(const char *s, int len);
120 class ScintillaGTK : public ScintillaBase {
121 _ScintillaObject *sci;
122 Window wText;
123 Window scrollbarv;
124 Window scrollbarh;
125 GtkAdjustment *adjustmentv;
126 GtkAdjustment *adjustmenth;
127 int verticalScrollBarWidth;
128 int horizontalScrollBarHeight;
130 SelectionText primary;
132 GdkEventButton *evbtn;
133 bool capturedMouse;
134 bool dragWasDropped;
135 int lastKey;
136 int rectangularSelectionModifier;
138 GtkWidgetClass *parentClass;
140 static GdkAtom atomClipboard;
141 static GdkAtom atomUTF8;
142 static GdkAtom atomString;
143 static GdkAtom atomUriList;
144 static GdkAtom atomDROPFILES_DND;
145 GdkAtom atomSought;
147 #if PLAT_GTK_WIN32
148 CLIPFORMAT cfColumnSelect;
149 #endif
151 Window wPreedit;
152 Window wPreeditDraw;
153 GtkIMContext *im_context;
154 PangoScript lastNonCommonScript;
156 // Wheel mouse support
157 unsigned int linesPerScroll;
158 GTimeVal lastWheelMouseTime;
159 gint lastWheelMouseDirection;
160 gint wheelMouseIntensity;
162 #if GTK_CHECK_VERSION(3,0,0)
163 cairo_rectangle_list_t *rgnUpdate;
164 #else
165 GdkRegion *rgnUpdate;
166 #endif
167 bool repaintFullWindow;
169 // Private so ScintillaGTK objects can not be copied
170 ScintillaGTK(const ScintillaGTK &);
171 ScintillaGTK &operator=(const ScintillaGTK &);
173 public:
174 explicit ScintillaGTK(_ScintillaObject *sci_);
175 virtual ~ScintillaGTK();
176 static void ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class);
177 private:
178 virtual void Initialise();
179 virtual void Finalise();
180 virtual bool AbandonPaint();
181 virtual void DisplayCursor(Window::Cursor c);
182 virtual bool DragThreshold(Point ptStart, Point ptNow);
183 virtual void StartDrag();
184 int TargetAsUTF8(char *text);
185 int EncodedFromUTF8(char *utf8, char *encoded) const;
186 virtual bool ValidCodePage(int codePage) const;
187 public: // Public for scintilla_send_message
188 virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
189 private:
190 virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
191 struct TimeThunk {
192 TickReason reason;
193 ScintillaGTK *scintilla;
194 guint timer;
195 TimeThunk() : reason(tickCaret), scintilla(NULL), timer(0) {}
197 TimeThunk timers[tickDwell+1];
198 virtual bool FineTickerAvailable();
199 virtual bool FineTickerRunning(TickReason reason);
200 virtual void FineTickerStart(TickReason reason, int millis, int tolerance);
201 virtual void FineTickerCancel(TickReason reason);
202 virtual bool SetIdle(bool on);
203 virtual void SetMouseCapture(bool on);
204 virtual bool HaveMouseCapture();
205 virtual bool PaintContains(PRectangle rc);
206 void FullPaint();
207 virtual PRectangle GetClientRectangle() const;
208 virtual void ScrollText(int linesToMove);
209 virtual void SetVerticalScrollPos();
210 virtual void SetHorizontalScrollPos();
211 virtual bool ModifyScrollBars(int nMax, int nPage);
212 void ReconfigureScrollBars();
213 virtual void NotifyChange();
214 virtual void NotifyFocus(bool focus);
215 virtual void NotifyParent(SCNotification scn);
216 void NotifyKey(int key, int modifiers);
217 void NotifyURIDropped(const char *list);
218 const char *CharacterSetID() const;
219 virtual CaseFolder *CaseFolderForEncoding();
220 virtual std::string CaseMapString(const std::string &s, int caseMapping);
221 virtual int KeyDefault(int key, int modifiers);
222 virtual void CopyToClipboard(const SelectionText &selectedText);
223 virtual void Copy();
224 virtual void Paste();
225 virtual void CreateCallTipWindow(PRectangle rc);
226 virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
227 bool OwnPrimarySelection();
228 virtual void ClaimSelection();
229 void GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText);
230 void ReceivedSelection(GtkSelectionData *selection_data);
231 void ReceivedDrop(GtkSelectionData *selection_data);
232 static void GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *selected);
233 void StoreOnClipboard(SelectionText *clipText);
234 static void ClipboardGetSelection(GtkClipboard* clip, GtkSelectionData *selection_data, guint info, void *data);
235 static void ClipboardClearSelection(GtkClipboard* clip, void *data);
237 void UnclaimSelection(GdkEventSelection *selection_event);
238 void Resize(int width, int height);
240 // Callback functions
241 void RealizeThis(GtkWidget *widget);
242 static void Realize(GtkWidget *widget);
243 void UnRealizeThis(GtkWidget *widget);
244 static void UnRealize(GtkWidget *widget);
245 void MapThis();
246 static void Map(GtkWidget *widget);
247 void UnMapThis();
248 static void UnMap(GtkWidget *widget);
249 gint FocusInThis(GtkWidget *widget);
250 static gint FocusIn(GtkWidget *widget, GdkEventFocus *event);
251 gint FocusOutThis(GtkWidget *widget);
252 static gint FocusOut(GtkWidget *widget, GdkEventFocus *event);
253 static void SizeRequest(GtkWidget *widget, GtkRequisition *requisition);
254 #if GTK_CHECK_VERSION(3,0,0)
255 static void GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth);
256 static void GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight);
257 #endif
258 static void SizeAllocate(GtkWidget *widget, GtkAllocation *allocation);
259 #if GTK_CHECK_VERSION(3,0,0)
260 gboolean DrawTextThis(cairo_t *cr);
261 static gboolean DrawText(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
262 gboolean DrawThis(cairo_t *cr);
263 static gboolean DrawMain(GtkWidget *widget, cairo_t *cr);
264 #else
265 gboolean ExposeTextThis(GtkWidget *widget, GdkEventExpose *ose);
266 static gboolean ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
267 gboolean Expose(GtkWidget *widget, GdkEventExpose *ose);
268 static gboolean ExposeMain(GtkWidget *widget, GdkEventExpose *ose);
269 #endif
270 void ForAll(GtkCallback callback, gpointer callback_data);
271 static void MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data);
273 static void ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
274 static void ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
275 gint PressThis(GdkEventButton *event);
276 static gint Press(GtkWidget *widget, GdkEventButton *event);
277 static gint MouseRelease(GtkWidget *widget, GdkEventButton *event);
278 static gint ScrollEvent(GtkWidget *widget, GdkEventScroll *event);
279 static gint Motion(GtkWidget *widget, GdkEventMotion *event);
280 gboolean KeyThis(GdkEventKey *event);
281 static gboolean KeyPress(GtkWidget *widget, GdkEventKey *event);
282 static gboolean KeyRelease(GtkWidget *widget, GdkEventKey *event);
283 #if GTK_CHECK_VERSION(3,0,0)
284 gboolean DrawPreeditThis(GtkWidget *widget, cairo_t *cr);
285 static gboolean DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
286 #else
287 gboolean ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose);
288 static gboolean ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
289 #endif
291 bool KoreanIME();
292 void CommitThis(char *str);
293 static void Commit(GtkIMContext *context, char *str, ScintillaGTK *sciThis);
294 void PreeditChangedInlineThis();
295 void PreeditChangedWindowedThis();
296 static void PreeditChanged(GtkIMContext *context, ScintillaGTK *sciThis);
297 void MoveImeCarets(int pos);
298 void DrawImeIndicator(int indicator, int len);
299 static void GetImeUnderlines(PangoAttrList *attrs, bool *normalInput);
300 static void GetImeBackgrounds(PangoAttrList *attrs, bool *targetInput);
301 void SetCandidateWindowPos();
303 static void StyleSetText(GtkWidget *widget, GtkStyle *previous, void*);
304 static void RealizeText(GtkWidget *widget, void*);
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(TimeThunk *tt);
326 static gboolean IdleCallback(ScintillaGTK *sciThis);
327 static gboolean StyleIdle(ScintillaGTK *sciThis);
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 reinterpret_cast<GtkWidget *>(w.GetID());
381 static ScintillaGTK *ScintillaFromWidget(GtkWidget *widget) {
382 ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(widget);
383 return reinterpret_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_idle_remove_by_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 (*callback) (PWidget(scrollbarv), callback_data);
621 (*callback) (PWidget(scrollbarh), callback_data);
622 } catch (...) {
623 errorStatus = SC_STATUS_FAILURE;
627 void ScintillaGTK::MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data) {
628 ScintillaGTK *sciThis = ScintillaFromWidget((GtkWidget *)container);
630 if (callback != NULL && include_internals) {
631 sciThis->ForAll(callback, callback_data);
635 namespace {
637 class PreEditString {
638 public:
639 gchar *str;
640 gint cursor_pos;
641 PangoAttrList *attrs;
642 gboolean validUTF8;
643 glong uniStrLen;
644 gunichar *uniStr;
645 PangoScript pscript;
647 explicit PreEditString(GtkIMContext *im_context) {
648 gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
649 validUTF8 = g_utf8_validate(str, strlen(str), NULL);
650 uniStr = g_utf8_to_ucs4_fast(str, strlen(str), &uniStrLen);
651 pscript = pango_script_for_unichar(uniStr[0]);
653 ~PreEditString() {
654 g_free(str);
655 g_free(uniStr);
656 pango_attr_list_unref(attrs);
662 gint ScintillaGTK::FocusInThis(GtkWidget *widget) {
663 try {
664 SetFocusState(true);
665 if (im_context != NULL) {
666 PreEditString pes(im_context);
667 if (PWidget(wPreedit) != NULL) {
668 if (strlen(pes.str) > 0) {
669 gtk_widget_show(PWidget(wPreedit));
670 } else {
671 gtk_widget_hide(PWidget(wPreedit));
674 gtk_im_context_focus_in(im_context);
677 } catch (...) {
678 errorStatus = SC_STATUS_FAILURE;
680 return FALSE;
683 gint ScintillaGTK::FocusIn(GtkWidget *widget, GdkEventFocus * /*event*/) {
684 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
685 return sciThis->FocusInThis(widget);
688 gint ScintillaGTK::FocusOutThis(GtkWidget *widget) {
689 try {
690 SetFocusState(false);
692 if (PWidget(wPreedit) != NULL)
693 gtk_widget_hide(PWidget(wPreedit));
694 if (im_context != NULL)
695 gtk_im_context_focus_out(im_context);
697 } catch (...) {
698 errorStatus = SC_STATUS_FAILURE;
700 return FALSE;
703 gint ScintillaGTK::FocusOut(GtkWidget *widget, GdkEventFocus * /*event*/) {
704 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
705 return sciThis->FocusOutThis(widget);
708 void ScintillaGTK::SizeRequest(GtkWidget *widget, GtkRequisition *requisition) {
709 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
710 requisition->width = 1;
711 requisition->height = 1;
712 GtkRequisition child_requisition;
713 #if GTK_CHECK_VERSION(3,0,0)
714 gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarh), NULL, &child_requisition);
715 gtk_widget_get_preferred_size(PWidget(sciThis->scrollbarv), NULL, &child_requisition);
716 #else
717 gtk_widget_size_request(PWidget(sciThis->scrollbarh), &child_requisition);
718 gtk_widget_size_request(PWidget(sciThis->scrollbarv), &child_requisition);
719 #endif
722 #if GTK_CHECK_VERSION(3,0,0)
724 void ScintillaGTK::GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth) {
725 GtkRequisition requisition;
726 SizeRequest(widget, &requisition);
727 *minimalWidth = *naturalWidth = requisition.width;
730 void ScintillaGTK::GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight) {
731 GtkRequisition requisition;
732 SizeRequest(widget, &requisition);
733 *minimalHeight = *naturalHeight = requisition.height;
736 #endif
738 void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) {
739 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
740 try {
741 gtk_widget_set_allocation(widget, allocation);
742 if (IS_WIDGET_REALIZED(widget))
743 gdk_window_move_resize(WindowFromWidget(widget),
744 allocation->x,
745 allocation->y,
746 allocation->width,
747 allocation->height);
749 sciThis->Resize(allocation->width, allocation->height);
751 } catch (...) {
752 sciThis->errorStatus = SC_STATUS_FAILURE;
756 void ScintillaGTK::Initialise() {
757 //Platform::DebugPrintf("ScintillaGTK::Initialise\n");
758 parentClass = reinterpret_cast<GtkWidgetClass *>(
759 g_type_class_ref(gtk_container_get_type()));
761 gtk_widget_set_can_focus(PWidget(wMain), TRUE);
762 gtk_widget_set_sensitive(PWidget(wMain), TRUE);
763 gtk_widget_set_events(PWidget(wMain),
764 GDK_EXPOSURE_MASK
765 | GDK_SCROLL_MASK
766 | GDK_STRUCTURE_MASK
767 | GDK_KEY_PRESS_MASK
768 | GDK_KEY_RELEASE_MASK
769 | GDK_FOCUS_CHANGE_MASK
770 | GDK_LEAVE_NOTIFY_MASK
771 | GDK_BUTTON_PRESS_MASK
772 | GDK_BUTTON_RELEASE_MASK
773 | GDK_POINTER_MOTION_MASK
774 | GDK_POINTER_MOTION_HINT_MASK);
776 wText = gtk_drawing_area_new();
777 gtk_widget_set_parent(PWidget(wText), PWidget(wMain));
778 GtkWidget *widtxt = PWidget(wText); // No code inside the G_OBJECT macro
779 gtk_widget_show(widtxt);
780 #if GTK_CHECK_VERSION(3,0,0)
781 g_signal_connect(G_OBJECT(widtxt), "draw",
782 G_CALLBACK(ScintillaGTK::DrawText), this);
783 #else
784 g_signal_connect(G_OBJECT(widtxt), "expose_event",
785 G_CALLBACK(ScintillaGTK::ExposeText), this);
786 #endif
787 #if GTK_CHECK_VERSION(3,0,0)
788 // we need a runtime check because we don't want double buffering when
789 // running on >= 3.9.2
790 if (gtk_check_version(3,9,2) != NULL /* on < 3.9.2 */)
791 #endif
793 #if !GTK_CHECK_VERSION(3,14,0)
794 // Avoid background drawing flash/missing redraws
795 gtk_widget_set_double_buffered(widtxt, FALSE);
796 #endif
798 gtk_widget_set_events(widtxt, GDK_EXPOSURE_MASK);
799 gtk_widget_set_size_request(widtxt, 100, 100);
800 adjustmentv = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 201.0, 1.0, 20.0, 20.0));
801 #if GTK_CHECK_VERSION(3,0,0)
802 scrollbarv = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT(adjustmentv));
803 #else
804 scrollbarv = gtk_vscrollbar_new(GTK_ADJUSTMENT(adjustmentv));
805 #endif
806 gtk_widget_set_can_focus(PWidget(scrollbarv), FALSE);
807 g_signal_connect(G_OBJECT(adjustmentv), "value_changed",
808 G_CALLBACK(ScrollSignal), this);
809 gtk_widget_set_parent(PWidget(scrollbarv), PWidget(wMain));
810 gtk_widget_show(PWidget(scrollbarv));
812 adjustmenth = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 101.0, 1.0, 20.0, 20.0));
813 #if GTK_CHECK_VERSION(3,0,0)
814 scrollbarh = gtk_scrollbar_new(GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT(adjustmenth));
815 #else
816 scrollbarh = gtk_hscrollbar_new(GTK_ADJUSTMENT(adjustmenth));
817 #endif
818 gtk_widget_set_can_focus(PWidget(scrollbarh), FALSE);
819 g_signal_connect(G_OBJECT(adjustmenth), "value_changed",
820 G_CALLBACK(ScrollHSignal), this);
821 gtk_widget_set_parent(PWidget(scrollbarh), PWidget(wMain));
822 gtk_widget_show(PWidget(scrollbarh));
824 gtk_widget_grab_focus(PWidget(wMain));
826 gtk_drag_dest_set(GTK_WIDGET(PWidget(wMain)),
827 GTK_DEST_DEFAULT_ALL, clipboardPasteTargets, nClipboardPasteTargets,
828 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE));
830 /* create pre-edit window */
831 wPreedit = gtk_window_new(GTK_WINDOW_POPUP);
832 wPreeditDraw = gtk_drawing_area_new();
833 GtkWidget *predrw = PWidget(wPreeditDraw); // No code inside the G_OBJECT macro
834 #if GTK_CHECK_VERSION(3,0,0)
835 g_signal_connect(G_OBJECT(predrw), "draw",
836 G_CALLBACK(DrawPreedit), this);
837 #else
838 g_signal_connect(G_OBJECT(predrw), "expose_event",
839 G_CALLBACK(ExposePreedit), this);
840 #endif
841 gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw);
842 gtk_widget_show(predrw);
844 // Set caret period based on GTK settings
845 gboolean blinkOn = false;
846 if (g_object_class_find_property(G_OBJECT_GET_CLASS(
847 G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink")) {
848 g_object_get(G_OBJECT(
849 gtk_settings_get_default()), "gtk-cursor-blink", &blinkOn, NULL);
851 if (blinkOn &&
852 g_object_class_find_property(G_OBJECT_GET_CLASS(
853 G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink-time")) {
854 gint value;
855 g_object_get(G_OBJECT(
856 gtk_settings_get_default()), "gtk-cursor-blink-time", &value, NULL);
857 caret.period = gint(value / 1.75);
858 } else {
859 caret.period = 0;
862 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
863 timers[tr].reason = tr;
864 timers[tr].scintilla = this;
866 vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
867 vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
868 vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
869 vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
872 void ScintillaGTK::Finalise() {
873 for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
874 FineTickerCancel(tr);
876 ScintillaBase::Finalise();
879 bool ScintillaGTK::AbandonPaint() {
880 if ((paintState == painting) && !paintingAllText) {
881 repaintFullWindow = true;
883 return false;
886 void ScintillaGTK::DisplayCursor(Window::Cursor c) {
887 if (cursorMode == SC_CURSORNORMAL)
888 wText.SetCursor(c);
889 else
890 wText.SetCursor(static_cast<Window::Cursor>(cursorMode));
893 bool ScintillaGTK::DragThreshold(Point ptStart, Point ptNow) {
894 return gtk_drag_check_threshold(GTK_WIDGET(PWidget(wMain)),
895 ptStart.x, ptStart.y, ptNow.x, ptNow.y);
898 void ScintillaGTK::StartDrag() {
899 PLATFORM_ASSERT(evbtn != 0);
900 dragWasDropped = false;
901 inDragDrop = ddDragging;
902 GtkTargetList *tl = gtk_target_list_new(clipboardCopyTargets, nClipboardCopyTargets);
903 #if GTK_CHECK_VERSION(3,10,0)
904 gtk_drag_begin_with_coordinates(GTK_WIDGET(PWidget(wMain)),
906 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
907 evbtn->button,
908 reinterpret_cast<GdkEvent *>(evbtn),
909 -1, -1);
910 #else
911 gtk_drag_begin(GTK_WIDGET(PWidget(wMain)),
913 static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
914 evbtn->button,
915 reinterpret_cast<GdkEvent *>(evbtn));
916 #endif
919 static std::string ConvertText(const char *s, size_t len, const char *charSetDest,
920 const char *charSetSource, bool transliterations, bool silent=false) {
921 // s is not const because of different versions of iconv disagreeing about const
922 std::string destForm;
923 Converter conv(charSetDest, charSetSource, transliterations);
924 if (conv) {
925 size_t outLeft = len*3+1;
926 destForm = std::string(outLeft, '\0');
927 // g_iconv does not actually write to its input argument so safe to cast away const
928 char *pin = const_cast<char *>(s);
929 size_t inLeft = len;
930 char *putf = &destForm[0];
931 char *pout = putf;
932 size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
933 if (conversions == ((size_t)(-1))) {
934 if (!silent) {
935 if (len == 1)
936 fprintf(stderr, "iconv %s->%s failed for %0x '%s'\n",
937 charSetSource, charSetDest, (unsigned char)(*s), s);
938 else
939 fprintf(stderr, "iconv %s->%s failed for %s\n",
940 charSetSource, charSetDest, s);
942 destForm = std::string();
943 } else {
944 destForm.resize(pout - putf);
946 } else {
947 fprintf(stderr, "Can not iconv %s %s\n", charSetDest, charSetSource);
949 return destForm;
952 // Returns the target converted to UTF8.
953 // Return the length in bytes.
954 int ScintillaGTK::TargetAsUTF8(char *text) {
955 int targetLength = targetEnd - targetStart;
956 if (IsUnicodeMode()) {
957 if (text) {
958 pdoc->GetCharRange(text, targetStart, targetLength);
960 } else {
961 // Need to convert
962 const char *charSetBuffer = CharacterSetID();
963 if (*charSetBuffer) {
964 std::string s = RangeText(targetStart, targetEnd);
965 std::string tmputf = ConvertText(&s[0], targetLength, "UTF-8", charSetBuffer, false);
966 if (text) {
967 memcpy(text, tmputf.c_str(), tmputf.length());
969 return tmputf.length();
970 } else {
971 if (text) {
972 pdoc->GetCharRange(text, targetStart, targetLength);
976 return targetLength;
979 // Translates a nul terminated UTF8 string into the document encoding.
980 // Return the length of the result in bytes.
981 int ScintillaGTK::EncodedFromUTF8(char *utf8, char *encoded) const {
982 int inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8);
983 if (IsUnicodeMode()) {
984 if (encoded) {
985 memcpy(encoded, utf8, inputLength);
987 return inputLength;
988 } else {
989 // Need to convert
990 const char *charSetBuffer = CharacterSetID();
991 if (*charSetBuffer) {
992 std::string tmpEncoded = ConvertText(utf8, inputLength, charSetBuffer, "UTF-8", true);
993 if (encoded) {
994 memcpy(encoded, tmpEncoded.c_str(), tmpEncoded.length());
996 return tmpEncoded.length();
997 } else {
998 if (encoded) {
999 memcpy(encoded, utf8, inputLength);
1001 return inputLength;
1004 // Fail
1005 return 0;
1008 bool ScintillaGTK::ValidCodePage(int codePage) const {
1009 return codePage == 0
1010 || codePage == SC_CP_UTF8
1011 || codePage == 932
1012 || codePage == 936
1013 || codePage == 949
1014 || codePage == 950
1015 || codePage == 1361;
1018 sptr_t ScintillaGTK::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
1019 try {
1020 switch (iMessage) {
1022 case SCI_GRABFOCUS:
1023 gtk_widget_grab_focus(PWidget(wMain));
1024 break;
1026 case SCI_GETDIRECTFUNCTION:
1027 return reinterpret_cast<sptr_t>(DirectFunction);
1029 case SCI_GETDIRECTPOINTER:
1030 return reinterpret_cast<sptr_t>(this);
1032 #ifdef SCI_LEXER
1033 case SCI_LOADLEXERLIBRARY:
1034 LexerManager::GetInstance()->Load(reinterpret_cast<const char*>(lParam));
1035 break;
1036 #endif
1037 case SCI_TARGETASUTF8:
1038 return TargetAsUTF8(reinterpret_cast<char*>(lParam));
1040 case SCI_ENCODEDFROMUTF8:
1041 return EncodedFromUTF8(reinterpret_cast<char*>(wParam),
1042 reinterpret_cast<char*>(lParam));
1044 case SCI_SETRECTANGULARSELECTIONMODIFIER:
1045 rectangularSelectionModifier = wParam;
1046 break;
1048 case SCI_GETRECTANGULARSELECTIONMODIFIER:
1049 return rectangularSelectionModifier;
1051 default:
1052 return ScintillaBase::WndProc(iMessage, wParam, lParam);
1054 } catch (std::bad_alloc&) {
1055 errorStatus = SC_STATUS_BADALLOC;
1056 } catch (...) {
1057 errorStatus = SC_STATUS_FAILURE;
1059 return 0l;
1062 sptr_t ScintillaGTK::DefWndProc(unsigned int, uptr_t, sptr_t) {
1063 return 0;
1067 * Report that this Editor subclass has a working implementation of FineTickerStart.
1069 bool ScintillaGTK::FineTickerAvailable() {
1070 return true;
1073 bool ScintillaGTK::FineTickerRunning(TickReason reason) {
1074 return timers[reason].timer != 0;
1077 void ScintillaGTK::FineTickerStart(TickReason reason, int millis, int /* tolerance */) {
1078 FineTickerCancel(reason);
1079 timers[reason].timer = g_timeout_add(millis, reinterpret_cast<GSourceFunc>(TimeOut), &timers[reason]);
1082 void ScintillaGTK::FineTickerCancel(TickReason reason) {
1083 if (timers[reason].timer) {
1084 g_source_remove(timers[reason].timer);
1085 timers[reason].timer = 0;
1089 bool ScintillaGTK::SetIdle(bool on) {
1090 if (on) {
1091 // Start idler, if it's not running.
1092 if (!idler.state) {
1093 idler.state = true;
1094 idler.idlerID = reinterpret_cast<IdlerID>(
1095 g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
1096 reinterpret_cast<GSourceFunc>(IdleCallback), this, NULL));
1098 } else {
1099 // Stop idler, if it's running
1100 if (idler.state) {
1101 idler.state = false;
1102 g_source_remove(GPOINTER_TO_UINT(idler.idlerID));
1105 return true;
1108 void ScintillaGTK::SetMouseCapture(bool on) {
1109 if (mouseDownCaptures) {
1110 if (on) {
1111 gtk_grab_add(GTK_WIDGET(PWidget(wMain)));
1112 } else {
1113 gtk_grab_remove(GTK_WIDGET(PWidget(wMain)));
1116 capturedMouse = on;
1119 bool ScintillaGTK::HaveMouseCapture() {
1120 return capturedMouse;
1123 #if GTK_CHECK_VERSION(3,0,0)
1125 // Is crcTest completely in crcContainer?
1126 static bool CRectContains(const cairo_rectangle_t &crcContainer, const cairo_rectangle_t &crcTest) {
1127 return
1128 (crcTest.x >= crcContainer.x) && ((crcTest.x + crcTest.width) <= (crcContainer.x + crcContainer.width)) &&
1129 (crcTest.y >= crcContainer.y) && ((crcTest.y + crcTest.height) <= (crcContainer.y + crcContainer.height));
1132 // Is crcTest completely in crcListContainer?
1133 // May incorrectly return false if complex shape
1134 static bool CRectListContains(const cairo_rectangle_list_t *crcListContainer, const cairo_rectangle_t &crcTest) {
1135 for (int r=0; r<crcListContainer->num_rectangles; r++) {
1136 if (CRectContains(crcListContainer->rectangles[r], crcTest))
1137 return true;
1139 return false;
1142 #endif
1144 bool ScintillaGTK::PaintContains(PRectangle rc) {
1145 // This allows optimization when a rectangle is completely in the update region.
1146 // It is OK to return false when too difficult to determine as that just performs extra drawing
1147 bool contains = true;
1148 if (paintState == painting) {
1149 if (!rcPaint.Contains(rc)) {
1150 contains = false;
1151 } else if (rgnUpdate) {
1152 #if GTK_CHECK_VERSION(3,0,0)
1153 cairo_rectangle_t grc = {rc.left, rc.top,
1154 rc.right - rc.left, rc.bottom - rc.top};
1155 contains = CRectListContains(rgnUpdate, grc);
1156 #else
1157 GdkRectangle grc = {static_cast<gint>(rc.left), static_cast<gint>(rc.top),
1158 static_cast<gint>(rc.right - rc.left), static_cast<gint>(rc.bottom - rc.top)};
1159 if (gdk_region_rect_in(rgnUpdate, &grc) != GDK_OVERLAP_RECTANGLE_IN) {
1160 contains = false;
1162 #endif
1165 return contains;
1168 // Redraw all of text area. This paint will not be abandoned.
1169 void ScintillaGTK::FullPaint() {
1170 wText.InvalidateAll();
1173 PRectangle ScintillaGTK::GetClientRectangle() const {
1174 Window &win = const_cast<Window &>(wMain);
1175 PRectangle rc = win.GetClientPosition();
1176 if (verticalScrollBarVisible)
1177 rc.right -= verticalScrollBarWidth;
1178 if (horizontalScrollBarVisible && !Wrapping())
1179 rc.bottom -= horizontalScrollBarHeight;
1180 // Move to origin
1181 rc.right -= rc.left;
1182 rc.bottom -= rc.top;
1183 if (rc.bottom < 0)
1184 rc.bottom = 0;
1185 if (rc.right < 0)
1186 rc.right = 0;
1187 rc.left = 0;
1188 rc.top = 0;
1189 return rc;
1192 void ScintillaGTK::ScrollText(int linesToMove) {
1193 int diff = vs.lineHeight * -linesToMove;
1194 //Platform::DebugPrintf("ScintillaGTK::ScrollText %d %d %0d,%0d %0d,%0d\n", linesToMove, diff,
1195 // rc.left, rc.top, rc.right, rc.bottom);
1196 GtkWidget *wi = PWidget(wText);
1197 NotifyUpdateUI();
1199 if (IS_WIDGET_REALIZED(wi)) {
1200 gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
1201 gdk_window_process_updates(WindowFromWidget(wi), FALSE);
1205 void ScintillaGTK::SetVerticalScrollPos() {
1206 DwellEnd(true);
1207 gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmentv), topLine);
1210 void ScintillaGTK::SetHorizontalScrollPos() {
1211 DwellEnd(true);
1212 gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset);
1215 bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) {
1216 bool modified = false;
1217 int pageScroll = LinesToScroll();
1219 if (gtk_adjustment_get_upper(adjustmentv) != (nMax + 1) ||
1220 gtk_adjustment_get_page_size(adjustmentv) != nPage ||
1221 gtk_adjustment_get_page_increment(adjustmentv) != pageScroll) {
1222 gtk_adjustment_set_upper(adjustmentv, nMax + 1);
1223 gtk_adjustment_set_page_size(adjustmentv, nPage);
1224 gtk_adjustment_set_page_increment(adjustmentv, pageScroll);
1225 gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv));
1226 modified = true;
1229 PRectangle rcText = GetTextRectangle();
1230 int horizEndPreferred = scrollWidth;
1231 if (horizEndPreferred < 0)
1232 horizEndPreferred = 0;
1233 unsigned int pageWidth = rcText.Width();
1234 unsigned int pageIncrement = pageWidth / 3;
1235 unsigned int charWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
1236 if (gtk_adjustment_get_upper(adjustmenth) != horizEndPreferred ||
1237 gtk_adjustment_get_page_size(adjustmenth) != pageWidth ||
1238 gtk_adjustment_get_page_increment(adjustmenth) != pageIncrement ||
1239 gtk_adjustment_get_step_increment(adjustmenth) != charWidth) {
1240 gtk_adjustment_set_upper(adjustmenth, horizEndPreferred);
1241 gtk_adjustment_set_page_size(adjustmenth, pageWidth);
1242 gtk_adjustment_set_page_increment(adjustmenth, pageIncrement);
1243 gtk_adjustment_set_step_increment(adjustmenth, charWidth);
1244 gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth));
1245 modified = true;
1247 if (modified && (paintState == painting)) {
1248 repaintFullWindow = true;
1251 return modified;
1254 void ScintillaGTK::ReconfigureScrollBars() {
1255 PRectangle rc = wMain.GetClientPosition();
1256 Resize(rc.Width(), rc.Height());
1259 void ScintillaGTK::NotifyChange() {
1260 g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1261 Platform::LongFromTwoShorts(GetCtrlID(), SCEN_CHANGE), PWidget(wMain));
1264 void ScintillaGTK::NotifyFocus(bool focus) {
1265 g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
1266 Platform::LongFromTwoShorts
1267 (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), PWidget(wMain));
1268 Editor::NotifyFocus(focus);
1271 void ScintillaGTK::NotifyParent(SCNotification scn) {
1272 scn.nmhdr.hwndFrom = PWidget(wMain);
1273 scn.nmhdr.idFrom = GetCtrlID();
1274 g_signal_emit(G_OBJECT(sci), scintilla_signals[NOTIFY_SIGNAL], 0,
1275 GetCtrlID(), &scn);
1278 void ScintillaGTK::NotifyKey(int key, int modifiers) {
1279 SCNotification scn = {};
1280 scn.nmhdr.code = SCN_KEY;
1281 scn.ch = key;
1282 scn.modifiers = modifiers;
1284 NotifyParent(scn);
1287 void ScintillaGTK::NotifyURIDropped(const char *list) {
1288 SCNotification scn = {};
1289 scn.nmhdr.code = SCN_URIDROPPED;
1290 scn.text = list;
1292 NotifyParent(scn);
1295 const char *CharacterSetID(int characterSet);
1297 const char *ScintillaGTK::CharacterSetID() const {
1298 return ::CharacterSetID(vs.styles[STYLE_DEFAULT].characterSet);
1301 class CaseFolderDBCS : public CaseFolderTable {
1302 const char *charSet;
1303 public:
1304 explicit CaseFolderDBCS(const char *charSet_) : charSet(charSet_) {
1305 StandardASCII();
1307 virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
1308 if ((lenMixed == 1) && (sizeFolded > 0)) {
1309 folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
1310 return 1;
1311 } else if (*charSet) {
1312 std::string sUTF8 = ConvertText(mixed, lenMixed,
1313 "UTF-8", charSet, false);
1314 if (!sUTF8.empty()) {
1315 gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
1316 size_t lenMapped = strlen(mapped);
1317 if (lenMapped < sizeFolded) {
1318 memcpy(folded, mapped, lenMapped);
1319 } else {
1320 folded[0] = '\0';
1321 lenMapped = 1;
1323 g_free(mapped);
1324 return lenMapped;
1327 // Something failed so return a single NUL byte
1328 folded[0] = '\0';
1329 return 1;
1333 CaseFolder *ScintillaGTK::CaseFolderForEncoding() {
1334 if (pdoc->dbcsCodePage == SC_CP_UTF8) {
1335 return new CaseFolderUnicode();
1336 } else {
1337 const char *charSetBuffer = CharacterSetID();
1338 if (charSetBuffer) {
1339 if (pdoc->dbcsCodePage == 0) {
1340 CaseFolderTable *pcf = new CaseFolderTable();
1341 pcf->StandardASCII();
1342 // Only for single byte encodings
1343 for (int i=0x80; i<0x100; i++) {
1344 char sCharacter[2] = "A";
1345 sCharacter[0] = i;
1346 // Silent as some bytes have no assigned character
1347 std::string sUTF8 = ConvertText(sCharacter, 1,
1348 "UTF-8", charSetBuffer, false, true);
1349 if (!sUTF8.empty()) {
1350 gchar *mapped = g_utf8_casefold(sUTF8.c_str(), sUTF8.length());
1351 if (mapped) {
1352 std::string mappedBack = ConvertText(mapped, strlen(mapped),
1353 charSetBuffer, "UTF-8", false, true);
1354 if ((mappedBack.length() == 1) && (mappedBack[0] != sCharacter[0])) {
1355 pcf->SetTranslation(sCharacter[0], mappedBack[0]);
1357 g_free(mapped);
1361 return pcf;
1362 } else {
1363 return new CaseFolderDBCS(charSetBuffer);
1366 return 0;
1370 namespace {
1372 struct CaseMapper {
1373 gchar *mapped; // Must be freed with g_free
1374 CaseMapper(const std::string &sUTF8, bool toUpperCase) {
1375 if (toUpperCase) {
1376 mapped = g_utf8_strup(sUTF8.c_str(), sUTF8.length());
1377 } else {
1378 mapped = g_utf8_strdown(sUTF8.c_str(), sUTF8.length());
1381 ~CaseMapper() {
1382 g_free(mapped);
1388 std::string ScintillaGTK::CaseMapString(const std::string &s, int caseMapping) {
1389 if ((s.size() == 0) || (caseMapping == cmSame))
1390 return s;
1392 if (IsUnicodeMode()) {
1393 std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
1394 size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
1395 (caseMapping == cmUpper) ? CaseConversionUpper : CaseConversionLower);
1396 retMapped.resize(lenMapped);
1397 return retMapped;
1400 const char *charSetBuffer = CharacterSetID();
1402 if (!*charSetBuffer) {
1403 CaseMapper mapper(s, caseMapping == cmUpper);
1404 return std::string(mapper.mapped, strlen(mapper.mapped));
1405 } else {
1406 // Change text to UTF-8
1407 std::string sUTF8 = ConvertText(s.c_str(), s.length(),
1408 "UTF-8", charSetBuffer, false);
1409 CaseMapper mapper(sUTF8, caseMapping == cmUpper);
1410 return ConvertText(mapper.mapped, strlen(mapper.mapped), charSetBuffer, "UTF-8", false);
1414 int ScintillaGTK::KeyDefault(int key, int modifiers) {
1415 // Pass up to container in case it is an accelerator
1416 NotifyKey(key, modifiers);
1417 return 0;
1420 void ScintillaGTK::CopyToClipboard(const SelectionText &selectedText) {
1421 SelectionText *clipText = new SelectionText();
1422 clipText->Copy(selectedText);
1423 StoreOnClipboard(clipText);
1426 void ScintillaGTK::Copy() {
1427 if (!sel.Empty()) {
1428 SelectionText *clipText = new SelectionText();
1429 CopySelectionRange(clipText);
1430 StoreOnClipboard(clipText);
1431 #if PLAT_GTK_WIN32
1432 if (sel.IsRectangular()) {
1433 ::OpenClipboard(NULL);
1434 ::SetClipboardData(cfColumnSelect, 0);
1435 ::CloseClipboard();
1437 #endif
1441 void ScintillaGTK::ClipboardReceived(GtkClipboard *clipboard, GtkSelectionData *selection_data, gpointer data) {
1442 ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(data);
1443 sciThis->ReceivedSelection(selection_data);
1446 void ScintillaGTK::Paste() {
1447 atomSought = atomUTF8;
1448 GtkClipboard *clipBoard =
1449 gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard);
1450 if (clipBoard == NULL)
1451 return;
1452 gtk_clipboard_request_contents(clipBoard, atomSought, ClipboardReceived, this);
1455 void ScintillaGTK::CreateCallTipWindow(PRectangle rc) {
1456 if (!ct.wCallTip.Created()) {
1457 ct.wCallTip = gtk_window_new(GTK_WINDOW_POPUP);
1458 ct.wDraw = gtk_drawing_area_new();
1459 GtkWidget *widcdrw = PWidget(ct.wDraw); // // No code inside the G_OBJECT macro
1460 gtk_container_add(GTK_CONTAINER(PWidget(ct.wCallTip)), widcdrw);
1461 #if GTK_CHECK_VERSION(3,0,0)
1462 g_signal_connect(G_OBJECT(widcdrw), "draw",
1463 G_CALLBACK(ScintillaGTK::DrawCT), &ct);
1464 #else
1465 g_signal_connect(G_OBJECT(widcdrw), "expose_event",
1466 G_CALLBACK(ScintillaGTK::ExposeCT), &ct);
1467 #endif
1468 g_signal_connect(G_OBJECT(widcdrw), "button_press_event",
1469 G_CALLBACK(ScintillaGTK::PressCT), static_cast<void *>(this));
1470 gtk_widget_set_events(widcdrw,
1471 GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK);
1473 gtk_widget_set_size_request(PWidget(ct.wDraw), rc.Width(), rc.Height());
1474 ct.wDraw.Show();
1475 if (PWindow(ct.wCallTip)) {
1476 gdk_window_resize(PWindow(ct.wCallTip), rc.Width(), rc.Height());
1480 void ScintillaGTK::AddToPopUp(const char *label, int cmd, bool enabled) {
1481 GtkWidget *menuItem;
1482 if (label[0])
1483 menuItem = gtk_menu_item_new_with_label(label);
1484 else
1485 menuItem = gtk_separator_menu_item_new();
1486 gtk_menu_shell_append(GTK_MENU_SHELL(popup.GetID()), menuItem);
1487 g_object_set_data(G_OBJECT(menuItem), "CmdNum", reinterpret_cast<void *>(cmd));
1488 g_signal_connect(G_OBJECT(menuItem),"activate", G_CALLBACK(PopUpCB), this);
1490 if (cmd) {
1491 if (menuItem)
1492 gtk_widget_set_sensitive(menuItem, enabled);
1496 bool ScintillaGTK::OwnPrimarySelection() {
1497 return ((gdk_selection_owner_get(GDK_SELECTION_PRIMARY)
1498 == PWindow(wMain)) &&
1499 (PWindow(wMain) != NULL));
1502 void ScintillaGTK::ClaimSelection() {
1503 // X Windows has a 'primary selection' as well as the clipboard.
1504 // Whenever the user selects some text, we become the primary selection
1505 if (!sel.Empty() && IS_WIDGET_REALIZED(GTK_WIDGET(PWidget(wMain)))) {
1506 primarySelection = true;
1507 gtk_selection_owner_set(GTK_WIDGET(PWidget(wMain)),
1508 GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1509 primary.Clear();
1510 } else if (OwnPrimarySelection()) {
1511 primarySelection = true;
1512 if (primary.Empty())
1513 gtk_selection_owner_set(NULL, GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
1514 } else {
1515 primarySelection = false;
1516 primary.Clear();
1520 static const guchar *DataOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data(sd); }
1521 static gint LengthOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_length(sd); }
1522 static GdkAtom TypeOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data_type(sd); }
1523 static GdkAtom SelectionOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_selection(sd); }
1525 // Detect rectangular text, convert line ends to current mode, convert from or to UTF-8
1526 void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText) {
1527 const char *data = reinterpret_cast<const char *>(DataOfGSD(selectionData));
1528 int len = LengthOfGSD(selectionData);
1529 GdkAtom selectionTypeData = TypeOfGSD(selectionData);
1531 // Return empty string if selection is not a string
1532 if ((selectionTypeData != GDK_TARGET_STRING) && (selectionTypeData != atomUTF8)) {
1533 selText.Clear();
1534 return;
1537 // Check for "\n\0" ending to string indicating that selection is rectangular
1538 bool isRectangular;
1539 #if PLAT_GTK_WIN32
1540 isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
1541 #else
1542 isRectangular = ((len > 2) && (data[len - 1] == 0 && data[len - 2] == '\n'));
1543 if (isRectangular)
1544 len--; // Forget the extra '\0'
1545 #endif
1547 #if PLAT_GTK_WIN32
1548 // Win32 includes an ending '\0' byte in 'len' for clipboard text from
1549 // external applications; ignore it.
1550 if ((len > 0) && (data[len - 1] == '\0'))
1551 len--;
1552 #endif
1554 std::string dest(data, len);
1555 if (selectionTypeData == GDK_TARGET_STRING) {
1556 if (IsUnicodeMode()) {
1557 // Unknown encoding so assume in Latin1
1558 dest = UTF8FromLatin1(dest.c_str(), dest.length());
1559 selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
1560 } else {
1561 // Assume buffer is in same encoding as selection
1562 selText.Copy(dest, pdoc->dbcsCodePage,
1563 vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1565 } else { // UTF-8
1566 const char *charSetBuffer = CharacterSetID();
1567 if (!IsUnicodeMode() && *charSetBuffer) {
1568 // Convert to locale
1569 dest = ConvertText(dest.c_str(), dest.length(), charSetBuffer, "UTF-8", true);
1570 selText.Copy(dest, pdoc->dbcsCodePage,
1571 vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false);
1572 } else {
1573 selText.Copy(dest, SC_CP_UTF8, 0, isRectangular, false);
1578 void ScintillaGTK::ReceivedSelection(GtkSelectionData *selection_data) {
1579 try {
1580 if ((SelectionOfGSD(selection_data) == atomClipboard) ||
1581 (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY)) {
1582 if ((atomSought == atomUTF8) && (LengthOfGSD(selection_data) <= 0)) {
1583 atomSought = atomString;
1584 gtk_selection_convert(GTK_WIDGET(PWidget(wMain)),
1585 SelectionOfGSD(selection_data), atomSought, GDK_CURRENT_TIME);
1586 } else if ((LengthOfGSD(selection_data) > 0) &&
1587 ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8))) {
1588 SelectionText selText;
1589 GetGtkSelectionText(selection_data, selText);
1591 UndoGroup ug(pdoc);
1592 if (SelectionOfGSD(selection_data) != GDK_SELECTION_PRIMARY) {
1593 ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
1596 InsertPasteShape(selText.Data(), selText.Length(),
1597 selText.rectangular ? pasteRectangular : pasteStream);
1598 EnsureCaretVisible();
1601 // else fprintf(stderr, "Target non string %d %d\n", (int)(selection_data->type),
1602 // (int)(atomUTF8));
1603 Redraw();
1604 } catch (...) {
1605 errorStatus = SC_STATUS_FAILURE;
1609 void ScintillaGTK::ReceivedDrop(GtkSelectionData *selection_data) {
1610 dragWasDropped = true;
1611 if (TypeOfGSD(selection_data) == atomUriList || TypeOfGSD(selection_data) == atomDROPFILES_DND) {
1612 const char *data = reinterpret_cast<const char *>(DataOfGSD(selection_data));
1613 std::vector<char> drop(data, data + LengthOfGSD(selection_data));
1614 drop.push_back('\0');
1615 NotifyURIDropped(&drop[0]);
1616 } else if ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == atomUTF8)) {
1617 if (LengthOfGSD(selection_data) > 0) {
1618 SelectionText selText;
1619 GetGtkSelectionText(selection_data, selText);
1620 DropAt(posDrop, selText.Data(), selText.Length(), false, selText.rectangular);
1622 } else if (LengthOfGSD(selection_data) > 0) {
1623 //~ fprintf(stderr, "ReceivedDrop other %p\n", static_cast<void *>(selection_data->type));
1625 Redraw();
1630 void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *text) {
1631 #if PLAT_GTK_WIN32
1632 // GDK on Win32 expands any \n into \r\n, so make a copy of
1633 // the clip text now with newlines converted to \n. Use { } to hide symbols
1634 // from code below
1635 SelectionText *newline_normalized = NULL;
1637 std::string tmpstr = Document::TransformLineEnds(text->Data(), text->Length(), SC_EOL_LF);
1638 newline_normalized = new SelectionText();
1639 newline_normalized->Copy(tmpstr, SC_CP_UTF8, 0, text->rectangular, false);
1640 text = newline_normalized;
1642 #endif
1644 // Convert text to utf8 if it isn't already
1645 SelectionText *converted = 0;
1646 if ((text->codePage != SC_CP_UTF8) && (info == TARGET_UTF8_STRING)) {
1647 const char *charSet = ::CharacterSetID(text->characterSet);
1648 if (*charSet) {
1649 std::string tmputf = ConvertText(text->Data(), text->Length(), "UTF-8", charSet, false);
1650 converted = new SelectionText();
1651 converted->Copy(tmputf, SC_CP_UTF8, 0, text->rectangular, false);
1652 text = converted;
1656 // Here is a somewhat evil kludge.
1657 // As I can not work out how to store data on the clipboard in multiple formats
1658 // and need some way to mark the clipping as being stream or rectangular,
1659 // the terminating \0 is included in the length for rectangular clippings.
1660 // All other tested aplications behave benignly by ignoring the \0.
1661 // The #if is here because on Windows cfColumnSelect clip entry is used
1662 // instead as standard indicator of rectangularness (so no need to kludge)
1663 const char *textData = text->Data();
1664 int len = text->Length();
1665 #if PLAT_GTK_WIN32 == 0
1666 if (text->rectangular)
1667 len++;
1668 #endif
1670 if (info == TARGET_UTF8_STRING) {
1671 gtk_selection_data_set_text(selection_data, textData, len);
1672 } else {
1673 gtk_selection_data_set(selection_data,
1674 static_cast<GdkAtom>(GDK_SELECTION_TYPE_STRING),
1675 8, reinterpret_cast<const unsigned char *>(textData), len);
1677 delete converted;
1679 #if PLAT_GTK_WIN32
1680 delete newline_normalized;
1681 #endif
1684 void ScintillaGTK::StoreOnClipboard(SelectionText *clipText) {
1685 GtkClipboard *clipBoard =
1686 gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard);
1687 if (clipBoard == NULL) // Occurs if widget isn't in a toplevel
1688 return;
1690 if (gtk_clipboard_set_with_data(clipBoard, clipboardCopyTargets, nClipboardCopyTargets,
1691 ClipboardGetSelection, ClipboardClearSelection, clipText)) {
1692 gtk_clipboard_set_can_store(clipBoard, clipboardCopyTargets, nClipboardCopyTargets);
1696 void ScintillaGTK::ClipboardGetSelection(GtkClipboard *, GtkSelectionData *selection_data, guint info, void *data) {
1697 GetSelection(selection_data, info, static_cast<SelectionText*>(data));
1700 void ScintillaGTK::ClipboardClearSelection(GtkClipboard *, void *data) {
1701 SelectionText *obj = static_cast<SelectionText*>(data);
1702 delete obj;
1705 void ScintillaGTK::UnclaimSelection(GdkEventSelection *selection_event) {
1706 try {
1707 //Platform::DebugPrintf("UnclaimSelection\n");
1708 if (selection_event->selection == GDK_SELECTION_PRIMARY) {
1709 //Platform::DebugPrintf("UnclaimPrimarySelection\n");
1710 if (!OwnPrimarySelection()) {
1711 primary.Clear();
1712 primarySelection = false;
1713 FullPaint();
1716 } catch (...) {
1717 errorStatus = SC_STATUS_FAILURE;
1721 void ScintillaGTK::Resize(int width, int height) {
1722 //Platform::DebugPrintf("Resize %d %d\n", width, height);
1723 //printf("Resize %d %d\n", width, height);
1725 // Not always needed, but some themes can have different sizes of scrollbars
1726 #if GTK_CHECK_VERSION(3,0,0)
1727 GtkRequisition requisition;
1728 gtk_widget_get_preferred_size(PWidget(scrollbarv), NULL, &requisition);
1729 verticalScrollBarWidth = requisition.width;
1730 gtk_widget_get_preferred_size(PWidget(scrollbarh), NULL, &requisition);
1731 horizontalScrollBarHeight = requisition.height;
1732 #else
1733 verticalScrollBarWidth = GTK_WIDGET(PWidget(scrollbarv))->requisition.width;
1734 horizontalScrollBarHeight = GTK_WIDGET(PWidget(scrollbarh))->requisition.height;
1735 #endif
1737 // These allocations should never produce negative sizes as they would wrap around to huge
1738 // unsigned numbers inside GTK+ causing warnings.
1739 bool showSBHorizontal = horizontalScrollBarVisible && !Wrapping();
1741 GtkAllocation alloc;
1742 if (showSBHorizontal) {
1743 gtk_widget_show(GTK_WIDGET(PWidget(scrollbarh)));
1744 alloc.x = 0;
1745 alloc.y = height - horizontalScrollBarHeight;
1746 alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
1747 alloc.height = horizontalScrollBarHeight;
1748 gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarh)), &alloc);
1749 } else {
1750 gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarh)));
1751 horizontalScrollBarHeight = 0; // in case horizontalScrollBarVisible is true.
1754 if (verticalScrollBarVisible) {
1755 gtk_widget_show(GTK_WIDGET(PWidget(scrollbarv)));
1756 alloc.x = width - verticalScrollBarWidth;
1757 alloc.y = 0;
1758 alloc.width = verticalScrollBarWidth;
1759 alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
1760 gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarv)), &alloc);
1761 } else {
1762 gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarv)));
1763 verticalScrollBarWidth = 0;
1765 if (IS_WIDGET_MAPPED(PWidget(wMain))) {
1766 ChangeSize();
1769 alloc.x = 0;
1770 alloc.y = 0;
1771 alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
1772 alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
1773 gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc);
1776 static void SetAdjustmentValue(GtkAdjustment *object, int value) {
1777 GtkAdjustment *adjustment = GTK_ADJUSTMENT(object);
1778 int maxValue = static_cast<int>(
1779 gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size(adjustment));
1781 if (value > maxValue)
1782 value = maxValue;
1783 if (value < 0)
1784 value = 0;
1785 gtk_adjustment_set_value(adjustment, value);
1788 static int modifierTranslated(int sciModifier) {
1789 switch (sciModifier) {
1790 case SCMOD_SHIFT:
1791 return GDK_SHIFT_MASK;
1792 case SCMOD_CTRL:
1793 return GDK_CONTROL_MASK;
1794 case SCMOD_ALT:
1795 return GDK_MOD1_MASK;
1796 case SCMOD_SUPER:
1797 return GDK_MOD4_MASK;
1798 default:
1799 return 0;
1803 gint ScintillaGTK::PressThis(GdkEventButton *event) {
1804 try {
1805 //Platform::DebugPrintf("Press %x time=%d state = %x button = %x\n",this,event->time, event->state, event->button);
1806 // Do not use GTK+ double click events as Scintilla has its own double click detection
1807 if (event->type != GDK_BUTTON_PRESS)
1808 return FALSE;
1810 if (evbtn) {
1811 gdk_event_free(reinterpret_cast<GdkEvent *>(evbtn));
1812 evbtn = 0;
1814 evbtn = reinterpret_cast<GdkEventButton *>(gdk_event_copy(reinterpret_cast<GdkEvent *>(event)));
1815 Point pt;
1816 pt.x = int(event->x);
1817 pt.y = int(event->y);
1818 PRectangle rcClient = GetClientRectangle();
1819 //Platform::DebugPrintf("Press %0d,%0d in %0d,%0d %0d,%0d\n",
1820 // pt.x, pt.y, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
1821 if ((pt.x > rcClient.right) || (pt.y > rcClient.bottom)) {
1822 Platform::DebugPrintf("Bad location\n");
1823 return FALSE;
1826 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
1827 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
1828 // On X, instead of sending literal modifiers use the user specified
1829 // modifier, defaulting to control instead of alt.
1830 // This is because most X window managers grab alt + click for moving
1831 bool alt = (event->state & modifierTranslated(rectangularSelectionModifier)) != 0;
1833 gtk_widget_grab_focus(PWidget(wMain));
1834 if (event->button == 1) {
1835 #if PLAT_GTK_MACOSX
1836 bool meta = ctrl;
1837 // GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
1838 // not GDK_META_MASK like in key events.
1839 ctrl = (event->state & GDK_MOD2_MASK) != 0;
1840 #else
1841 bool meta = false;
1842 #endif
1843 ButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
1844 } else if (event->button == 2) {
1845 // Grab the primary selection if it exists
1846 SelectionPosition pos = SPositionFromLocation(pt, false, false, UserVirtualSpace());
1847 if (OwnPrimarySelection() && primary.Empty())
1848 CopySelectionRange(&primary);
1850 sel.Clear();
1851 SetSelection(pos, pos);
1852 atomSought = atomUTF8;
1853 gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_PRIMARY,
1854 atomSought, event->time);
1855 } else if (event->button == 3) {
1856 if (!PointInSelection(pt))
1857 SetEmptySelection(PositionFromLocation(pt));
1858 if (displayPopupMenu) {
1859 // PopUp menu
1860 // Convert to screen
1861 int ox = 0;
1862 int oy = 0;
1863 gdk_window_get_origin(PWindow(wMain), &ox, &oy);
1864 ContextMenu(Point(pt.x + ox, pt.y + oy));
1865 } else {
1866 return FALSE;
1868 } else if (event->button == 4) {
1869 // Wheel scrolling up (only GTK 1.x does it this way)
1870 if (ctrl)
1871 SetAdjustmentValue(adjustmenth, xOffset - 6);
1872 else
1873 SetAdjustmentValue(adjustmentv, topLine - 3);
1874 } else if (event->button == 5) {
1875 // Wheel scrolling down (only GTK 1.x does it this way)
1876 if (ctrl)
1877 SetAdjustmentValue(adjustmenth, xOffset + 6);
1878 else
1879 SetAdjustmentValue(adjustmentv, topLine + 3);
1881 } catch (...) {
1882 errorStatus = SC_STATUS_FAILURE;
1884 return TRUE;
1887 gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) {
1888 if (event->window != WindowFromWidget(widget))
1889 return FALSE;
1890 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1891 return sciThis->PressThis(event);
1894 gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
1895 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1896 try {
1897 //Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state);
1898 if (!sciThis->HaveMouseCapture())
1899 return FALSE;
1900 if (event->button == 1) {
1901 Point pt;
1902 pt.x = int(event->x);
1903 pt.y = int(event->y);
1904 //Platform::DebugPrintf("Up %x %x %d %d %d\n",
1905 // sciThis,event->window,event->time, pt.x, pt.y);
1906 if (event->window != PWindow(sciThis->wMain))
1907 // If mouse released on scroll bar then the position is relative to the
1908 // scrollbar, not the drawing window so just repeat the most recent point.
1909 pt = sciThis->ptMouseLast;
1910 sciThis->ButtonUp(pt, event->time, (event->state & GDK_CONTROL_MASK) != 0);
1912 } catch (...) {
1913 sciThis->errorStatus = SC_STATUS_FAILURE;
1915 return FALSE;
1918 // win32gtk and GTK >= 2 use SCROLL_* events instead of passing the
1919 // button4/5/6/7 events to the GTK app
1920 gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
1921 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
1922 try {
1924 if (widget == NULL || event == NULL)
1925 return FALSE;
1927 // Compute amount and direction to scroll (even tho on win32 there is
1928 // intensity of scrolling info in the native message, gtk doesn't
1929 // support this so we simulate similarly adaptive scrolling)
1930 // Note that this is disabled on OS X (Darwin) with the X11 backend
1931 // where the X11 server already has an adaptive scrolling algorithm
1932 // that fights with this one
1933 int cLineScroll;
1934 #if defined(__APPLE__) && !defined(GDK_WINDOWING_QUARTZ)
1935 cLineScroll = sciThis->linesPerScroll;
1936 if (cLineScroll == 0)
1937 cLineScroll = 4;
1938 sciThis->wheelMouseIntensity = cLineScroll;
1939 #else
1940 int timeDelta = 1000000;
1941 GTimeVal curTime;
1942 g_get_current_time(&curTime);
1943 if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec)
1944 timeDelta = curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec;
1945 else if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec + 1)
1946 timeDelta = 1000000 + (curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec);
1947 if ((event->direction == sciThis->lastWheelMouseDirection) && (timeDelta < 250000)) {
1948 if (sciThis->wheelMouseIntensity < 12)
1949 sciThis->wheelMouseIntensity++;
1950 cLineScroll = sciThis->wheelMouseIntensity;
1951 } else {
1952 cLineScroll = sciThis->linesPerScroll;
1953 if (cLineScroll == 0)
1954 cLineScroll = 4;
1955 sciThis->wheelMouseIntensity = cLineScroll;
1957 #endif
1958 if (event->direction == GDK_SCROLL_UP || event->direction == GDK_SCROLL_LEFT) {
1959 cLineScroll *= -1;
1961 g_get_current_time(&sciThis->lastWheelMouseTime);
1962 sciThis->lastWheelMouseDirection = event->direction;
1964 // Note: Unpatched versions of win32gtk don't set the 'state' value so
1965 // only regular scrolling is supported there. Also, unpatched win32gtk
1966 // issues spurious button 2 mouse events during wheeling, which can cause
1967 // problems (a patch for both was submitted by archaeopteryx.com on 13Jun2001)
1969 // Data zoom not supported
1970 if (event->state & GDK_SHIFT_MASK) {
1971 return FALSE;
1974 #if GTK_CHECK_VERSION(3,4,0)
1975 // Smooth scrolling not supported
1976 if (event->direction == GDK_SCROLL_SMOOTH) {
1977 return FALSE;
1979 #endif
1981 // Horizontal scrolling
1982 if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) {
1983 sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll);
1985 // Text font size zoom
1986 } else if (event->state & GDK_CONTROL_MASK) {
1987 if (cLineScroll < 0) {
1988 sciThis->KeyCommand(SCI_ZOOMIN);
1989 } else {
1990 sciThis->KeyCommand(SCI_ZOOMOUT);
1993 // Regular scrolling
1994 } else {
1995 sciThis->ScrollTo(sciThis->topLine + cLineScroll);
1997 return TRUE;
1998 } catch (...) {
1999 sciThis->errorStatus = SC_STATUS_FAILURE;
2001 return FALSE;
2004 gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
2005 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2006 try {
2007 //Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time);
2008 if (event->window != WindowFromWidget(widget))
2009 return FALSE;
2010 int x = 0;
2011 int y = 0;
2012 GdkModifierType state;
2013 if (event->is_hint) {
2014 #if GTK_CHECK_VERSION(3,0,0)
2015 gdk_window_get_device_position(event->window,
2016 event->device, &x, &y, &state);
2017 #else
2018 gdk_window_get_pointer(event->window, &x, &y, &state);
2019 #endif
2020 } else {
2021 x = static_cast<int>(event->x);
2022 y = static_cast<int>(event->y);
2023 state = static_cast<GdkModifierType>(event->state);
2025 //Platform::DebugPrintf("Move %x %x %d %c %d %d\n",
2026 // sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y);
2027 Point pt(x, y);
2028 int modifiers = ((event->state & GDK_SHIFT_MASK) != 0 ? SCI_SHIFT : 0) |
2029 ((event->state & GDK_CONTROL_MASK) != 0 ? SCI_CTRL : 0) |
2030 ((event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) != 0 ? SCI_ALT : 0);
2031 sciThis->ButtonMoveWithModifiers(pt, modifiers);
2032 } catch (...) {
2033 sciThis->errorStatus = SC_STATUS_FAILURE;
2035 return FALSE;
2038 // Map the keypad keys to their equivalent functions
2039 static int KeyTranslate(int keyIn) {
2040 switch (keyIn) {
2041 #if GTK_CHECK_VERSION(3,0,0)
2042 case GDK_KEY_ISO_Left_Tab:
2043 return SCK_TAB;
2044 case GDK_KEY_KP_Down:
2045 return SCK_DOWN;
2046 case GDK_KEY_KP_Up:
2047 return SCK_UP;
2048 case GDK_KEY_KP_Left:
2049 return SCK_LEFT;
2050 case GDK_KEY_KP_Right:
2051 return SCK_RIGHT;
2052 case GDK_KEY_KP_Home:
2053 return SCK_HOME;
2054 case GDK_KEY_KP_End:
2055 return SCK_END;
2056 case GDK_KEY_KP_Page_Up:
2057 return SCK_PRIOR;
2058 case GDK_KEY_KP_Page_Down:
2059 return SCK_NEXT;
2060 case GDK_KEY_KP_Delete:
2061 return SCK_DELETE;
2062 case GDK_KEY_KP_Insert:
2063 return SCK_INSERT;
2064 case GDK_KEY_KP_Enter:
2065 return SCK_RETURN;
2067 case GDK_KEY_Down:
2068 return SCK_DOWN;
2069 case GDK_KEY_Up:
2070 return SCK_UP;
2071 case GDK_KEY_Left:
2072 return SCK_LEFT;
2073 case GDK_KEY_Right:
2074 return SCK_RIGHT;
2075 case GDK_KEY_Home:
2076 return SCK_HOME;
2077 case GDK_KEY_End:
2078 return SCK_END;
2079 case GDK_KEY_Page_Up:
2080 return SCK_PRIOR;
2081 case GDK_KEY_Page_Down:
2082 return SCK_NEXT;
2083 case GDK_KEY_Delete:
2084 return SCK_DELETE;
2085 case GDK_KEY_Insert:
2086 return SCK_INSERT;
2087 case GDK_KEY_Escape:
2088 return SCK_ESCAPE;
2089 case GDK_KEY_BackSpace:
2090 return SCK_BACK;
2091 case GDK_KEY_Tab:
2092 return SCK_TAB;
2093 case GDK_KEY_Return:
2094 return SCK_RETURN;
2095 case GDK_KEY_KP_Add:
2096 return SCK_ADD;
2097 case GDK_KEY_KP_Subtract:
2098 return SCK_SUBTRACT;
2099 case GDK_KEY_KP_Divide:
2100 return SCK_DIVIDE;
2101 case GDK_KEY_Super_L:
2102 return SCK_WIN;
2103 case GDK_KEY_Super_R:
2104 return SCK_RWIN;
2105 case GDK_KEY_Menu:
2106 return SCK_MENU;
2108 #else
2110 case GDK_ISO_Left_Tab:
2111 return SCK_TAB;
2112 case GDK_KP_Down:
2113 return SCK_DOWN;
2114 case GDK_KP_Up:
2115 return SCK_UP;
2116 case GDK_KP_Left:
2117 return SCK_LEFT;
2118 case GDK_KP_Right:
2119 return SCK_RIGHT;
2120 case GDK_KP_Home:
2121 return SCK_HOME;
2122 case GDK_KP_End:
2123 return SCK_END;
2124 case GDK_KP_Page_Up:
2125 return SCK_PRIOR;
2126 case GDK_KP_Page_Down:
2127 return SCK_NEXT;
2128 case GDK_KP_Delete:
2129 return SCK_DELETE;
2130 case GDK_KP_Insert:
2131 return SCK_INSERT;
2132 case GDK_KP_Enter:
2133 return SCK_RETURN;
2135 case GDK_Down:
2136 return SCK_DOWN;
2137 case GDK_Up:
2138 return SCK_UP;
2139 case GDK_Left:
2140 return SCK_LEFT;
2141 case GDK_Right:
2142 return SCK_RIGHT;
2143 case GDK_Home:
2144 return SCK_HOME;
2145 case GDK_End:
2146 return SCK_END;
2147 case GDK_Page_Up:
2148 return SCK_PRIOR;
2149 case GDK_Page_Down:
2150 return SCK_NEXT;
2151 case GDK_Delete:
2152 return SCK_DELETE;
2153 case GDK_Insert:
2154 return SCK_INSERT;
2155 case GDK_Escape:
2156 return SCK_ESCAPE;
2157 case GDK_BackSpace:
2158 return SCK_BACK;
2159 case GDK_Tab:
2160 return SCK_TAB;
2161 case GDK_Return:
2162 return SCK_RETURN;
2163 case GDK_KP_Add:
2164 return SCK_ADD;
2165 case GDK_KP_Subtract:
2166 return SCK_SUBTRACT;
2167 case GDK_KP_Divide:
2168 return SCK_DIVIDE;
2169 case GDK_Super_L:
2170 return SCK_WIN;
2171 case GDK_Super_R:
2172 return SCK_RWIN;
2173 case GDK_Menu:
2174 return SCK_MENU;
2175 #endif
2176 default:
2177 return keyIn;
2181 gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
2182 try {
2183 //fprintf(stderr, "SC-key: %d %x [%s]\n",
2184 // event->keyval, event->state, (event->length > 0) ? event->string : "empty");
2185 if (gtk_im_context_filter_keypress(im_context, event)) {
2186 return 1;
2188 if (!event->keyval) {
2189 return true;
2192 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
2193 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
2194 bool alt = (event->state & GDK_MOD1_MASK) != 0;
2195 guint key = event->keyval;
2196 if ((ctrl || alt) && (key < 128))
2197 key = toupper(key);
2198 #if GTK_CHECK_VERSION(3,0,0)
2199 else if (!ctrl && (key >= GDK_KEY_KP_Multiply && key <= GDK_KEY_KP_9))
2200 #else
2201 else if (!ctrl && (key >= GDK_KP_Multiply && key <= GDK_KP_9))
2202 #endif
2203 key &= 0x7F;
2204 // Hack for keys over 256 and below command keys but makes Hungarian work.
2205 // This will have to change for Unicode
2206 else if (key >= 0xFE00)
2207 key = KeyTranslate(key);
2209 bool consumed = false;
2210 #if !(PLAT_GTK_MACOSX)
2211 bool added = KeyDown(key, shift, ctrl, alt, &consumed) != 0;
2212 #else
2213 bool meta = ctrl;
2214 ctrl = (event->state & GDK_META_MASK) != 0;
2215 bool added = KeyDownWithModifiers(key, (shift ? SCI_SHIFT : 0) |
2216 (ctrl ? SCI_CTRL : 0) |
2217 (alt ? SCI_ALT : 0) |
2218 (meta ? SCI_META : 0), &consumed) != 0;
2219 #endif
2220 if (!consumed)
2221 consumed = added;
2222 //fprintf(stderr, "SK-key: %d %x %x\n",event->keyval, event->state, consumed);
2223 if (event->keyval == 0xffffff && event->length > 0) {
2224 ClearSelection();
2225 const int lengthInserted = pdoc->InsertString(CurrentPosition(), event->string, strlen(event->string));
2226 if (lengthInserted > 0) {
2227 MovePositionTo(CurrentPosition() + lengthInserted);
2230 return consumed;
2231 } catch (...) {
2232 errorStatus = SC_STATUS_FAILURE;
2234 return FALSE;
2237 gboolean ScintillaGTK::KeyPress(GtkWidget *widget, GdkEventKey *event) {
2238 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2239 return sciThis->KeyThis(event);
2242 gboolean ScintillaGTK::KeyRelease(GtkWidget *widget, GdkEventKey *event) {
2243 //Platform::DebugPrintf("SC-keyrel: %d %x %3s\n",event->keyval, event->state, event->string);
2244 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2245 if (gtk_im_context_filter_keypress(sciThis->im_context, event)) {
2246 return TRUE;
2248 return FALSE;
2251 #if GTK_CHECK_VERSION(3,0,0)
2253 gboolean ScintillaGTK::DrawPreeditThis(GtkWidget *widget, cairo_t *cr) {
2254 try {
2255 PreEditString pes(im_context);
2256 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2257 pango_layout_set_attributes(layout, pes.attrs);
2259 cairo_move_to(cr, 0, 0);
2260 pango_cairo_show_layout(cr, layout);
2262 g_object_unref(layout);
2263 } catch (...) {
2264 errorStatus = SC_STATUS_FAILURE;
2266 return TRUE;
2269 gboolean ScintillaGTK::DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis) {
2270 return sciThis->DrawPreeditThis(widget, cr);
2273 #else
2275 gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose) {
2276 try {
2277 PreEditString pes(im_context);
2278 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2279 pango_layout_set_attributes(layout, pes.attrs);
2281 cairo_t *context = gdk_cairo_create(reinterpret_cast<GdkDrawable *>(WindowFromWidget(widget)));
2282 cairo_move_to(context, 0, 0);
2283 pango_cairo_show_layout(context, layout);
2284 cairo_destroy(context);
2285 g_object_unref(layout);
2286 } catch (...) {
2287 errorStatus = SC_STATUS_FAILURE;
2289 return TRUE;
2292 gboolean ScintillaGTK::ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2293 return sciThis->ExposePreeditThis(widget, ose);
2296 #endif
2298 bool ScintillaGTK::KoreanIME() {
2299 PreEditString pes(im_context);
2300 if (pes.pscript != PANGO_SCRIPT_COMMON)
2301 lastNonCommonScript = pes.pscript;
2302 return lastNonCommonScript == PANGO_SCRIPT_HANGUL;
2305 void ScintillaGTK::MoveImeCarets(int pos) {
2306 // Move carets relatively by bytes
2307 for (size_t r=0; r<sel.Count(); r++) {
2308 int positionInsert = sel.Range(r).Start().Position();
2309 sel.Range(r).caret.SetPosition(positionInsert + pos);
2310 sel.Range(r).anchor.SetPosition(positionInsert + pos);
2314 void ScintillaGTK::DrawImeIndicator(int indicator, int len) {
2315 // Emulate the visual style of IME characters with indicators.
2316 // Draw an indicator on the character before caret by the character bytes of len
2317 // so it should be called after addCharUTF().
2318 // It does not affect caret positions.
2319 if (indicator < 8 || indicator > INDIC_MAX) {
2320 return;
2322 pdoc->decorations.SetCurrentIndicator(indicator);
2323 for (size_t r=0; r<sel.Count(); r++) {
2324 int positionInsert = sel.Range(r).Start().Position();
2325 pdoc->DecorationFillRange(positionInsert - len, 1, len);
2329 void ScintillaGTK::GetImeUnderlines(PangoAttrList *attrs, bool *normalInput) {
2330 // Whether single underlines attribute is or not
2331 // attr position is counted by the number of UTF-8 bytes
2332 PangoAttrIterator *iterunderline = pango_attr_list_get_iterator(attrs);
2333 if (iterunderline) {
2334 do {
2335 PangoAttribute *attrunderline = pango_attr_iterator_get(iterunderline, PANGO_ATTR_UNDERLINE);
2336 if (attrunderline) {
2337 glong start = attrunderline->start_index;
2338 glong end = attrunderline->end_index;
2339 PangoUnderline uline = (PangoUnderline)((PangoAttrInt *)attrunderline)->value;
2340 for (glong i=start; i < end; ++i) {
2341 switch (uline) {
2342 case PANGO_UNDERLINE_NONE:
2343 normalInput[i] = false;
2344 break;
2345 case PANGO_UNDERLINE_SINGLE: // normal input
2346 normalInput[i] = true;
2347 break;
2348 case PANGO_UNDERLINE_DOUBLE:
2349 case PANGO_UNDERLINE_LOW:
2350 case PANGO_UNDERLINE_ERROR:
2351 break;
2355 } while (pango_attr_iterator_next(iterunderline));
2356 pango_attr_iterator_destroy(iterunderline);
2360 void ScintillaGTK::GetImeBackgrounds(PangoAttrList *attrs, bool *targetInput) {
2361 // Whether background color attribue is or not
2362 // attr position is measured in UTF-8 bytes
2363 PangoAttrIterator *itercolor = pango_attr_list_get_iterator(attrs);
2364 if (itercolor) {
2365 do {
2366 PangoAttribute *backcolor = pango_attr_iterator_get(itercolor, PANGO_ATTR_BACKGROUND);
2367 if (backcolor) {
2368 glong start = backcolor->start_index;
2369 glong end = backcolor->end_index;
2370 for (glong i=start; i < end; ++i) {
2371 targetInput[i] = true; // target converted
2374 } while (pango_attr_iterator_next(itercolor));
2375 pango_attr_iterator_destroy(itercolor);
2379 void ScintillaGTK::SetCandidateWindowPos() {
2380 // Composition box accompanies candidate box.
2381 Point pt = PointMainCaret();
2382 GdkRectangle imeBox = {0}; // No need to set width
2383 imeBox.x = pt.x; // Only need positiion
2384 imeBox.y = pt.y + vs.lineHeight; // underneath the first charater
2385 gtk_im_context_set_cursor_location(im_context, &imeBox);
2388 void ScintillaGTK::CommitThis(char *commitStr) {
2389 try {
2390 //~ fprintf(stderr, "Commit '%s'\n", commitStr);
2391 view.imeCaretBlockOverride = false;
2393 if (pdoc->TentativeActive()) {
2394 pdoc->TentativeUndo();
2397 const char *charSetSource = CharacterSetID();
2399 glong uniStrLen = 0;
2400 gunichar *uniStr = g_utf8_to_ucs4_fast(commitStr, strlen(commitStr), &uniStrLen);
2401 for (glong i = 0; i < uniStrLen; i++) {
2403 gunichar uniChar[1] = {0};
2404 uniChar[0] = uniStr[i];
2406 glong oneCharLen = 0;
2407 gchar *oneChar = g_ucs4_to_utf8(uniChar, 1, NULL, &oneCharLen, NULL);
2409 if (IsUnicodeMode()) {
2410 // Do nothing ;
2411 } else {
2412 std::string oneCharSTD = ConvertText(oneChar, oneCharLen, charSetSource, "UTF-8", true);
2413 oneCharLen = oneCharSTD.copy(oneChar,oneCharSTD.length(), 0);
2414 oneChar[oneCharLen] = '\0';
2417 AddCharUTF(oneChar, oneCharLen);
2418 g_free(oneChar);
2420 g_free(uniStr);
2421 ShowCaretAtCurrentPosition();
2422 } catch (...) {
2423 errorStatus = SC_STATUS_FAILURE;
2427 void ScintillaGTK::Commit(GtkIMContext *, char *str, ScintillaGTK *sciThis) {
2428 sciThis->CommitThis(str);
2431 void ScintillaGTK::PreeditChangedInlineThis() {
2432 // Copy & paste by johnsonj with a lot of helps of Neil
2433 // Great thanks for my foreruners, jiniya and BLUEnLIVE
2434 try {
2435 view.imeCaretBlockOverride = false; // If backspace.
2437 if (pdoc->TentativeActive()) {
2438 pdoc->TentativeUndo();
2439 } else {
2440 // No tentative undo means start of this composition so
2441 // fill in any virtual spaces.
2442 ClearBeforeTentativeStart();
2445 PreEditString preeditStr(im_context);
2446 const char *charSetSource = CharacterSetID();
2448 if (!preeditStr.validUTF8 || (charSetSource == NULL)) {
2449 ShowCaretAtCurrentPosition();
2450 return;
2453 if (preeditStr.uniStrLen == 0 || preeditStr.uniStrLen > maxLenInputIME) {
2454 //fprintf(stderr, "Do not allow over 200 chars: %i\n", preeditStr.uniStrLen);
2455 ShowCaretAtCurrentPosition();
2456 return;
2459 pdoc->TentativeStart(); // TentativeActive() from now on
2461 // Get preedit string attribues
2462 bool normalInput[maxLenInputIME*3+1] = {false};
2463 bool targetInput[maxLenInputIME*3+1] = {false};
2464 GetImeUnderlines(preeditStr.attrs, normalInput);
2465 GetImeBackgrounds(preeditStr.attrs, targetInput);
2467 // Display preedit characters, one by one
2468 glong imeCharPos[maxLenInputIME+1] = { 0 };
2469 glong attrPos = -1; // Start at -1 to designate the last byte of one character.
2470 glong charWidth = 0;
2472 bool tmpRecordingMacro = recordingMacro;
2473 recordingMacro = false;
2474 for (glong i = 0; i < preeditStr.uniStrLen; i++) {
2476 gunichar uniChar[1] = {0};
2477 uniChar[0] = preeditStr.uniStr[i];
2479 glong oneCharLen = 0;
2480 gchar *oneChar = g_ucs4_to_utf8(uniChar, 1, NULL, &oneCharLen, NULL);
2482 // Record attribute positions in UTF-8 bytes
2483 attrPos += oneCharLen;
2485 if (IsUnicodeMode()) {
2486 // Do nothing
2487 } else {
2488 std::string oneCharSTD = ConvertText(oneChar, oneCharLen, charSetSource, "UTF-8", true);
2489 oneCharLen = oneCharSTD.copy(oneChar,oneCharSTD.length(), 0);
2490 oneChar[oneCharLen] = '\0';
2493 // Record character positions in UTF-8 or DBCS bytes
2495 charWidth += oneCharLen;
2496 imeCharPos[i+1] = charWidth;
2498 // Display one character
2499 AddCharUTF(oneChar, oneCharLen);
2501 // Draw an indicator on the character,
2502 // Overlapping allowed
2503 if (normalInput[attrPos]) {
2504 DrawImeIndicator(SC_INDICATOR_INPUT, oneCharLen);
2506 if (targetInput[attrPos]) {
2507 DrawImeIndicator(SC_INDICATOR_TARGET, oneCharLen);
2509 g_free(oneChar);
2511 recordingMacro = tmpRecordingMacro;
2513 // Move caret to ime cursor position.
2514 if (KoreanIME()) {
2515 view.imeCaretBlockOverride = true;
2516 MoveImeCarets( - (imeCharPos[preeditStr.uniStrLen]));
2518 } else {
2519 MoveImeCarets( - (imeCharPos[preeditStr.uniStrLen]) + imeCharPos[preeditStr.cursor_pos]);
2522 EnsureCaretVisible();
2523 SetCandidateWindowPos();
2524 ShowCaretAtCurrentPosition();
2525 } catch (...) {
2526 errorStatus = SC_STATUS_FAILURE;
2530 void ScintillaGTK::PreeditChangedWindowedThis() {
2531 try {
2532 PreEditString pes(im_context);
2533 if (strlen(pes.str) > 0) {
2534 PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
2535 pango_layout_set_attributes(layout, pes.attrs);
2537 gint w, h;
2538 pango_layout_get_pixel_size(layout, &w, &h);
2539 g_object_unref(layout);
2541 gint x, y;
2542 gdk_window_get_origin(PWindow(wText), &x, &y);
2544 Point pt = PointMainCaret();
2545 if (pt.x < 0)
2546 pt.x = 0;
2547 if (pt.y < 0)
2548 pt.y = 0;
2550 gtk_window_move(GTK_WINDOW(PWidget(wPreedit)), x + pt.x, y + pt.y);
2551 gtk_window_resize(GTK_WINDOW(PWidget(wPreedit)), w, h);
2552 gtk_widget_show(PWidget(wPreedit));
2553 gtk_widget_queue_draw_area(PWidget(wPreeditDraw), 0, 0, w, h);
2554 } else {
2555 gtk_widget_hide(PWidget(wPreedit));
2557 } catch (...) {
2558 errorStatus = SC_STATUS_FAILURE;
2562 void ScintillaGTK::PreeditChanged(GtkIMContext *, ScintillaGTK *sciThis) {
2563 if ((sciThis->imeInteraction == imeInline) || (sciThis->KoreanIME())) {
2564 sciThis->PreeditChangedInlineThis();
2565 } else {
2566 sciThis->PreeditChangedWindowedThis();
2570 void ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) {
2571 RealizeText(widget, NULL);
2574 void ScintillaGTK::RealizeText(GtkWidget *widget, void*) {
2575 // Set NULL background to avoid automatic clearing so Scintilla responsible for all drawing
2576 if (WindowFromWidget(widget)) {
2577 #if GTK_CHECK_VERSION(3,0,0)
2578 gdk_window_set_background_pattern(WindowFromWidget(widget), NULL);
2579 #else
2580 gdk_window_set_back_pixmap(WindowFromWidget(widget), NULL, FALSE);
2581 #endif
2585 static GObjectClass *scintilla_class_parent_class;
2587 void ScintillaGTK::Destroy(GObject *object) {
2588 try {
2589 ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(object);
2591 // This avoids a double destruction
2592 if (!scio->pscin)
2593 return;
2594 ScintillaGTK *sciThis = reinterpret_cast<ScintillaGTK *>(scio->pscin);
2595 //Platform::DebugPrintf("Destroying %x %x\n", sciThis, object);
2596 sciThis->Finalise();
2598 gtk_widget_unparent(PWidget(sciThis->scrollbarv));
2599 gtk_widget_unparent(PWidget(sciThis->scrollbarh));
2601 delete sciThis;
2602 scio->pscin = 0;
2603 scintilla_class_parent_class->finalize(object);
2604 } catch (...) {
2605 // Its dead so nowhere to save the status
2609 #if GTK_CHECK_VERSION(3,0,0)
2611 gboolean ScintillaGTK::DrawTextThis(cairo_t *cr) {
2612 try {
2613 paintState = painting;
2614 repaintFullWindow = false;
2616 rcPaint = GetClientRectangle();
2618 PLATFORM_ASSERT(rgnUpdate == NULL);
2619 rgnUpdate = cairo_copy_clip_rectangle_list(cr);
2620 if (rgnUpdate && rgnUpdate->status != CAIRO_STATUS_SUCCESS) {
2621 // If not successful then ignore
2622 fprintf(stderr, "DrawTextThis failed to copy update region %d [%d]\n", rgnUpdate->status, rgnUpdate->num_rectangles);
2623 cairo_rectangle_list_destroy(rgnUpdate);
2624 rgnUpdate = 0;
2627 double x1, y1, x2, y2;
2628 cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
2629 rcPaint.left = x1;
2630 rcPaint.top = y1;
2631 rcPaint.right = x2;
2632 rcPaint.bottom = y2;
2633 PRectangle rcClient = GetClientRectangle();
2634 paintingAllText = rcPaint.Contains(rcClient);
2635 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2636 if (surfaceWindow) {
2637 surfaceWindow->Init(cr, PWidget(wText));
2638 Paint(surfaceWindow, rcPaint);
2639 surfaceWindow->Release();
2640 delete surfaceWindow;
2642 if ((paintState == paintAbandoned) || repaintFullWindow) {
2643 // Painting area was insufficient to cover new styling or brace highlight positions
2644 FullPaint();
2646 paintState = notPainting;
2647 repaintFullWindow = false;
2649 if (rgnUpdate) {
2650 cairo_rectangle_list_destroy(rgnUpdate);
2652 rgnUpdate = 0;
2653 paintState = notPainting;
2654 } catch (...) {
2655 errorStatus = SC_STATUS_FAILURE;
2658 return FALSE;
2661 gboolean ScintillaGTK::DrawText(GtkWidget *, cairo_t *cr, ScintillaGTK *sciThis) {
2662 return sciThis->DrawTextThis(cr);
2665 gboolean ScintillaGTK::DrawThis(cairo_t *cr) {
2666 try {
2667 #ifdef GTK_STYLE_CLASS_SCROLLBARS_JUNCTION /* GTK >= 3.4 */
2668 // if both scrollbars are visible, paint the little square on the bottom right corner
2669 if (verticalScrollBarVisible && horizontalScrollBarVisible && !Wrapping()) {
2670 GtkStyleContext *styleContext = gtk_widget_get_style_context(PWidget(wMain));
2671 PRectangle rc = GetClientRectangle();
2673 gtk_style_context_save(styleContext);
2674 gtk_style_context_add_class(styleContext, GTK_STYLE_CLASS_SCROLLBARS_JUNCTION);
2676 gtk_render_background(styleContext, cr, rc.right, rc.bottom,
2677 verticalScrollBarWidth, horizontalScrollBarHeight);
2678 gtk_render_frame(styleContext, cr, rc.right, rc.bottom,
2679 verticalScrollBarWidth, horizontalScrollBarHeight);
2681 gtk_style_context_restore(styleContext);
2683 #endif
2685 gtk_container_propagate_draw(
2686 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), cr);
2687 gtk_container_propagate_draw(
2688 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), cr);
2689 // Starting from the following version, the expose event are not propagated
2690 // for double buffered non native windows, so we need to call it ourselves
2691 // or keep the default handler
2692 #if GTK_CHECK_VERSION(3,0,0)
2693 // we want to forward on any >= 3.9.2 runtime
2694 if (gtk_check_version(3,9,2) == NULL) {
2695 gtk_container_propagate_draw(
2696 GTK_CONTAINER(PWidget(wMain)), PWidget(wText), cr);
2698 #endif
2699 } catch (...) {
2700 errorStatus = SC_STATUS_FAILURE;
2702 return FALSE;
2705 gboolean ScintillaGTK::DrawMain(GtkWidget *widget, cairo_t *cr) {
2706 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2707 return sciThis->DrawThis(cr);
2710 #else
2712 gboolean ScintillaGTK::ExposeTextThis(GtkWidget * /*widget*/, GdkEventExpose *ose) {
2713 try {
2714 paintState = painting;
2716 rcPaint.left = ose->area.x;
2717 rcPaint.top = ose->area.y;
2718 rcPaint.right = ose->area.x + ose->area.width;
2719 rcPaint.bottom = ose->area.y + ose->area.height;
2721 PLATFORM_ASSERT(rgnUpdate == NULL);
2722 rgnUpdate = gdk_region_copy(ose->region);
2723 PRectangle rcClient = GetClientRectangle();
2724 paintingAllText = rcPaint.Contains(rcClient);
2725 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
2726 if (surfaceWindow) {
2727 cairo_t *cr = gdk_cairo_create(PWindow(wText));
2728 surfaceWindow->Init(cr, PWidget(wText));
2729 Paint(surfaceWindow, rcPaint);
2730 surfaceWindow->Release();
2731 delete surfaceWindow;
2732 cairo_destroy(cr);
2734 if (paintState == paintAbandoned) {
2735 // Painting area was insufficient to cover new styling or brace highlight positions
2736 FullPaint();
2738 paintState = notPainting;
2740 if (rgnUpdate) {
2741 gdk_region_destroy(rgnUpdate);
2743 rgnUpdate = 0;
2744 } catch (...) {
2745 errorStatus = SC_STATUS_FAILURE;
2748 return FALSE;
2751 gboolean ScintillaGTK::ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) {
2752 return sciThis->ExposeTextThis(widget, ose);
2755 gboolean ScintillaGTK::ExposeMain(GtkWidget *widget, GdkEventExpose *ose) {
2756 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2757 //Platform::DebugPrintf("Expose Main %0d,%0d %0d,%0d\n",
2758 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2759 return sciThis->Expose(widget, ose);
2762 gboolean ScintillaGTK::Expose(GtkWidget *, GdkEventExpose *ose) {
2763 try {
2764 //fprintf(stderr, "Expose %0d,%0d %0d,%0d\n",
2765 //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
2767 // The text is painted in ExposeText
2768 gtk_container_propagate_expose(
2769 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), ose);
2770 gtk_container_propagate_expose(
2771 GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), ose);
2773 } catch (...) {
2774 errorStatus = SC_STATUS_FAILURE;
2776 return FALSE;
2779 #endif
2781 void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2782 try {
2783 sciThis->ScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)), false);
2784 } catch (...) {
2785 sciThis->errorStatus = SC_STATUS_FAILURE;
2789 void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
2790 try {
2791 sciThis->HorizontalScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)));
2792 } catch (...) {
2793 sciThis->errorStatus = SC_STATUS_FAILURE;
2797 void ScintillaGTK::SelectionReceived(GtkWidget *widget,
2798 GtkSelectionData *selection_data, guint) {
2799 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2800 //Platform::DebugPrintf("Selection received\n");
2801 sciThis->ReceivedSelection(selection_data);
2804 void ScintillaGTK::SelectionGet(GtkWidget *widget,
2805 GtkSelectionData *selection_data, guint info, guint) {
2806 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2807 try {
2808 //Platform::DebugPrintf("Selection get\n");
2809 if (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY) {
2810 if (sciThis->primary.Empty()) {
2811 sciThis->CopySelectionRange(&sciThis->primary);
2813 sciThis->GetSelection(selection_data, info, &sciThis->primary);
2815 } catch (...) {
2816 sciThis->errorStatus = SC_STATUS_FAILURE;
2820 gint ScintillaGTK::SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event) {
2821 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2822 //Platform::DebugPrintf("Selection clear\n");
2823 sciThis->UnclaimSelection(selection_event);
2824 if (GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event) {
2825 return GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event(widget, selection_event);
2827 return TRUE;
2830 gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context,
2831 gint x, gint y, guint dragtime) {
2832 try {
2833 Point npt(x, y);
2834 SetDragPosition(SPositionFromLocation(npt, false, false, UserVirtualSpace()));
2835 #if GTK_CHECK_VERSION(2,22,0)
2836 GdkDragAction preferredAction = gdk_drag_context_get_suggested_action(context);
2837 GdkDragAction actions = gdk_drag_context_get_actions(context);
2838 #else
2839 GdkDragAction preferredAction = context->suggested_action;
2840 GdkDragAction actions = context->actions;
2841 #endif
2842 SelectionPosition pos = SPositionFromLocation(npt);
2843 if ((inDragDrop == ddDragging) && (PositionInSelection(pos.Position()))) {
2844 // Avoid dragging selection onto itself as that produces a move
2845 // with no real effect but which creates undo actions.
2846 preferredAction = static_cast<GdkDragAction>(0);
2847 } else if (actions == static_cast<GdkDragAction>
2848 (GDK_ACTION_COPY | GDK_ACTION_MOVE)) {
2849 preferredAction = GDK_ACTION_MOVE;
2851 gdk_drag_status(context, preferredAction, dragtime);
2852 } catch (...) {
2853 errorStatus = SC_STATUS_FAILURE;
2855 return FALSE;
2858 gboolean ScintillaGTK::DragMotion(GtkWidget *widget, GdkDragContext *context,
2859 gint x, gint y, guint dragtime) {
2860 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2861 return sciThis->DragMotionThis(context, x, y, dragtime);
2864 void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, guint) {
2865 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2866 try {
2867 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2868 //Platform::DebugPrintf("DragLeave %x\n", sciThis);
2869 } catch (...) {
2870 sciThis->errorStatus = SC_STATUS_FAILURE;
2874 void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) {
2875 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2876 try {
2877 // If drag did not result in drop here or elsewhere
2878 if (!sciThis->dragWasDropped)
2879 sciThis->SetEmptySelection(sciThis->posDrag);
2880 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2881 //Platform::DebugPrintf("DragEnd %x %d\n", sciThis, sciThis->dragWasDropped);
2882 sciThis->inDragDrop = ddNone;
2883 } catch (...) {
2884 sciThis->errorStatus = SC_STATUS_FAILURE;
2888 gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/,
2889 gint, gint, guint) {
2890 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2891 try {
2892 //Platform::DebugPrintf("Drop %x\n", sciThis);
2893 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2894 } catch (...) {
2895 sciThis->errorStatus = SC_STATUS_FAILURE;
2897 return FALSE;
2900 void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*context*/,
2901 gint, gint, GtkSelectionData *selection_data, guint /*info*/, guint) {
2902 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2903 try {
2904 sciThis->ReceivedDrop(selection_data);
2905 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2906 } catch (...) {
2907 sciThis->errorStatus = SC_STATUS_FAILURE;
2911 void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context,
2912 GtkSelectionData *selection_data, guint info, guint) {
2913 ScintillaGTK *sciThis = ScintillaFromWidget(widget);
2914 try {
2915 sciThis->dragWasDropped = true;
2916 if (!sciThis->sel.Empty()) {
2917 sciThis->GetSelection(selection_data, info, &sciThis->drag);
2919 #if GTK_CHECK_VERSION(2,22,0)
2920 GdkDragAction action = gdk_drag_context_get_selected_action(context);
2921 #else
2922 GdkDragAction action = context->action;
2923 #endif
2924 if (action == GDK_ACTION_MOVE) {
2925 for (size_t r=0; r<sciThis->sel.Count(); r++) {
2926 if (sciThis->posDrop >= sciThis->sel.Range(r).Start()) {
2927 if (sciThis->posDrop > sciThis->sel.Range(r).End()) {
2928 sciThis->posDrop.Add(-sciThis->sel.Range(r).Length());
2929 } else {
2930 sciThis->posDrop.Add(-SelectionRange(sciThis->posDrop, sciThis->sel.Range(r).Start()).Length());
2934 sciThis->ClearSelection();
2936 sciThis->SetDragPosition(SelectionPosition(invalidPosition));
2937 } catch (...) {
2938 sciThis->errorStatus = SC_STATUS_FAILURE;
2942 int ScintillaGTK::TimeOut(TimeThunk *tt) {
2943 tt->scintilla->TickFor(tt->reason);
2944 return 1;
2947 gboolean ScintillaGTK::IdleCallback(ScintillaGTK *sciThis) {
2948 // Idler will be automatically stopped, if there is nothing
2949 // to do while idle.
2950 #ifndef GDK_VERSION_3_6
2951 gdk_threads_enter();
2952 #endif
2953 bool ret = sciThis->Idle();
2954 if (ret == false) {
2955 // FIXME: This will remove the idler from GTK, we don't want to
2956 // remove it as it is removed automatically when this function
2957 // returns false (although, it should be harmless).
2958 sciThis->SetIdle(false);
2960 #ifndef GDK_VERSION_3_6
2961 gdk_threads_leave();
2962 #endif
2963 return ret;
2966 gboolean ScintillaGTK::StyleIdle(ScintillaGTK *sciThis) {
2967 #ifndef GDK_VERSION_3_6
2968 gdk_threads_enter();
2969 #endif
2970 sciThis->IdleWork();
2971 #ifndef GDK_VERSION_3_6
2972 gdk_threads_leave();
2973 #endif
2974 // Idler will be automatically stopped
2975 return FALSE;
2978 void ScintillaGTK::QueueIdleWork(WorkNeeded::workItems items, int upTo) {
2979 Editor::QueueIdleWork(items, upTo);
2980 if (!workNeeded.active) {
2981 // Only allow one style needed to be queued
2982 workNeeded.active = true;
2983 g_idle_add_full(G_PRIORITY_HIGH_IDLE,
2984 reinterpret_cast<GSourceFunc>(StyleIdle), this, NULL);
2988 void ScintillaGTK::PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis) {
2989 guint action = (sptr_t)(g_object_get_data(G_OBJECT(menuItem), "CmdNum"));
2990 if (action) {
2991 sciThis->Command(action);
2995 gboolean ScintillaGTK::PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis) {
2996 try {
2997 if (event->window != WindowFromWidget(widget))
2998 return FALSE;
2999 if (event->type != GDK_BUTTON_PRESS)
3000 return FALSE;
3001 Point pt;
3002 pt.x = int(event->x);
3003 pt.y = int(event->y);
3004 sciThis->ct.MouseClick(pt);
3005 sciThis->CallTipClick();
3006 } catch (...) {
3008 return TRUE;
3011 #if GTK_CHECK_VERSION(3,0,0)
3013 gboolean ScintillaGTK::DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip) {
3014 try {
3015 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
3016 if (surfaceWindow) {
3017 surfaceWindow->Init(cr, widget);
3018 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
3019 surfaceWindow->SetDBCSMode(ctip->codePage);
3020 ctip->PaintCT(surfaceWindow);
3021 surfaceWindow->Release();
3022 delete surfaceWindow;
3024 } catch (...) {
3025 // No pointer back to Scintilla to save status
3027 return TRUE;
3030 #else
3032 gboolean ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, CallTip *ctip) {
3033 try {
3034 Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
3035 if (surfaceWindow) {
3036 cairo_t *cr = gdk_cairo_create(WindowFromWidget(widget));
3037 surfaceWindow->Init(cr, widget);
3038 surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
3039 surfaceWindow->SetDBCSMode(ctip->codePage);
3040 ctip->PaintCT(surfaceWindow);
3041 surfaceWindow->Release();
3042 delete surfaceWindow;
3043 cairo_destroy(cr);
3045 } catch (...) {
3046 // No pointer back to Scintilla to save status
3048 return TRUE;
3051 #endif
3053 sptr_t ScintillaGTK::DirectFunction(
3054 sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3055 return reinterpret_cast<ScintillaGTK *>(ptr)->WndProc(iMessage, wParam, lParam);
3058 GEANY_API_SYMBOL
3059 sptr_t scintilla_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
3060 ScintillaGTK *psci = reinterpret_cast<ScintillaGTK *>(sci->pscin);
3061 return psci->WndProc(iMessage, wParam, lParam);
3064 static void scintilla_class_init(ScintillaClass *klass);
3065 static void scintilla_init(ScintillaObject *sci);
3067 extern void Platform_Initialise();
3068 extern void Platform_Finalise();
3070 GEANY_API_SYMBOL
3071 GType scintilla_get_type() {
3072 static GType scintilla_type = 0;
3073 try {
3075 if (!scintilla_type) {
3076 scintilla_type = g_type_from_name("Scintilla");
3077 if (!scintilla_type) {
3078 static GTypeInfo scintilla_info = {
3079 (guint16) sizeof (ScintillaClass),
3080 NULL, //(GBaseInitFunc)
3081 NULL, //(GBaseFinalizeFunc)
3082 (GClassInitFunc) scintilla_class_init,
3083 NULL, //(GClassFinalizeFunc)
3084 NULL, //gconstpointer data
3085 (guint16) sizeof (ScintillaObject),
3086 0, //n_preallocs
3087 (GInstanceInitFunc) scintilla_init,
3088 NULL //(GTypeValueTable*)
3091 scintilla_type = g_type_register_static(
3092 GTK_TYPE_CONTAINER, "Scintilla", &scintilla_info, (GTypeFlags) 0);
3096 } catch (...) {
3098 return scintilla_type;
3101 void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class) {
3102 Platform_Initialise();
3103 #ifdef SCI_LEXER
3104 Scintilla_LinkLexers();
3105 #endif
3106 atomClipboard = gdk_atom_intern("CLIPBOARD", FALSE);
3107 atomUTF8 = gdk_atom_intern("UTF8_STRING", FALSE);
3108 atomString = GDK_SELECTION_TYPE_STRING;
3109 atomUriList = gdk_atom_intern("text/uri-list", FALSE);
3110 atomDROPFILES_DND = gdk_atom_intern("DROPFILES_DND", FALSE);
3112 // Define default signal handlers for the class: Could move more
3113 // of the signal handlers here (those that currently attached to wDraw
3114 // in Initialise() may require coordinate translation?)
3116 object_class->finalize = Destroy;
3117 #if GTK_CHECK_VERSION(3,0,0)
3118 widget_class->get_preferred_width = GetPreferredWidth;
3119 widget_class->get_preferred_height = GetPreferredHeight;
3120 #else
3121 widget_class->size_request = SizeRequest;
3122 #endif
3123 widget_class->size_allocate = SizeAllocate;
3124 #if GTK_CHECK_VERSION(3,0,0)
3125 widget_class->draw = DrawMain;
3126 #else
3127 widget_class->expose_event = ExposeMain;
3128 #endif
3129 widget_class->motion_notify_event = Motion;
3130 widget_class->button_press_event = Press;
3131 widget_class->button_release_event = MouseRelease;
3132 widget_class->scroll_event = ScrollEvent;
3133 widget_class->key_press_event = KeyPress;
3134 widget_class->key_release_event = KeyRelease;
3135 widget_class->focus_in_event = FocusIn;
3136 widget_class->focus_out_event = FocusOut;
3137 widget_class->selection_received = SelectionReceived;
3138 widget_class->selection_get = SelectionGet;
3139 widget_class->selection_clear_event = SelectionClear;
3141 widget_class->drag_data_received = DragDataReceived;
3142 widget_class->drag_motion = DragMotion;
3143 widget_class->drag_leave = DragLeave;
3144 widget_class->drag_end = DragEnd;
3145 widget_class->drag_drop = Drop;
3146 widget_class->drag_data_get = DragDataGet;
3148 widget_class->realize = Realize;
3149 widget_class->unrealize = UnRealize;
3150 widget_class->map = Map;
3151 widget_class->unmap = UnMap;
3153 container_class->forall = MainForAll;
3156 #define SIG_MARSHAL scintilla_marshal_NONE__INT_POINTER
3157 #define MARSHAL_ARGUMENTS G_TYPE_INT, G_TYPE_POINTER
3159 static void scintilla_class_init(ScintillaClass *klass) {
3160 try {
3161 OBJECT_CLASS *object_class = (OBJECT_CLASS*) klass;
3162 GtkWidgetClass *widget_class = (GtkWidgetClass*) klass;
3163 GtkContainerClass *container_class = (GtkContainerClass*) klass;
3165 GSignalFlags sigflags = GSignalFlags(G_SIGNAL_ACTION | G_SIGNAL_RUN_LAST);
3166 scintilla_signals[COMMAND_SIGNAL] = g_signal_new(
3167 "command",
3168 G_TYPE_FROM_CLASS(object_class),
3169 sigflags,
3170 G_STRUCT_OFFSET(ScintillaClass, command),
3171 NULL, //(GSignalAccumulator)
3172 NULL, //(gpointer)
3173 SIG_MARSHAL,
3174 G_TYPE_NONE,
3175 2, MARSHAL_ARGUMENTS);
3177 scintilla_signals[NOTIFY_SIGNAL] = g_signal_new(
3178 SCINTILLA_NOTIFY,
3179 G_TYPE_FROM_CLASS(object_class),
3180 sigflags,
3181 G_STRUCT_OFFSET(ScintillaClass, notify),
3182 NULL,
3183 NULL,
3184 SIG_MARSHAL,
3185 G_TYPE_NONE,
3186 2, MARSHAL_ARGUMENTS);
3188 klass->command = NULL;
3189 klass->notify = NULL;
3190 scintilla_class_parent_class = G_OBJECT_CLASS(g_type_class_peek_parent(klass));
3191 ScintillaGTK::ClassInit(object_class, widget_class, container_class);
3192 } catch (...) {
3196 static void scintilla_init(ScintillaObject *sci) {
3197 try {
3198 gtk_widget_set_can_focus(GTK_WIDGET(sci), TRUE);
3199 sci->pscin = new ScintillaGTK(sci);
3200 } catch (...) {
3204 GEANY_API_SYMBOL
3205 GtkWidget* scintilla_new() {
3206 GtkWidget *widget = GTK_WIDGET(g_object_new(scintilla_get_type(), NULL));
3207 gtk_widget_set_direction(widget, GTK_TEXT_DIR_LTR);
3209 return widget;
3212 void scintilla_set_id(ScintillaObject *sci, uptr_t id) {
3213 ScintillaGTK *psci = reinterpret_cast<ScintillaGTK *>(sci->pscin);
3214 psci->ctrlID = id;
3217 void scintilla_release_resources(void) {
3218 try {
3219 Platform_Finalise();
3220 } catch (...) {