summaryrefslogtreecommitdiffstats
path: root/widget/gtk/NativeKeyBindings.cpp
blob: 55a3508e26f8c5f7470006c315d1f90135c0569f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/ArrayUtils.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/TextEvents.h"

#include "NativeKeyBindings.h"
#include "nsString.h"
#include "nsMemory.h"
#include "nsGtkKeyUtils.h"

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <gdk/gdk.h>

namespace mozilla {
namespace widget {

static nsIWidget::DoCommandCallback gCurrentCallback;
static void *gCurrentCallbackData;
static bool gHandled;

// Common GtkEntry and GtkTextView signals
static void
copy_clipboard_cb(GtkWidget *w, gpointer user_data)
{
  gCurrentCallback(CommandCopy, gCurrentCallbackData);
  g_signal_stop_emission_by_name(w, "copy_clipboard");
  gHandled = true;
}

static void
cut_clipboard_cb(GtkWidget *w, gpointer user_data)
{
  gCurrentCallback(CommandCut, gCurrentCallbackData);
  g_signal_stop_emission_by_name(w, "cut_clipboard");
  gHandled = true;
}

// GTK distinguishes between display lines (wrapped, as they appear on the
// screen) and paragraphs, which are runs of text terminated by a newline.
// We don't have this distinction, so we always use editor's notion of
// lines, which are newline-terminated.

static const Command sDeleteCommands[][2] = {
  // backward, forward
  { CommandDeleteCharBackward, CommandDeleteCharForward },    // CHARS
  { CommandDeleteWordBackward, CommandDeleteWordForward },    // WORD_ENDS
  { CommandDeleteWordBackward, CommandDeleteWordForward },    // WORDS
  { CommandDeleteToBeginningOfLine, CommandDeleteToEndOfLine }, // LINES
  { CommandDeleteToBeginningOfLine, CommandDeleteToEndOfLine }, // LINE_ENDS
  { CommandDeleteToBeginningOfLine, CommandDeleteToEndOfLine }, // PARAGRAPH_ENDS
  { CommandDeleteToBeginningOfLine, CommandDeleteToEndOfLine }, // PARAGRAPHS
  // This deletes from the end of the previous word to the beginning of the
  // next word, but only if the caret is not in a word.
  // XXX need to implement in editor
  { CommandDoNothing, CommandDoNothing } // WHITESPACE
};

static void
delete_from_cursor_cb(GtkWidget *w, GtkDeleteType del_type,
                      gint count, gpointer user_data)
{
  g_signal_stop_emission_by_name(w, "delete_from_cursor");
  bool forward = count > 0;

#if (MOZ_WIDGET_GTK == 3)
  // Ignore GTK's Ctrl-K keybinding introduced in GTK 3.14 and removed in
  // 3.18 if the user has custom bindings set. See bug 1176929.
  if (del_type == GTK_DELETE_PARAGRAPH_ENDS && forward && GTK_IS_ENTRY(w) &&
      !gtk_check_version(3, 14, 1) && gtk_check_version(3, 17, 9)) {
    GtkStyleContext* context = gtk_widget_get_style_context(w);
    GtkStateFlags flags = gtk_widget_get_state_flags(w);

    GPtrArray* array;
    gtk_style_context_get(context, flags, "gtk-key-bindings", &array, nullptr);
    if (!array)
      return;
    g_ptr_array_unref(array);
  }
#endif

  gHandled = true;
  if (uint32_t(del_type) >= ArrayLength(sDeleteCommands)) {
    // unsupported deletion type
    return;
  }

  if (del_type == GTK_DELETE_WORDS) {
    // This works like word_ends, except we first move the caret to the
    // beginning/end of the current word.
    if (forward) {
      gCurrentCallback(CommandWordNext, gCurrentCallbackData);
      gCurrentCallback(CommandWordPrevious, gCurrentCallbackData);
    } else {
      gCurrentCallback(CommandWordPrevious, gCurrentCallbackData);
      gCurrentCallback(CommandWordNext, gCurrentCallbackData);
    }
  } else if (del_type == GTK_DELETE_DISPLAY_LINES ||
             del_type == GTK_DELETE_PARAGRAPHS) {

    // This works like display_line_ends, except we first move the caret to the
    // beginning/end of the current line.
    if (forward) {
      gCurrentCallback(CommandBeginLine, gCurrentCallbackData);
    } else {
      gCurrentCallback(CommandEndLine, gCurrentCallbackData);
    }
  }

  Command command = sDeleteCommands[del_type][forward];
  if (!command) {
    return; // unsupported command
  }

  unsigned int absCount = Abs(count);
  for (unsigned int i = 0; i < absCount; ++i) {
    gCurrentCallback(command, gCurrentCallbackData);
  }
}

static const Command sMoveCommands[][2][2] = {
  // non-extend { backward, forward }, extend { backward, forward }
  // GTK differentiates between logical position, which is prev/next,
  // and visual position, which is always left/right.
  // We should fix this to work the same way for RTL text input.
  { // LOGICAL_POSITIONS
    { CommandCharPrevious, CommandCharNext },
    { CommandSelectCharPrevious, CommandSelectCharNext }
  },
  { // VISUAL_POSITIONS
    { CommandCharPrevious, CommandCharNext },
    { CommandSelectCharPrevious, CommandSelectCharNext }
  },
  { // WORDS
    { CommandWordPrevious, CommandWordNext },
    { CommandSelectWordPrevious, CommandSelectWordNext }
  },
  { // DISPLAY_LINES
    { CommandLinePrevious, CommandLineNext },
    { CommandSelectLinePrevious, CommandSelectLineNext }
  },
  { // DISPLAY_LINE_ENDS
    { CommandBeginLine, CommandEndLine },
    { CommandSelectBeginLine, CommandSelectEndLine }
  },
  { // PARAGRAPHS
    { CommandLinePrevious, CommandLineNext },
    { CommandSelectLinePrevious, CommandSelectLineNext }
  },
  { // PARAGRAPH_ENDS
    { CommandBeginLine, CommandEndLine },
    { CommandSelectBeginLine, CommandSelectEndLine }
  },
  { // PAGES
    { CommandMovePageUp, CommandMovePageDown },
    { CommandSelectPageUp, CommandSelectPageDown }
  },
  { // BUFFER_ENDS
    { CommandMoveTop, CommandMoveBottom },
    { CommandSelectTop, CommandSelectBottom }
  },
  { // HORIZONTAL_PAGES (unsupported)
    { CommandDoNothing, CommandDoNothing },
    { CommandDoNothing, CommandDoNothing }
  }
};

static void
move_cursor_cb(GtkWidget *w, GtkMovementStep step, gint count,
               gboolean extend_selection, gpointer user_data)
{
  g_signal_stop_emission_by_name(w, "move_cursor");
  gHandled = true;
  bool forward = count > 0;
  if (uint32_t(step) >= ArrayLength(sMoveCommands)) {
    // unsupported movement type
    return;
  }

  Command command = sMoveCommands[step][extend_selection][forward];
  if (!command) {
    return; // unsupported command
  }

  unsigned int absCount = Abs(count);
  for (unsigned int i = 0; i < absCount; ++i) {
    gCurrentCallback(command, gCurrentCallbackData);
  }
}

static void
paste_clipboard_cb(GtkWidget *w, gpointer user_data)
{
  gCurrentCallback(CommandPaste, gCurrentCallbackData);
  g_signal_stop_emission_by_name(w, "paste_clipboard");
  gHandled = true;
}

// GtkTextView-only signals
static void
select_all_cb(GtkWidget *w, gboolean select, gpointer user_data)
{
  gCurrentCallback(CommandSelectAll, gCurrentCallbackData);
  g_signal_stop_emission_by_name(w, "select_all");
  gHandled = true;
}

NativeKeyBindings* NativeKeyBindings::sInstanceForSingleLineEditor = nullptr;
NativeKeyBindings* NativeKeyBindings::sInstanceForMultiLineEditor = nullptr;

// static
NativeKeyBindings*
NativeKeyBindings::GetInstance(NativeKeyBindingsType aType)
{
  switch (aType) {
    case nsIWidget::NativeKeyBindingsForSingleLineEditor:
      if (!sInstanceForSingleLineEditor) {
        sInstanceForSingleLineEditor = new NativeKeyBindings();
        sInstanceForSingleLineEditor->Init(aType);
      }
      return sInstanceForSingleLineEditor;

    default:
      // fallback to multiline editor case in release build
      MOZ_FALLTHROUGH_ASSERT("aType is invalid or not yet implemented");
    case nsIWidget::NativeKeyBindingsForMultiLineEditor:
    case nsIWidget::NativeKeyBindingsForRichTextEditor:
      if (!sInstanceForMultiLineEditor) {
        sInstanceForMultiLineEditor = new NativeKeyBindings();
        sInstanceForMultiLineEditor->Init(aType);
      }
      return sInstanceForMultiLineEditor;
  }
}

// static
void
NativeKeyBindings::Shutdown()
{
  delete sInstanceForSingleLineEditor;
  sInstanceForSingleLineEditor = nullptr;
  delete sInstanceForMultiLineEditor;
  sInstanceForMultiLineEditor = nullptr;
}

void
NativeKeyBindings::Init(NativeKeyBindingsType  aType)
{
  switch (aType) {
  case nsIWidget::NativeKeyBindingsForSingleLineEditor:
    mNativeTarget = gtk_entry_new();
    break;
  default:
    mNativeTarget = gtk_text_view_new();
    if (gtk_major_version > 2 ||
        (gtk_major_version == 2 && (gtk_minor_version > 2 ||
                                    (gtk_minor_version == 2 &&
                                     gtk_micro_version >= 2)))) {
      // select_all only exists in gtk >= 2.2.2.  Prior to that,
      // ctrl+a is bound to (move to beginning, select to end).
      g_signal_connect(mNativeTarget, "select_all",
                       G_CALLBACK(select_all_cb), this);
    }
    break;
  }

  g_object_ref_sink(mNativeTarget);

  g_signal_connect(mNativeTarget, "copy_clipboard",
                   G_CALLBACK(copy_clipboard_cb), this);
  g_signal_connect(mNativeTarget, "cut_clipboard",
                   G_CALLBACK(cut_clipboard_cb), this);
  g_signal_connect(mNativeTarget, "delete_from_cursor",
                   G_CALLBACK(delete_from_cursor_cb), this);
  g_signal_connect(mNativeTarget, "move_cursor",
                   G_CALLBACK(move_cursor_cb), this);
  g_signal_connect(mNativeTarget, "paste_clipboard",
                   G_CALLBACK(paste_clipboard_cb), this);
}

NativeKeyBindings::~NativeKeyBindings()
{
  gtk_widget_destroy(mNativeTarget);
  g_object_unref(mNativeTarget);
}

bool
NativeKeyBindings::Execute(const WidgetKeyboardEvent& aEvent,
                           DoCommandCallback aCallback,
                           void* aCallbackData)
{
  // If the native key event is set, it must be synthesized for tests.
  // We just ignore such events because this behavior depends on system
  // settings.
  if (!aEvent.mNativeKeyEvent) {
    // It must be synthesized event or dispatched DOM event from chrome.
    return false;
  }

  guint keyval;

  if (aEvent.mCharCode) {
    keyval = gdk_unicode_to_keyval(aEvent.mCharCode);
  } else {
    keyval =
      static_cast<GdkEventKey*>(aEvent.mNativeKeyEvent)->keyval;
  }

  if (ExecuteInternal(aEvent, aCallback, aCallbackData, keyval)) {
    return true;
  }

  for (uint32_t i = 0; i < aEvent.mAlternativeCharCodes.Length(); ++i) {
    uint32_t ch = aEvent.IsShift() ?
      aEvent.mAlternativeCharCodes[i].mShiftedCharCode :
      aEvent.mAlternativeCharCodes[i].mUnshiftedCharCode;
    if (ch && ch != aEvent.mCharCode) {
      keyval = gdk_unicode_to_keyval(ch);
      if (ExecuteInternal(aEvent, aCallback, aCallbackData, keyval)) {
        return true;
      }
    }
  }

/*
gtk_bindings_activate_event is preferable, but it has unresolved bug:
http://bugzilla.gnome.org/show_bug.cgi?id=162726
The bug was already marked as FIXED.  However, somebody reports that the
bug still exists.
Also gtk_bindings_activate may work with some non-shortcuts operations
(todo: check it). See bug 411005 and bug 406407.

Code, which should be used after fixing GNOME bug 162726:

  gtk_bindings_activate_event(GTK_OBJECT(mNativeTarget),
    static_cast<GdkEventKey*>(aEvent.mNativeKeyEvent));
*/

  return false;
}

bool
NativeKeyBindings::ExecuteInternal(const WidgetKeyboardEvent& aEvent,
                                   DoCommandCallback aCallback,
                                   void* aCallbackData,
                                   guint aKeyval)
{
  guint modifiers =
    static_cast<GdkEventKey*>(aEvent.mNativeKeyEvent)->state;

  gCurrentCallback = aCallback;
  gCurrentCallbackData = aCallbackData;

  gHandled = false;
#if (MOZ_WIDGET_GTK == 2)
  gtk_bindings_activate(GTK_OBJECT(mNativeTarget),
                        aKeyval, GdkModifierType(modifiers));
#else
  gtk_bindings_activate(G_OBJECT(mNativeTarget),
                        aKeyval, GdkModifierType(modifiers));
#endif

  gCurrentCallback = nullptr;
  gCurrentCallbackData = nullptr;

  return gHandled;
}

} // namespace widget
} // namespace mozilla