Coverage Report

Created: 2026-10-28 06:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/tmux/server-client.c
Line
Count
Source
1
/* $OpenBSD: server-client.c,v 1.530 2026/10/27 13:00:14 nicm Exp $ */
2
3
/*
4
 * Copyright (c) 2009 Nicholas Marriott <nicholas.marriott@gmail.com>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
19
#include <sys/types.h>
20
#include <sys/ioctl.h>
21
#include <sys/uio.h>
22
23
#include <errno.h>
24
#include <fcntl.h>
25
#include <stdlib.h>
26
#include <string.h>
27
#include <time.h>
28
#include <unistd.h>
29
30
#include "tmux.h"
31
32
static void server_client_free(int, short, void *);
33
static void server_client_check_pane_resize(struct window_pane *);
34
static void server_client_check_pane_buffer(struct window_pane *);
35
static void server_client_check_window_resize(struct window *);
36
static key_code server_client_check_mouse(struct client *, struct key_event *);
37
static void server_client_repeat_timer(int, short, void *);
38
static void server_client_click_timer(int, short, void *);
39
static void server_client_check_exit(struct client *, int);
40
static void server_client_exit_timer(int, short, void *);
41
static void server_client_check_redraw(struct client *);
42
static void server_client_check_modes(struct client *);
43
static void server_client_set_title(struct client *);
44
static void server_client_set_path(struct client *);
45
static void server_client_set_progress_bar(struct client *);
46
static void server_client_reset_state(struct client *);
47
static void server_client_update_latest(struct client *);
48
static int  server_client_handle_dead_key(struct window_pane *, key_code);
49
static int  server_client_handle_key0(struct client *, struct key_event *,
50
        struct cmdq_item *, struct cmdq_item **, int);
51
static enum cmd_retval  server_client_key_callback(struct cmdq_item *, void *);
52
static void server_client_dispatch(struct imsg *, void *);
53
static int  server_client_dispatch_command(struct client *, struct imsg *);
54
static int  server_client_dispatch_identify(struct client *, struct imsg *);
55
static int  server_client_dispatch_shell(struct client *);
56
static void server_client_report_theme(struct client *, enum client_theme);
57
58
/* Clients that have been lost but not yet freed. */
59
struct clients dead_clients = TAILQ_HEAD_INITIALIZER(dead_clients);
60
61
/* Number of attached clients. */
62
u_int
63
server_client_how_many(void)
64
0
{
65
0
  struct client *c;
66
0
  u_int    n;
67
68
0
  n = 0;
69
0
  TAILQ_FOREACH(c, &clients, entry) {
70
0
    if (c->session != NULL && (~c->flags & CLIENT_UNATTACHEDFLAGS))
71
0
      n++;
72
0
  }
73
0
  return (n);
74
0
}
75
76
/* Are these ranges empty? That is, nothing is visible. */
77
int
78
server_client_ranges_is_empty(struct visible_ranges *r)
79
0
{
80
0
  u_int i;
81
82
0
  for (i = 0; i < r->used; i++) {
83
0
    if (r->ranges[i].nx != 0)
84
0
      return (0);
85
0
  }
86
0
  return (1);
87
0
}
88
89
/* Ensure we have space for at least n ranges. */
90
void
91
server_client_ensure_ranges(struct visible_ranges *r, u_int n)
92
2.36M
{
93
2.36M
  if (r->size >= n)
94
2.35M
    return;
95
12.3k
  r->ranges = xrecallocarray(r->ranges, r->size, n, sizeof *r->ranges);
96
12.3k
  r->size = n;
97
12.3k
}
98
99
/* Check if this client is inside this server. */
100
int
101
server_client_check_nested(struct client *c)
102
0
{
103
0
  struct environ_entry  *envent;
104
0
  struct window_pane  *wp;
105
106
0
  envent = environ_find(c->environ, "TMUX");
107
0
  if (envent == NULL || *envent->value == '\0')
108
0
    return (0);
109
110
0
  RB_FOREACH(wp, window_pane_tree, &all_window_panes) {
111
0
    if (strcmp(wp->tty, c->ttyname) == 0)
112
0
      return (1);
113
0
  }
114
0
  return (0);
115
0
}
116
117
/* Set client key table. */
118
void
119
server_client_set_key_table(struct client *c, const char *name)
120
0
{
121
0
  if (name == NULL)
122
0
    name = server_client_get_key_table(c);
123
124
0
  key_bindings_unref_table(c->keytable);
125
0
  c->keytable = key_bindings_get_table(name, 1);
126
0
  c->keytable->references++;
127
0
  if (gettimeofday(&c->keytable->activity_time, NULL) != 0)
128
0
    fatal("gettimeofday failed");
129
0
}
130
131
static uint64_t
132
server_client_key_table_activity_diff(struct client *c)
133
0
{
134
0
  struct timeval  diff;
135
136
0
  timersub(&c->activity_time, &c->keytable->activity_time, &diff);
137
0
  return ((diff.tv_sec * 1000ULL) + (diff.tv_usec / 1000ULL));
138
0
}
139
140
/* Get default key table. */
141
const char *
142
server_client_get_key_table(struct client *c)
143
0
{
144
0
  struct session  *s = c->session;
145
0
  const char  *name;
146
147
0
  if (s == NULL)
148
0
    return ("root");
149
150
0
  name = options_get_string(s->options, "key-table");
151
0
  if (*name == '\0')
152
0
    return ("root");
153
0
  return (name);
154
0
}
155
156
/* Is this table the default key table? */
157
static int
158
server_client_is_default_key_table(struct client *c, struct key_table *table)
159
0
{
160
0
  return (strcmp(table->name, server_client_get_key_table(c)) == 0);
161
0
}
162
163
/* Create a new client. */
164
struct client *
165
server_client_create(int fd)
166
0
{
167
0
  struct client *c;
168
0
  u_int    i;
169
170
0
  setblocking(fd, 0);
171
172
0
  c = xcalloc(1, sizeof *c);
173
0
  c->references = 1;
174
0
  c->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);
175
176
0
  if (gettimeofday(&c->creation_time, NULL) != 0)
177
0
    fatal("gettimeofday failed");
178
0
  memcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);
179
180
0
  c->environ = environ_create();
181
182
0
  c->fd = -1;
183
0
  c->out_fd = -1;
184
185
0
  c->queue = cmdq_new();
186
0
  RB_INIT(&c->files);
187
188
0
  c->tty.sx = 80;
189
0
  c->tty.sy = 24;
190
191
0
  for (i = 0; i < COLOUR_THEME_COUNT; i++)
192
0
    c->theme_colours[i] = 8;
193
0
  c->theme = THEME_UNKNOWN;
194
195
0
  status_init(c);
196
0
  status_side_init(c);
197
0
  c->flags |= CLIENT_FOCUSED;
198
199
0
  c->keytable = key_bindings_get_table("root", 1);
200
0
  c->keytable->references++;
201
202
0
  evtimer_set(&c->repeat_timer, server_client_repeat_timer, c);
203
0
  evtimer_set(&c->click_timer, server_client_click_timer, c);
204
0
  evtimer_set(&c->exit_timer, server_client_exit_timer, c);
205
206
0
  c->click_wp = -1;
207
208
0
  TAILQ_INIT(&c->input_requests);
209
210
0
  TAILQ_INSERT_TAIL(&clients, c, entry);
211
0
  log_debug("new client %p", c);
212
0
  return (c);
213
0
}
214
215
/* Open client terminal if needed. */
216
int
217
server_client_open(struct client *c, char **cause)
218
0
{
219
0
  const char  *ttynam = _PATH_TTY;
220
221
0
  if (c->flags & CLIENT_CONTROL)
222
0
    return (0);
223
224
0
  if (strcmp(c->ttyname, ttynam) == 0||
225
0
      ((isatty(STDIN_FILENO) &&
226
0
      (ttynam = ttyname(STDIN_FILENO)) != NULL &&
227
0
      strcmp(c->ttyname, ttynam) == 0) ||
228
0
      (isatty(STDOUT_FILENO) &&
229
0
      (ttynam = ttyname(STDOUT_FILENO)) != NULL &&
230
0
      strcmp(c->ttyname, ttynam) == 0) ||
231
0
      (isatty(STDERR_FILENO) &&
232
0
      (ttynam = ttyname(STDERR_FILENO)) != NULL &&
233
0
      strcmp(c->ttyname, ttynam) == 0))) {
234
0
    xasprintf(cause, "can't use %s", c->ttyname);
235
0
    return (-1);
236
0
  }
237
238
0
  if (!(c->flags & CLIENT_TERMINAL)) {
239
0
    *cause = xstrdup("not a terminal");
240
0
    return (-1);
241
0
  }
242
243
0
  if (tty_open(&c->tty, cause) != 0)
244
0
    return (-1);
245
246
0
  server_client_update_theme_colours(c);
247
0
  return (0);
248
0
}
249
250
/* Lost an attached client. */
251
static void
252
server_client_attached_lost(struct client *c)
253
0
{
254
0
  struct session  *s;
255
0
  struct window *w;
256
0
  struct client *loop;
257
0
  struct client *found;
258
259
0
  log_debug("lost attached client %p", c);
260
261
  /*
262
   * By this point the session in the client has been cleared so walk all
263
   * windows to find any with this client as the latest.
264
   */
265
0
  RB_FOREACH(w, windows, &windows) {
266
0
    if (w->latest != c)
267
0
      continue;
268
269
0
    found = NULL;
270
0
    TAILQ_FOREACH(loop, &clients, entry) {
271
0
      s = loop->session;
272
0
      if (loop == c || s == NULL || s->curw->window != w)
273
0
        continue;
274
0
      if (found == NULL || timercmp(&loop->activity_time,
275
0
          &found->activity_time, >))
276
0
        found = loop;
277
0
    }
278
0
    if (found != NULL)
279
0
      server_client_update_latest(found);
280
0
  }
281
0
}
282
283
/* Fire client session changed. */
284
static void
285
server_client_fire_session_changed(struct client *c, struct session *old)
286
0
{
287
0
  struct event_payload  *ep;
288
0
  struct cmd_find_state  fs;
289
290
0
  ep = event_payload_create();
291
0
  cmd_find_from_client(&fs, c, 0);
292
0
  event_payload_set_target(ep, &fs);
293
0
  event_payload_set_client(ep, "client", c);
294
0
  if (fs.s != NULL) {
295
0
    event_payload_set_session(ep, "session", fs.s);
296
0
    event_payload_set_session(ep, "new_session", fs.s);
297
0
  }
298
0
  if (old != NULL)
299
0
    event_payload_set_session(ep, "old_session", old);
300
0
  if (fs.w != NULL)
301
0
    event_payload_set_window(ep, "window", fs.w);
302
0
  if (fs.wl != NULL)
303
0
    event_payload_set_int(ep, "window_index", fs.wl->idx);
304
0
  else if (fs.idx != -1)
305
0
    event_payload_set_int(ep, "window_index", fs.idx);
306
0
  if (fs.wp != NULL)
307
0
    event_payload_set_pane(ep, "pane", fs.wp);
308
0
  events_fire("client-session-changed", ep);
309
0
}
310
311
/* Fire client resized. */
312
static void
313
server_client_fire_resized(struct client *c, u_int old_sx, u_int old_sy)
314
0
{
315
0
  struct event_payload  *ep;
316
0
  struct cmd_find_state  fs;
317
318
0
  ep = event_payload_create();
319
0
  cmd_find_from_client(&fs, c, 0);
320
0
  event_payload_set_target(ep, &fs);
321
0
  event_payload_set_client(ep, "client", c);
322
0
  if (fs.s != NULL)
323
0
    event_payload_set_session(ep, "session", fs.s);
324
0
  if (fs.w != NULL)
325
0
    event_payload_set_window(ep, "window", fs.w);
326
0
  if (fs.wl != NULL)
327
0
    event_payload_set_int(ep, "window_index", fs.wl->idx);
328
0
  else if (fs.idx != -1)
329
0
    event_payload_set_int(ep, "window_index", fs.idx);
330
0
  if (fs.wp != NULL)
331
0
    event_payload_set_pane(ep, "pane", fs.wp);
332
0
  event_payload_set_uint(ep, "width", c->tty.sx);
333
0
  event_payload_set_uint(ep, "height", c->tty.sy);
334
0
  event_payload_set_uint(ep, "old_width", old_sx);
335
0
  event_payload_set_uint(ep, "old_height", old_sy);
336
0
  events_fire("client-resized", ep);
337
0
}
338
339
/* Recalculate sizes and notify a resized client. */
340
static void
341
server_client_apply_resize(struct client *c, u_int old_sx, u_int old_sy)
342
0
{
343
0
  if (c->session != NULL) {
344
0
    recalculate_sizes();
345
0
    server_redraw_client(c);
346
0
    server_client_fire_resized(c, old_sx, old_sy);
347
0
  }
348
0
}
349
350
/* Apply a new reported size. */
351
void
352
server_client_size_changed(struct client *c, u_int sx, u_int sy)
353
0
{
354
0
  u_int old_sx = c->tty.sx, old_sy = c->tty.sy;
355
356
0
  if (c->flags & CLIENT_CONTROL)
357
0
    return;
358
0
  if (sx == 0 || sy == 0 || (sx == old_sx && sy == old_sy))
359
0
    return;
360
361
0
  log_debug("%s: reported size %ux%u (was %ux%u)", c->name, sx, sy,
362
0
      old_sx, old_sy);
363
0
  server_client_update_latest(c);
364
0
  tty_set_size(&c->tty, sx, sy, c->tty.xpixel, c->tty.ypixel);
365
0
  tty_invalidate(&c->tty);
366
0
  server_client_apply_resize(c, old_sx, old_sy);
367
0
}
368
369
/* Set client session. */
370
void
371
server_client_set_session(struct client *c, struct session *s)
372
0
{
373
0
  struct session  *old = c->session;
374
375
0
  if (s != NULL && c->session != NULL && c->session != s)
376
0
    c->last_session = c->session;
377
0
  else if (s == NULL)
378
0
    c->last_session = NULL;
379
0
  c->session = s;
380
0
  c->flags |= CLIENT_FOCUSED;
381
382
0
  if (old != NULL && old->curw != NULL)
383
0
    window_update_focus(old->curw->window);
384
0
  if (s != NULL) {
385
0
    s->curw->window->latest = c;
386
0
    recalculate_sizes();
387
0
    window_update_focus(s->curw->window);
388
0
    session_update_activity(s, NULL);
389
0
    session_theme_changed(s);
390
0
    gettimeofday(&s->last_attached_time, NULL);
391
0
    s->curw->flags &= ~WINLINK_ALERTFLAGS;
392
0
    alerts_check_session(s);
393
0
    tty_update_client_offset(c);
394
0
    status_timer_start(c);
395
0
    server_client_fire_session_changed(c, old);
396
397
    /*
398
     * Redraw if the session or displayed window changed. Use the
399
     * cached scene because the session's current window is already set.
400
     */
401
0
    if (old != s || !redraw_client_has_window(c, s->curw->window))
402
0
      server_redraw_client(c);
403
0
  }
404
405
0
  server_check_unattached();
406
0
  server_update_socket();
407
0
}
408
409
/* Lost a client. */
410
void
411
server_client_lost(struct client *c)
412
0
{
413
0
  struct client_file  *cf, *cf1;
414
415
0
  cfg_client_lost(c);
416
0
  c->flags |= CLIENT_DEAD;
417
418
0
  status_prompt_clear(c);
419
0
  status_message_clear(c);
420
421
0
  RB_FOREACH_SAFE(cf, client_files, &c->files, cf1) {
422
0
    cf->error = EINTR;
423
0
    file_fire_done(cf);
424
0
  }
425
426
0
  TAILQ_REMOVE(&clients, c, entry);
427
0
  TAILQ_INSERT_TAIL(&dead_clients, c, entry);
428
0
  log_debug("lost client %p", c);
429
430
0
  cmd_wait_for_client_lost(c);
431
0
  cmdq_next(c);
432
433
0
  if (c->flags & CLIENT_ATTACHED) {
434
0
    server_client_attached_lost(c);
435
0
    events_fire_client("client-detached", c);
436
0
  }
437
0
  if (c->name != NULL && (c->flags & (CLIENT_CONTROL|CLIENT_TERMINAL)))
438
0
    events_fire_client("client-closed", c);
439
440
0
  c->session = NULL;
441
0
  c->last_session = NULL;
442
443
0
  if (c->flags & CLIENT_CONTROL)
444
0
    control_stop(c);
445
0
  if (c->flags & CLIENT_TERMINAL)
446
0
    tty_free(&c->tty);
447
0
  free(c->ttyname);
448
0
  free(c->clipboard_panes);
449
450
0
  free(c->term_name);
451
0
  free(c->term_type);
452
0
  tty_term_free_list(c->term_caps, c->term_ncaps);
453
454
0
  status_free(c);
455
0
  status_side_free(c);
456
0
  input_cancel_requests(c);
457
458
0
  free(c->title);
459
0
  free(c->path);
460
0
  free((void *)c->cwd);
461
0
  free(c->exit_session);
462
0
  free(c->exit_message);
463
464
0
  evtimer_del(&c->repeat_timer);
465
0
  evtimer_del(&c->click_timer);
466
0
  evtimer_del(&c->exit_timer);
467
0
  if (event_initialized(&c->cycle_timer))
468
0
    evtimer_del(&c->cycle_timer);
469
470
0
  key_bindings_unref_table(c->keytable);
471
472
0
  free(c->message_string);
473
0
  if (event_initialized(&c->message_timer))
474
0
    evtimer_del(&c->message_timer);
475
0
  prompt_free(c->prompt);
476
477
0
  format_lost_client(c);
478
0
  environ_free(c->environ);
479
480
0
  proc_remove_peer(c->peer);
481
0
  c->peer = NULL;
482
483
0
  if (c->out_fd != -1)
484
0
    close(c->out_fd);
485
0
  if (c->fd != -1) {
486
0
    close(c->fd);
487
0
    c->fd = -1;
488
0
  }
489
0
  server_client_unref(c);
490
491
0
  server_add_accept(0); /* may be more file descriptors now */
492
493
0
  recalculate_sizes();
494
0
  server_check_unattached();
495
0
  server_update_socket();
496
0
}
497
498
/* Remove reference from a client. */
499
void
500
server_client_unref(struct client *c)
501
0
{
502
0
  log_debug("unref client %p (%d references)", c, c->references);
503
504
0
  c->references--;
505
0
  if (c->references == 0)
506
0
    event_once(-1, EV_TIMEOUT, server_client_free, c, NULL);
507
0
}
508
509
/* Free dead client. */
510
static void
511
server_client_free(__unused int fd, __unused short events, void *arg)
512
0
{
513
0
  struct client *c = arg;
514
515
0
  log_debug("free client %p (%d references)", c, c->references);
516
517
0
  TAILQ_REMOVE(&dead_clients, c, entry);
518
0
  redraw_free_scene(c->redraw_scene);
519
0
  cmdq_free(c->queue);
520
521
0
  if (c->references == 0) {
522
0
    free((void *)c->name);
523
0
    free((void *)c->user);
524
0
    free(c);
525
0
  }
526
0
}
527
528
/* Suspend a client. */
529
void
530
server_client_suspend(struct client *c)
531
0
{
532
0
  struct session  *s = c->session;
533
534
0
  if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
535
0
    return;
536
537
0
  tty_stop_tty(&c->tty);
538
0
  c->flags |= CLIENT_SUSPENDED;
539
0
  proc_send(c->peer, MSG_SUSPEND, -1, NULL, 0);
540
0
}
541
542
/* Detach a client. */
543
void
544
server_client_detach(struct client *c, enum msgtype msgtype)
545
0
{
546
0
  struct session  *s = c->session;
547
548
0
  if (s == NULL || (c->flags & CLIENT_NODETACHFLAGS))
549
0
    return;
550
551
0
  c->flags |= CLIENT_EXIT;
552
553
0
  c->exit_type = CLIENT_EXIT_DETACH;
554
0
  c->exit_msgtype = msgtype;
555
0
  c->exit_session = xstrdup(s->name);
556
0
}
557
558
/* Execute command to replace a client. */
559
void
560
server_client_exec(struct client *c, const char *cmd)
561
0
{
562
0
  struct session  *s = c->session;
563
0
  char    *msg;
564
0
  const char  *shell;
565
0
  size_t     cmdsize, shellsize;
566
567
0
  if (*cmd == '\0')
568
0
    return;
569
0
  cmdsize = strlen(cmd) + 1;
570
571
0
  if (s != NULL)
572
0
    shell = options_get_string(s->options, "default-shell");
573
0
  else
574
0
    shell = options_get_string(global_s_options, "default-shell");
575
0
  if (!checkshell(shell))
576
0
    shell = _PATH_BSHELL;
577
0
  shellsize = strlen(shell) + 1;
578
579
0
  msg = xmalloc(cmdsize + shellsize);
580
0
  memcpy(msg, cmd, cmdsize);
581
0
  memcpy(msg + cmdsize, shell, shellsize);
582
583
0
  proc_send(c->peer, MSG_EXEC, -1, msg, cmdsize + shellsize);
584
0
  free(msg);
585
0
}
586
587
/* Is this point inside the auto-hide scrollbar interaction area? */
588
static int
589
server_client_in_scrollbar_area(struct window_pane *wp, int px, int py)
590
0
{
591
0
  struct window *w = wp->window;
592
0
  u_int    width, pad, total;
593
0
  int    start, end;
594
595
0
  if (!window_pane_scrollbar_overlay(wp))
596
0
    return (0);
597
0
  if (py < wp->yoff || py >= wp->yoff + (int)wp->sy)
598
0
    return (0);
599
600
0
  width = wp->scrollbar_style.width;
601
0
  pad = wp->scrollbar_style.pad;
602
0
  total = width + pad;
603
0
  if (total == 0 || total > wp->sx)
604
0
    total = wp->sx;
605
606
0
  if (w->sb_pos == PANE_SCROLLBARS_LEFT) {
607
0
    start = wp->xoff;
608
0
    end = wp->xoff + (int)total - 1;
609
0
  } else {
610
0
    end = wp->xoff + (int)wp->sx - 1;
611
0
    start = end - (int)total + 1;
612
0
  }
613
0
  return (px >= start && px <= end);
614
0
}
615
616
/* Update auto-hide scrollbars for a mouse movement. */
617
static void
618
server_client_update_scrollbar_hover(struct client *c, int type, int px, int py)
619
0
{
620
0
  struct window   *w = c->session->curw->window;
621
0
  struct window_pane  *wp;
622
623
0
  if (type != KEYC_TYPE_MOUSEMOVE)
624
0
    return;
625
626
0
  TAILQ_FOREACH(wp, &w->panes, entry) {
627
0
    if (!window_pane_is_visible(wp))
628
0
      continue;
629
0
    if (server_client_in_scrollbar_area(wp, px, py)) {
630
0
      wp->sb_auto_hover = 1;
631
0
      window_pane_scrollbar_show(wp, 1);
632
0
    } else {
633
0
      wp->sb_auto_hover = 0;
634
0
      window_pane_scrollbar_start_timer(wp);
635
0
    }
636
0
  }
637
0
}
638
639
/* Is the mouse inside a pane? */
640
static enum key_code_mouse_location
641
server_client_check_mouse_in_pane(struct window_pane *wp, int px, int py,
642
    u_int *sl_mpos)
643
0
{
644
0
  struct window   *w = wp->window;
645
0
  struct window_pane  *fwp;
646
0
  int      pane_status, sb_w, sb_pad;
647
0
  int      pane_status_line, sl_top, sl_bottom;
648
0
  int      bdr_bottom, bdr_top, bdr_left, bdr_right;
649
0
  int      sb_start, sb_end, sb_overlay;
650
651
0
  pane_status = window_pane_get_pane_status(wp);
652
0
  sb_overlay = window_pane_scrollbar_overlay(wp);
653
654
0
  if (window_pane_scrollbar_visible(wp)) {
655
0
    sb_w = wp->scrollbar_style.width;
656
0
    sb_pad = wp->scrollbar_style.pad;
657
0
    if (sb_overlay && sb_w > (int)wp->sx)
658
0
      sb_w = wp->sx;
659
0
  } else {
660
0
    sb_w = 0;
661
0
    sb_pad = 0;
662
0
  }
663
664
0
  if (pane_status == PANE_STATUS_TOP)
665
0
    pane_status_line = wp->yoff - 1;
666
0
  else if (pane_status == PANE_STATUS_BOTTOM)
667
0
    pane_status_line = wp->yoff + wp->sy;
668
0
  else
669
0
    pane_status_line = -1; /* not used */
670
0
  bdr_left = wp->xoff - 1;
671
0
  if (!sb_overlay && w->sb_pos == PANE_SCROLLBARS_LEFT)
672
0
    bdr_left -= sb_pad + sb_w;
673
674
0
  if (sb_overlay && sb_w != 0 &&
675
0
      py >= wp->yoff && py < wp->yoff + (int)wp->sy &&
676
0
      px >= wp->xoff && px < wp->xoff + (int)wp->sx) {
677
0
    if (w->sb_pos == PANE_SCROLLBARS_LEFT) {
678
0
      sb_start = wp->xoff;
679
0
      sb_end = sb_start + sb_w - 1;
680
0
    } else {
681
0
      sb_end = wp->xoff + (int)wp->sx - 1;
682
0
      sb_start = sb_end - sb_w + 1;
683
0
    }
684
0
    if (px >= sb_start && px <= sb_end) {
685
0
      sl_top = wp->yoff + wp->sb_slider_y;
686
0
      sl_bottom = (wp->yoff + wp->sb_slider_y +
687
0
          wp->sb_slider_h - 1);
688
0
      if (py < sl_top)
689
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_UP);
690
0
      else if (py >= sl_top && py <= sl_bottom) {
691
0
        *sl_mpos = (py - wp->sb_slider_y - wp->yoff);
692
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_SLIDER);
693
0
      } else
694
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_DOWN);
695
0
    }
696
0
    return (KEYC_MOUSE_LOCATION_PANE);
697
0
  }
698
699
  /* Check if point is within the pane or scrollbar. */
700
0
  if (((pane_status != PANE_STATUS_OFF &&
701
0
      py != pane_status_line && py != wp->yoff + (int)wp->sy) ||
702
0
      (wp->yoff == 0 && py < (int)wp->sy) ||
703
0
      (py >= wp->yoff && py < wp->yoff + (int)wp->sy)) &&
704
0
      ((w->sb_pos == PANE_SCROLLBARS_RIGHT &&
705
0
      px < wp->xoff + (int)wp->sx + sb_pad + sb_w) ||
706
0
      (w->sb_pos == PANE_SCROLLBARS_LEFT &&
707
0
      px < wp->xoff + (int)wp->sx - sb_pad - sb_w))) {
708
    /* Check if in the scrollbar. */
709
0
    if ((w->sb_pos == PANE_SCROLLBARS_RIGHT &&
710
0
        (px >= wp->xoff + (int)wp->sx + sb_pad &&
711
0
        px < wp->xoff + (int)wp->sx + sb_pad + sb_w)) ||
712
0
        (w->sb_pos == PANE_SCROLLBARS_LEFT &&
713
0
        (px >= wp->xoff - sb_pad - sb_w &&
714
0
        px < wp->xoff - sb_pad))) {
715
      /* Check where inside the scrollbar. */
716
0
      sl_top = wp->yoff + wp->sb_slider_y;
717
0
      sl_bottom = (wp->yoff + wp->sb_slider_y +
718
0
          wp->sb_slider_h - 1);
719
0
      if (py < sl_top)
720
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_UP);
721
0
      else if (py >= sl_top && py <= sl_bottom) {
722
0
        *sl_mpos = (py - wp->sb_slider_y - wp->yoff);
723
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_SLIDER);
724
0
      } else /* py > sl_bottom */
725
0
        return (KEYC_MOUSE_LOCATION_SCROLLBAR_DOWN);
726
0
    } else if (window_pane_is_floating(wp) &&
727
0
        window_pane_get_pane_lines(wp) != PANE_LINES_NONE &&
728
0
        (px == bdr_left ||
729
0
        py == wp->yoff - 1 ||
730
0
        py == wp->yoff + (int)wp->sy)) {
731
      /* Floating pane left, bottom or top border. */
732
0
      return (KEYC_MOUSE_LOCATION_BORDER);
733
0
    } else {
734
      /* Must be inside the pane. */
735
0
      return (KEYC_MOUSE_LOCATION_PANE);
736
0
    }
737
0
  } else {
738
    /* Try the pane borders. */
739
0
    TAILQ_FOREACH(fwp, &w->panes, entry) {
740
0
      if (!window_pane_is_visible(fwp))
741
0
        continue;
742
0
      if (window_pane_is_floating(fwp) &&
743
0
          window_pane_get_pane_lines(fwp) == PANE_LINES_NONE)
744
0
        continue;
745
0
      if (window_pane_scrollbar_reserve(fwp)) {
746
0
        sb_w = fwp->scrollbar_style.width;
747
0
        sb_pad = fwp->scrollbar_style.pad;
748
0
      } else {
749
0
        sb_w = 0;
750
0
        sb_pad = 0;
751
0
      }
752
0
      bdr_top = fwp->yoff - 1;
753
0
      bdr_bottom = fwp->yoff + fwp->sy;
754
0
      bdr_left = fwp->xoff - 1;
755
0
      if (w->sb_pos == PANE_SCROLLBARS_LEFT) {
756
0
        bdr_left -= sb_pad + sb_w;
757
0
        bdr_right = fwp->xoff + fwp->sx;
758
0
      } else {
759
        /* PANE_SCROLLBARS_RIGHT or none. */
760
0
        bdr_right = fwp->xoff + fwp->sx + sb_pad + sb_w;
761
0
      }
762
0
      if (py >= fwp->yoff - 1 &&
763
0
          py <= fwp->yoff + (int)fwp->sy) {
764
0
        if (px == bdr_right)
765
0
          break;
766
0
        if (window_pane_is_floating(wp)) {
767
          /* Floating pane, check left border. */
768
0
          if (px == bdr_left)
769
0
            break;
770
0
        }
771
0
      }
772
0
      if (px >= bdr_left && px <= fwp->xoff + (int)fwp->sx) {
773
0
        bdr_bottom = fwp->yoff + fwp->sy;
774
0
        if (py == bdr_bottom)
775
0
          break;
776
0
        if (py == bdr_top)
777
0
          break;
778
0
      }
779
0
    }
780
0
    if (fwp != NULL)
781
0
      return (KEYC_MOUSE_LOCATION_BORDER);
782
0
  }
783
0
  return (KEYC_MOUSE_LOCATION_NOWHERE);
784
0
}
785
786
/* Check for mouse events on the status lines. */
787
static int
788
server_client_check_mouse_status(struct client *c, struct mouse_event *m,
789
    enum key_code_type type, u_int x, u_int y,
790
    enum key_code_mouse_location *loc)
791
0
{
792
0
  struct tty      *tty = &c->tty;
793
0
  struct winlink      *fwl;
794
0
  struct window_pane    *fwp;
795
0
  struct session      *s = c->session, *fs;
796
0
  struct style_range    *sr;
797
0
  u_int        n, sidey, separator;
798
0
  int        side = 0, mflag = tty->mouse_drag_flag;
799
0
  enum key_code_mouse_location   mloc = tty->mouse_drag_location;
800
801
0
  *loc = KEYC_MOUSE_LOCATION_NOWHERE;
802
803
0
  m->statusat = status_at_line(c);
804
0
  m->statuslines = status_line_size(c);
805
0
  m->sideat = status_side_at_column(c);
806
0
  m->sidewidth = status_side_size(c);
807
808
0
  if (mflag != 0 && mloc == KEYC_MOUSE_LOCATION_SIDE_STATUS_BORDER) {
809
0
    *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_BORDER;
810
0
    return (0);
811
0
  }
812
813
0
  if (m->statusat != -1 &&
814
0
      y >= (u_int)m->statusat &&
815
0
      y < m->statusat + m->statuslines) {
816
0
    sr = status_get_range(c, x, y - m->statusat);
817
0
  } else {
818
0
    if (m->sideat == -1 ||
819
0
        x < (u_int)m->sideat ||
820
0
        x >= m->sideat + m->sidewidth) {
821
0
      goto not_on_status;
822
0
    }
823
0
    if (m->statusat == 0)
824
0
      sidey = m->statuslines;
825
0
    else
826
0
      sidey = 0;
827
0
    if (y < sidey || y - sidey >= status_side_rows(c))
828
0
      goto not_on_status;
829
0
    separator = m->sideat;
830
0
    if (separator == 0)
831
0
      separator = m->sidewidth - 1;
832
0
    if (m->sidewidth > 1 && x == separator) {
833
0
      *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_BORDER;
834
0
      if (type == KEYC_TYPE_MOUSEDRAG && mflag == 0)
835
0
        tty->mouse_drag_status = 1;
836
0
      return (0);
837
0
    }
838
0
    side = 1;
839
0
    sr = status_side_get_range(c, x - m->sideat, y - sidey);
840
0
  }
841
0
  if (type == KEYC_TYPE_MOUSEDRAG && mflag == 0)
842
0
    tty->mouse_drag_status = 1;
843
0
  if (sr == NULL) {
844
0
    if (side)
845
0
      *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_DEFAULT;
846
0
    else
847
0
      *loc = KEYC_MOUSE_LOCATION_STATUS_DEFAULT;
848
0
    return (0);
849
0
  }
850
851
0
  if (side)
852
0
    *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS;
853
0
  else
854
0
    *loc = KEYC_MOUSE_LOCATION_STATUS;
855
0
  switch (sr->type) {
856
0
  case STYLE_RANGE_NONE:
857
0
    return (-1);
858
0
  case STYLE_RANGE_LEFT:
859
0
    log_debug("mouse range: left");
860
0
    if (side)
861
0
      *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_LEFT;
862
0
    else
863
0
      *loc = KEYC_MOUSE_LOCATION_STATUS_LEFT;
864
0
    break;
865
0
  case STYLE_RANGE_RIGHT:
866
0
    log_debug("mouse range: right");
867
0
    if (side)
868
0
      *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_RIGHT;
869
0
    else
870
0
      *loc = KEYC_MOUSE_LOCATION_STATUS_RIGHT;
871
0
    break;
872
0
  case STYLE_RANGE_PANE:
873
0
    fwp = window_pane_find_by_id(sr->argument);
874
0
    if (fwp == NULL)
875
0
      return (-1);
876
0
    m->wp = sr->argument;
877
878
0
    log_debug("mouse range: pane %%%u", m->wp);
879
0
    break;
880
0
  case STYLE_RANGE_WINDOW:
881
0
    fwl = winlink_find_by_index(&s->windows, sr->argument);
882
0
    if (fwl == NULL)
883
0
      return (-1);
884
0
    m->w = fwl->window->id;
885
886
0
    log_debug("mouse range: window @%u", m->w);
887
0
    break;
888
0
  case STYLE_RANGE_SESSION:
889
0
    fs = session_find_by_id(sr->argument);
890
0
    if (fs == NULL)
891
0
      return (-1);
892
0
    m->s = sr->argument;
893
894
0
    log_debug("mouse range: session $%u", m->s);
895
0
    break;
896
0
  case STYLE_RANGE_USER:
897
0
    log_debug("mouse range: user");
898
0
    break;
899
0
  case STYLE_RANGE_CONTROL:
900
0
    n = sr->argument; /* parsing keeps this < 10 */
901
0
    log_debug("mouse range: control %u", n);
902
0
    if (side)
903
0
      *loc = KEYC_MOUSE_LOCATION_SIDE_STATUS_CONTROL0 + n;
904
0
    else
905
0
      *loc = KEYC_MOUSE_LOCATION_CONTROL0 + n;
906
0
    break;
907
0
  }
908
0
  return (0);
909
910
0
not_on_status:
911
  /* Keep drags started on status lines from triggering pane bindings. */
912
0
  if (type == KEYC_TYPE_MOUSEDRAG && tty->mouse_drag_status)
913
0
    *loc = mloc;
914
0
  return (0);
915
0
}
916
917
/* Check for mouse keys. */
918
static key_code
919
server_client_check_mouse(struct client *c, struct key_event *event)
920
0
{
921
0
  struct mouse_event    *m = &event->m;
922
0
  struct session      *s = c->session;
923
0
  struct window     *w = s->curw->window;
924
0
  struct window_pane    *wp, *lwp = NULL;
925
0
  u_int        x, y, sx, sy, px, py, n, sl_mpos = 0;
926
0
  u_int        b, bn;
927
0
  int        ignore = 0;
928
0
  int        modal_drag = 0;
929
0
  key_code       key;
930
0
  struct timeval       tv;
931
0
  struct style_range    *sr;
932
0
  enum key_code_type     type = KEYC_TYPE_NOTYPE;
933
0
  enum key_code_mouse_location   loc = KEYC_MOUSE_LOCATION_NOWHERE;
934
935
0
  log_debug("%s mouse %02x at %u,%u (last %u,%u) (%d)", c->name, m->b,
936
0
      m->x, m->y, m->lx, m->ly, c->tty.mouse_drag_flag);
937
938
  /* Find last pane, if any. */
939
0
  if (c->tty.mouse_last_pane != -1) {
940
0
    lwp = window_pane_find_by_id(c->tty.mouse_last_pane);
941
0
    if (lwp != NULL)
942
0
      log_debug("%s mouse last pane %%%u", c->name, lwp->id);
943
0
  }
944
945
  /* What type of event is this? */
946
0
  if (event->key == KEYC_DOUBLECLICK) {
947
0
    type = KEYC_TYPE_DOUBLECLICK;
948
0
    x = m->x, y = m->y, b = m->b;
949
0
    ignore = 1;
950
0
    log_debug("double-click at %u,%u", x, y);
951
0
  } else if ((m->sgr_type != ' ' &&
952
0
      MOUSE_DRAG(m->sgr_b) &&
953
0
      MOUSE_RELEASE(m->sgr_b)) ||
954
0
      (m->sgr_type == ' ' &&
955
0
      MOUSE_DRAG(m->b) &&
956
0
      MOUSE_RELEASE(m->b) &&
957
0
      MOUSE_RELEASE(m->lb))) {
958
0
    type = KEYC_TYPE_MOUSEMOVE;
959
0
    x = m->x, y = m->y, b = 0;
960
0
    log_debug("move at %u,%u", x, y);
961
0
  } else if (MOUSE_DRAG(m->b)) {
962
0
    type = KEYC_TYPE_MOUSEDRAG;
963
0
    if (c->tty.mouse_drag_flag) {
964
0
      x = m->x, y = m->y, b = m->b;
965
0
      if (x == m->lx && y == m->ly)
966
0
        return (KEYC_UNKNOWN);
967
0
      log_debug("drag update at %u,%u", x, y);
968
0
    } else {
969
0
      x = m->lx, y = m->ly, b = m->lb;
970
0
      c->tty.mouse_drag_status = 0;
971
0
      log_debug("drag start at %u,%u", x, y);
972
0
    }
973
0
  } else if (MOUSE_WHEEL(m->b)) {
974
0
    if ((m->b & MOUSE_MASK_BUTTONS) == MOUSE_WHEEL_UP)
975
0
      type = KEYC_TYPE_WHEELUP;
976
0
    else
977
0
      type = KEYC_TYPE_WHEELDOWN;
978
0
    x = m->x, y = m->y, b = m->b;
979
0
    log_debug("wheel at %u,%u", x, y);
980
0
  } else if (MOUSE_RELEASE(m->b)) {
981
0
    type = KEYC_TYPE_MOUSEUP;
982
0
    x = m->x, y = m->y, b = m->lb;
983
0
    if (m->sgr_type == 'm')
984
0
      b = m->sgr_b;
985
0
    log_debug("up at %u,%u", x, y);
986
0
  } else {
987
0
    if (c->flags & CLIENT_DOUBLECLICK) {
988
0
      evtimer_del(&c->click_timer);
989
0
      c->flags &= ~CLIENT_DOUBLECLICK;
990
0
      type = KEYC_TYPE_SECONDCLICK;
991
0
      x = m->x, y = m->y, b = m->b;
992
0
      log_debug("second-click at %u,%u", x, y);
993
0
      c->flags |= CLIENT_TRIPLECLICK;
994
0
    } else if (c->flags & CLIENT_TRIPLECLICK) {
995
0
      evtimer_del(&c->click_timer);
996
0
      c->flags &= ~CLIENT_TRIPLECLICK;
997
0
      type = KEYC_TYPE_TRIPLECLICK;
998
0
      x = m->x, y = m->y, b = m->b;
999
0
      log_debug("triple-click at %u,%u", x, y);
1000
0
      goto have_event;
1001
0
    }
1002
1003
    /* DOWN is the only remaining event type. */
1004
0
    if (type == KEYC_TYPE_NOTYPE) {
1005
0
      type = KEYC_TYPE_MOUSEDOWN;
1006
0
      x = m->x, y = m->y, b = m->b;
1007
0
      log_debug("down at %u,%u", x, y);
1008
0
      c->flags |= CLIENT_DOUBLECLICK;
1009
0
    }
1010
0
  }
1011
1012
0
have_event:
1013
0
  if (type == KEYC_TYPE_NOTYPE)
1014
0
    return (KEYC_UNKNOWN);
1015
1016
  /* Save the session. */
1017
0
  m->s = s->id;
1018
0
  m->w = -1;
1019
0
  m->wp = -1;
1020
0
  m->ignore = ignore;
1021
1022
0
  if (server_client_check_mouse_status(c, m, type, x, y, &loc) != 0)
1023
0
    return (KEYC_UNKNOWN);
1024
0
  if (w->modal != NULL && loc != KEYC_MOUSE_LOCATION_NOWHERE)
1025
0
    return (KEYC_UNKNOWN);
1026
1027
  /*
1028
   * Not on status line. Adjust position and check for border, pane, or
1029
   * scrollbar.
1030
   */
1031
0
  if (loc == KEYC_MOUSE_LOCATION_NOWHERE && c->tty.mouse_scrolling_flag) {
1032
0
    if (lwp != NULL) {
1033
0
      loc = KEYC_MOUSE_LOCATION_SCROLLBAR_SLIDER;
1034
0
      m->wp = lwp->id;
1035
0
      m->w = lwp->window->id;
1036
0
    }
1037
0
  } else if (loc == KEYC_MOUSE_LOCATION_NOWHERE) {
1038
0
    if (m->sideat == 0 && x >= m->sidewidth)
1039
0
      px = x - m->sidewidth;
1040
0
    else if (m->sideat > 0 && x >= (u_int)m->sideat)
1041
0
      px = m->sideat - 1;
1042
0
    else
1043
0
      px = x;
1044
0
    if (m->statusat == 0 && y >= m->statuslines)
1045
0
      py = y - m->statuslines;
1046
0
    else if (m->statusat > 0 && y >= (u_int)m->statusat)
1047
0
      py = m->statusat - 1;
1048
0
    else
1049
0
      py = y;
1050
1051
0
    tty_window_offset(&c->tty, &m->ox, &m->oy, &sx, &sy);
1052
0
    log_debug("mouse window @%u at %u,%u (%ux%u)", w->id, m->ox,
1053
0
        m->oy, sx, sy);
1054
0
    if (px > sx || py > sy) {
1055
0
      server_client_update_scrollbar_hover(c, type, -1, -1);
1056
0
      return (KEYC_UNKNOWN);
1057
0
    }
1058
0
    px = px + m->ox;
1059
0
    py = py + m->oy;
1060
0
    if (w->modal != NULL &&
1061
0
        !window_pane_contains(w->modal, px, py)) {
1062
0
      if (lwp == w->modal &&
1063
0
          c->tty.mouse_drag_flag != 0 &&
1064
0
          (type == KEYC_TYPE_MOUSEDRAG ||
1065
0
          type == KEYC_TYPE_MOUSEUP)) {
1066
0
        modal_drag = 1;
1067
0
        wp = lwp;
1068
0
        loc = KEYC_MOUSE_LOCATION_PANE;
1069
0
        m->wp = wp->id;
1070
0
        m->w = wp->window->id;
1071
0
      } else {
1072
0
        server_client_update_scrollbar_hover(c, type,
1073
0
            -1, -1);
1074
0
        c->tty.mouse_drag_update = NULL;
1075
0
        c->tty.mouse_drag_release = NULL;
1076
0
        c->tty.mouse_drag_flag = 0;
1077
0
        c->tty.mouse_scrolling_flag = 0;
1078
0
        c->tty.mouse_slider_mpos = -1;
1079
0
        c->tty.mouse_last_pane = -1;
1080
0
        if ((w->modal->flags & PANE_CLOSEONCLICK) &&
1081
0
            (type == KEYC_TYPE_MOUSEDOWN ||
1082
0
            type == KEYC_TYPE_SECONDCLICK ||
1083
0
            type == KEYC_TYPE_TRIPLECLICK))
1084
0
          server_kill_pane(w->modal);
1085
0
        return (KEYC_UNKNOWN);
1086
0
      }
1087
0
    }
1088
0
    server_client_update_scrollbar_hover(c, type, px, py);
1089
1090
0
    if (modal_drag) {
1091
      /* Keep the drag with the modal pane. */
1092
0
    } else if (type == KEYC_TYPE_MOUSEDRAG && lwp != NULL) {
1093
      /* Use pane from last mouse event. */
1094
0
      wp = lwp;
1095
0
    } else {
1096
      /* Try inside the pane. */
1097
0
      wp = window_get_active_at(w, px, py);
1098
0
    }
1099
0
    if (wp == NULL) {
1100
0
      loc = KEYC_MOUSE_LOCATION_EMPTY;
1101
0
      m->w = w->id;
1102
0
      log_debug("mouse %u,%u on empty area", x, y);
1103
0
    } else {
1104
0
      if (!modal_drag) {
1105
0
        loc = server_client_check_mouse_in_pane(wp, px,
1106
0
            py, &sl_mpos);
1107
0
      }
1108
0
      if (loc == KEYC_MOUSE_LOCATION_PANE) {
1109
0
        log_debug("mouse %u,%u on pane %%%u", x, y,
1110
0
            wp->id);
1111
0
      } else if (loc == KEYC_MOUSE_LOCATION_BORDER) {
1112
0
        sr = window_pane_status_get_range(wp, px, py);
1113
0
        if (sr != NULL) {
1114
0
          n = sr->argument;
1115
0
          loc = KEYC_MOUSE_LOCATION_CONTROL0 + n;
1116
0
        }
1117
0
        log_debug("mouse on pane %%%u border", wp->id);
1118
0
      } else if (loc == KEYC_MOUSE_LOCATION_SCROLLBAR_UP ||
1119
0
          loc == KEYC_MOUSE_LOCATION_SCROLLBAR_SLIDER ||
1120
0
          loc == KEYC_MOUSE_LOCATION_SCROLLBAR_DOWN) {
1121
0
        log_debug("mouse on pane %%%u scrollbar",
1122
0
            wp->id);
1123
0
      }
1124
0
      m->wp = wp->id;
1125
0
      m->w = wp->window->id;
1126
0
    }
1127
0
  } else
1128
0
    server_client_update_scrollbar_hover(c, type, -1, -1);
1129
1130
  /* Reset click type or add a click timer if needed. */
1131
0
  if (type == KEYC_TYPE_MOUSEDOWN ||
1132
0
      type == KEYC_TYPE_SECONDCLICK ||
1133
0
      type == KEYC_TYPE_TRIPLECLICK) {
1134
0
    if (type != KEYC_TYPE_MOUSEDOWN &&
1135
0
        (m->b != c->click_button ||
1136
0
        loc != (enum key_code_mouse_location)c->click_loc ||
1137
0
        m->wp != c->click_wp)) {
1138
0
      type = KEYC_TYPE_MOUSEDOWN;
1139
0
      log_debug("click sequence reset at %u,%u", x, y);
1140
0
      c->flags &= ~CLIENT_TRIPLECLICK;
1141
0
      c->flags |= CLIENT_DOUBLECLICK;
1142
0
    }
1143
1144
0
    if (type != KEYC_TYPE_TRIPLECLICK && KEYC_CLICK_TIMEOUT != 0) {
1145
0
      memcpy(&c->click_event, m, sizeof c->click_event);
1146
0
      c->click_button = m->b;
1147
0
      c->click_loc = loc;
1148
0
      c->click_wp = m->wp;
1149
1150
0
      log_debug("click timer started");
1151
0
      tv.tv_sec = KEYC_CLICK_TIMEOUT / 1000;
1152
0
      tv.tv_usec = (KEYC_CLICK_TIMEOUT % 1000) * 1000L;
1153
0
      evtimer_add(&c->click_timer, &tv);
1154
0
    }
1155
0
  }
1156
1157
0
  key = KEYC_UNKNOWN;
1158
1159
  /* Stop dragging if needed. */
1160
0
  if (type != KEYC_TYPE_MOUSEDRAG &&
1161
0
      type != KEYC_TYPE_WHEELUP &&
1162
0
      type != KEYC_TYPE_WHEELDOWN &&
1163
0
      type != KEYC_TYPE_DOUBLECLICK &&
1164
0
      type != KEYC_TYPE_TRIPLECLICK &&
1165
0
      c->tty.mouse_drag_flag != 0) {
1166
0
    if (c->tty.mouse_drag_release != NULL)
1167
0
      c->tty.mouse_drag_release(c, m);
1168
1169
0
    c->tty.mouse_drag_update = NULL;
1170
0
    c->tty.mouse_drag_release = NULL;
1171
0
    c->tty.mouse_scrolling_flag = 0;
1172
1173
    /*
1174
     * End a mouse drag by passing a MouseDragEnd key corresponding
1175
     * to the button that started the drag.
1176
     */
1177
0
    type = KEYC_TYPE_MOUSEDRAGEND;
1178
0
    c->tty.mouse_drag_flag = 0;
1179
0
    c->tty.mouse_slider_mpos = -1;
1180
0
    c->tty.mouse_last_pane = -1;
1181
0
  }
1182
1183
  /* Convert to a key binding. */
1184
0
  if (type == KEYC_TYPE_MOUSEMOVE && loc == KEYC_MOUSE_LOCATION_PANE) {
1185
0
    key = KEYC_MOUSEMOVE_PANE;
1186
0
    if (wp != NULL &&
1187
0
        wp != w->active &&
1188
0
        options_get_number(s->options, "focus-follows-mouse")) {
1189
0
      window_redraw_active_switch(w, wp);
1190
0
      window_set_active_pane(w, wp, 1);
1191
0
      server_redraw_window_borders(w);
1192
0
      server_status_window(w);
1193
0
    }
1194
0
  }
1195
0
  if (type == KEYC_TYPE_MOUSEDRAG) {
1196
0
    if (c->tty.mouse_drag_update != NULL)
1197
0
      key = KEYC_DRAGGING;
1198
1199
    /*
1200
     * Begin a drag by setting the flag to a non-zero value that
1201
     * corresponds to the mouse button in use. If starting to drag
1202
     * the scrollbar, store the relative position in the slider
1203
     * where the user grabbed.
1204
     */
1205
0
    if (c->tty.mouse_drag_flag == 0) {
1206
0
      c->tty.mouse_drag_location = loc;
1207
0
      if (c->tty.mouse_drag_status) {
1208
0
        c->tty.mouse_drag_x = x;
1209
0
        c->tty.mouse_drag_y = y;
1210
0
      } else {
1211
0
        c->tty.mouse_drag_x = px;
1212
0
        c->tty.mouse_drag_y = py;
1213
0
      }
1214
0
    }
1215
0
    c->tty.mouse_drag_flag = MOUSE_BUTTONS(b) + 1;
1216
1217
    /* Change the pane if the drag did not start on status line. */
1218
0
    if (!c->tty.mouse_drag_status && lwp == NULL) {
1219
0
      lwp = wp = window_get_active_at(w, px, py);
1220
0
      if (wp != NULL)
1221
0
        c->tty.mouse_last_pane = wp->id;
1222
0
    }
1223
1224
    /* Change scrollbar position if needed. */
1225
0
    if (c->tty.mouse_scrolling_flag == 0 &&
1226
0
        loc == KEYC_MOUSE_LOCATION_SCROLLBAR_SLIDER) {
1227
0
      c->tty.mouse_scrolling_flag = 1;
1228
0
      if (m->statusat == 0) {
1229
0
        c->tty.mouse_slider_mpos = sl_mpos +
1230
0
            m->statuslines;
1231
0
      } else
1232
0
        c->tty.mouse_slider_mpos = sl_mpos;
1233
0
    }
1234
0
  }
1235
1236
0
  if (key == KEYC_UNKNOWN) {
1237
    /* Adjust the button number. */
1238
0
    if (type == KEYC_TYPE_MOUSEMOVE)
1239
0
      bn = 0;
1240
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_1)
1241
0
      bn = 1;
1242
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_2)
1243
0
      bn = 2;
1244
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_3)
1245
0
      bn = 3;
1246
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_6)
1247
0
      bn = 6;
1248
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_7)
1249
0
      bn = 7;
1250
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_8)
1251
0
      bn = 8;
1252
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_9)
1253
0
      bn = 9;
1254
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_10)
1255
0
      bn = 10;
1256
0
    else if (MOUSE_BUTTONS(b) == MOUSE_BUTTON_11)
1257
0
      bn = 11;
1258
0
    else
1259
0
      bn = 0;
1260
0
    key = KEYC_MAKE_MOUSE_KEY(type, bn, loc);
1261
0
  }
1262
1263
  /* Apply modifiers if any. */
1264
0
  if (b & MOUSE_MASK_META)
1265
0
    key |= KEYC_META;
1266
0
  if (b & MOUSE_MASK_CTRL)
1267
0
    key |= KEYC_CTRL;
1268
0
  if (b & MOUSE_MASK_SHIFT)
1269
0
    key |= KEYC_SHIFT;
1270
1271
0
  if (log_get_level() != 0)
1272
0
    log_debug("mouse key is %s", key_string_lookup_key (key, 1));
1273
0
  return (key);
1274
0
}
1275
1276
/* Update client theme colours from server options. */
1277
void
1278
server_client_update_theme_colours(struct client *c)
1279
0
{
1280
0
  struct format_tree  *ft;
1281
0
  const char    *name, *value;
1282
0
  enum client_theme  theme;
1283
0
  char      *expanded;
1284
0
  u_int      i;
1285
0
  int      colour, option;
1286
1287
0
  if (c == NULL)
1288
0
    return;
1289
1290
0
  option = options_get_number(global_options, "theme");
1291
0
  if (option == 1) {
1292
0
    for (i = 0; i < COLOUR_THEME_COUNT; i++)
1293
0
      c->theme_colours[i] = colour_theme_terminal_colour(i);
1294
0
    return;
1295
0
  }
1296
1297
0
  ft = format_create(c, NULL, FORMAT_NONE, FORMAT_NOJOBS);
1298
0
  format_defaults(ft, c, NULL, NULL, NULL);
1299
1300
0
  theme = c->theme;
1301
0
  if (theme == THEME_UNKNOWN)
1302
0
    theme = colour_totheme(c->tty.bg);
1303
0
  if (option == 2)
1304
0
    theme = THEME_LIGHT;
1305
0
  else if (option == 3)
1306
0
    theme = THEME_DARK;
1307
0
  for (i = 0; i < COLOUR_THEME_COUNT; i++) {
1308
0
    c->theme_colours[i] = 8;
1309
0
    name = colour_theme_option(i, theme);
1310
0
    if (name == NULL)
1311
0
      continue;
1312
0
    value = options_get_string(global_options, name);
1313
0
    expanded = format_expand(ft, value);
1314
0
    colour = colour_fromstring(expanded);
1315
0
    free(expanded);
1316
0
    if (colour == -1 || (colour & COLOUR_FLAG_THEME))
1317
0
      continue;
1318
0
    c->theme_colours[i] = colour;
1319
0
  }
1320
1321
0
  format_free(ft);
1322
0
}
1323
1324
/* Is this a bracket paste key? */
1325
static int
1326
server_client_is_bracket_paste(struct client *c, key_code key)
1327
0
{
1328
0
  if ((key & KEYC_MASK_KEY) == KEYC_PASTE_START) {
1329
0
    c->flags |= CLIENT_BRACKETPASTING;
1330
0
    c->paste_time = current_time;
1331
0
    log_debug("%s: bracket paste on", c->name);
1332
0
    return (0);
1333
0
  }
1334
1335
0
  if ((key & KEYC_MASK_KEY) == KEYC_PASTE_END) {
1336
0
    c->flags &= ~CLIENT_BRACKETPASTING;
1337
0
    log_debug("%s: bracket paste off", c->name);
1338
0
    return (0);
1339
0
  }
1340
1341
0
  return !!(c->flags & CLIENT_BRACKETPASTING);
1342
0
}
1343
1344
/* Is this fast enough to probably be a paste? */
1345
static int
1346
server_client_is_assume_paste(struct client *c)
1347
0
{
1348
0
  struct session  *s = c->session;
1349
0
  struct timeval   tv;
1350
0
  int    t;
1351
1352
0
  if (c->flags & CLIENT_BRACKETPASTING)
1353
0
    return (0);
1354
0
  if ((t = options_get_number(s->options, "assume-paste-time")) == 0)
1355
0
    return (0);
1356
0
  if (tty_term_has(c->tty.term, TTYC_ENBP))
1357
0
    return (0);
1358
1359
0
  timersub(&c->activity_time, &c->last_activity_time, &tv);
1360
0
  if (tv.tv_sec == 0 && tv.tv_usec < t * 1000) {
1361
0
    if (c->flags & CLIENT_ASSUMEPASTING)
1362
0
      return (1);
1363
0
    c->flags |= CLIENT_ASSUMEPASTING;
1364
0
    c->paste_time = current_time;
1365
0
    log_debug("%s: assume paste on", c->name);
1366
0
    return (0);
1367
0
  }
1368
0
  if (c->flags & CLIENT_ASSUMEPASTING) {
1369
0
    c->flags &= ~CLIENT_ASSUMEPASTING;
1370
0
    log_debug("%s: assume paste off", c->name);
1371
0
  }
1372
0
  return (0);
1373
0
}
1374
1375
/* Has the latest client changed? */
1376
static void
1377
server_client_update_latest(struct client *c)
1378
0
{
1379
0
  struct window *w;
1380
1381
0
  if (c->session == NULL)
1382
0
    return;
1383
0
  w = c->session->curw->window;
1384
1385
0
  if (w->latest == c)
1386
0
    return;
1387
0
  w->latest = c;
1388
1389
0
  if (options_get_number(w->options, "window-size") == WINDOW_SIZE_LATEST)
1390
0
    recalculate_size(w, 0);
1391
1392
0
  events_fire_client("client-active", c);
1393
0
}
1394
1395
/* Get repeat time. */
1396
static u_int
1397
server_client_repeat_time(struct client *c, struct key_binding *bd)
1398
0
{
1399
0
  struct session  *s = c->session;
1400
0
  u_int    repeat, initial;
1401
1402
0
  if (~bd->flags & KEY_BINDING_REPEAT)
1403
0
    return (0);
1404
0
  repeat = options_get_number(s->options, "repeat-time");
1405
0
  if (repeat == 0)
1406
0
    return (0);
1407
0
  if ((~c->flags & CLIENT_REPEAT) || bd->key != c->last_key) {
1408
0
    initial = options_get_number(s->options, "initial-repeat-time");
1409
0
    if (initial != 0)
1410
0
      repeat = initial;
1411
0
  }
1412
0
  return (repeat);
1413
0
}
1414
1415
/* Handle a key press which closes a dead pane. */
1416
static int
1417
server_client_handle_dead_key(struct window_pane *wp, key_code key)
1418
0
{
1419
0
  int remain_on_exit;
1420
1421
0
  if (wp == NULL ||
1422
0
      (~wp->flags & PANE_EXITED) ||
1423
0
      KEYC_IS_MOUSE(key) ||
1424
0
      KEYC_IS_PASTE(key))
1425
0
    return (0);
1426
0
  remain_on_exit = options_get_number(wp->options, "remain-on-exit");
1427
0
  if (remain_on_exit != 3 && remain_on_exit != 4)
1428
0
    return (0);
1429
0
  options_set_number(wp->options, "remain-on-exit", 0);
1430
0
  server_destroy_pane(wp, 0);
1431
0
  return (1);
1432
0
}
1433
1434
/*
1435
 * Handle data key input from client. This owns and can modify the key event it
1436
 * is given and is responsible for freeing it.
1437
 */
1438
static enum cmd_retval
1439
server_client_key_callback(struct cmdq_item *item, void *data)
1440
0
{
1441
0
  struct key_event    *event = data;
1442
0
  struct client     *c, *ec = event->client;
1443
0
  key_code       key = event->key;
1444
0
  struct mouse_event    *m = &event->m;
1445
0
  struct session      *s;
1446
0
  struct winlink      *wl;
1447
0
  struct window_pane    *wp;
1448
0
  struct window_mode_entry  *wme;
1449
0
  struct timeval       tv;
1450
0
  struct key_table    *table, *first;
1451
0
  struct key_binding    *bd;
1452
0
  u_int        repeat;
1453
0
  uint64_t       flags, prefix_delay;
1454
0
  struct cmd_find_state    fs;
1455
0
  key_code       key0, prefix, prefix2;
1456
1457
0
  if (ec != NULL)
1458
0
    c = ec;
1459
0
  else
1460
0
    c = cmdq_get_client(item);
1461
0
  s = c->session;
1462
1463
  /* Check the client is good to accept input. */
1464
0
  if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
1465
0
    goto out;
1466
1467
  /* Recheck input handlers opened by earlier queued commands. */
1468
0
  if (server_client_handle_key0(c, event, NULL, NULL, 1) == 0)
1469
0
    goto out;
1470
1471
0
  wl = s->curw;
1472
1473
  /* Update the activity timer. */
1474
0
  memcpy(&c->last_activity_time, &c->activity_time,
1475
0
      sizeof c->last_activity_time);
1476
0
  if (gettimeofday(&c->activity_time, NULL) != 0)
1477
0
    fatal("gettimeofday failed");
1478
0
  session_update_activity(s, &c->activity_time);
1479
1480
  /* Check for mouse keys. */
1481
0
  m->valid = 0;
1482
0
  if (key == KEYC_MOUSE || key == KEYC_DOUBLECLICK) {
1483
0
    if (c->flags & CLIENT_READONLY)
1484
0
      goto out;
1485
0
    key = server_client_check_mouse(c, event);
1486
0
    if (key == KEYC_UNKNOWN)
1487
0
      goto out;
1488
1489
0
    m->valid = 1;
1490
0
    m->key = key;
1491
1492
    /*
1493
     * Synchronize direct drag output with the later damage redraw
1494
     * before invoking the drag callback.
1495
     */
1496
0
    if ((key & KEYC_MASK_KEY) == KEYC_DRAGGING) {
1497
0
      tty_sync_start(&c->tty);
1498
0
      c->tty.mouse_drag_update(c, m);
1499
0
      goto out;
1500
0
    }
1501
0
    event->key = key;
1502
0
  }
1503
1504
  /* Find affected pane. */
1505
0
  if (!KEYC_IS_MOUSE(key) || cmd_find_from_mouse(&fs, m, 0) != 0)
1506
0
    cmd_find_from_client(&fs, c, 0);
1507
0
  wp = fs.wp;
1508
1509
  /* Forward mouse keys if disabled. */
1510
0
  if (KEYC_IS_MOUSE(key) && !options_get_number(s->options, "mouse"))
1511
0
    goto forward_key;
1512
1513
  /* Forward if bracket pasting. */
1514
0
  if (server_client_is_bracket_paste (c, key))
1515
0
    goto paste_key;
1516
1517
  /* Treat everything as a regular key when pasting is detected. */
1518
0
  if (!KEYC_IS_MOUSE(key) &&
1519
0
      key != KEYC_FOCUS_IN &&
1520
0
      key != KEYC_FOCUS_OUT &&
1521
0
      (~key & KEYC_SENT) &&
1522
0
      server_client_is_assume_paste(c))
1523
0
    goto paste_key;
1524
1525
  /* Forward keys directly if this pane is capturing all keys. */
1526
0
  if (wp != NULL &&
1527
0
      (wp->flags & PANE_CAPTUREALLKEYS) &&
1528
0
      (~wp->flags & PANE_EXITED) &&
1529
0
      !KEYC_IS_MOUSE(key) &&
1530
0
      TAILQ_EMPTY(&wp->modes))
1531
0
    goto forward_key;
1532
1533
  /* Focus events are not keys and cannot be bound. */
1534
0
  if (key == KEYC_FOCUS_IN || key == KEYC_FOCUS_OUT)
1535
0
    goto forward_key;
1536
1537
  /*
1538
   * Work out the current key table. If the pane is in a mode, use
1539
   * the mode table instead of the default key table.
1540
   */
1541
0
  if (server_client_is_default_key_table(c, c->keytable) &&
1542
0
      wp != NULL &&
1543
0
      (wme = TAILQ_FIRST(&wp->modes)) != NULL &&
1544
0
      wme->mode->key_table != NULL)
1545
0
    table = key_bindings_get_table(wme->mode->key_table(wme), 1);
1546
0
  else
1547
0
    table = c->keytable;
1548
0
  first = table;
1549
1550
0
table_changed:
1551
  /*
1552
   * The prefix always takes precedence and forces a switch to the prefix
1553
   * table, unless we are already there.
1554
   */
1555
0
  prefix = (key_code)options_get_number(s->options, "prefix");
1556
0
  prefix2 = (key_code)options_get_number(s->options, "prefix2");
1557
0
  key0 = (key & (KEYC_MASK_KEY|KEYC_MASK_MODIFIERS));
1558
0
  if ((key0 == (prefix & (KEYC_MASK_KEY|KEYC_MASK_MODIFIERS)) ||
1559
0
      key0 == (prefix2 & (KEYC_MASK_KEY|KEYC_MASK_MODIFIERS))) &&
1560
0
      strcmp(table->name, "prefix") != 0) {
1561
0
    server_client_set_key_table(c, "prefix");
1562
0
    server_status_client(c);
1563
0
    goto out;
1564
0
  }
1565
0
  flags = c->flags;
1566
1567
0
try_again:
1568
  /* Log key table. */
1569
0
  if (wp == NULL)
1570
0
    log_debug("key table %s (no pane)", table->name);
1571
0
  else
1572
0
    log_debug("key table %s (pane %%%u)", table->name, wp->id);
1573
0
  if (c->flags & CLIENT_REPEAT)
1574
0
    log_debug("currently repeating");
1575
1576
0
  bd = key_bindings_get(table, key0);
1577
1578
  /*
1579
   * If prefix-timeout is enabled and we're in the prefix table, see if
1580
   * the timeout has been exceeded. Revert to the root table if so.
1581
   */
1582
0
  prefix_delay = options_get_number(global_options, "prefix-timeout");
1583
0
  if (prefix_delay > 0 &&
1584
0
      strcmp(table->name, "prefix") == 0 &&
1585
0
      server_client_key_table_activity_diff(c) > prefix_delay) {
1586
    /*
1587
     * If repeating is active and this is a repeating binding,
1588
     * ignore the timeout.
1589
     */
1590
0
    if (bd != NULL &&
1591
0
        (c->flags & CLIENT_REPEAT) &&
1592
0
        (bd->flags & KEY_BINDING_REPEAT)) {
1593
0
      log_debug("prefix timeout ignored, repeat is active");
1594
0
    } else {
1595
0
      log_debug("prefix timeout exceeded");
1596
0
      server_client_set_key_table(c, NULL);
1597
0
      first = table = c->keytable;
1598
0
      server_status_client(c);
1599
0
      goto table_changed;
1600
0
    }
1601
0
  }
1602
1603
  /* Try to see if there is a key binding in the current table. */
1604
0
  if (bd != NULL) {
1605
    /*
1606
     * Key was matched in this table. If currently repeating but a
1607
     * non-repeating binding was found, stop repeating and try
1608
     * again in the root table.
1609
     */
1610
0
    if ((c->flags & CLIENT_REPEAT) &&
1611
0
        (~bd->flags & KEY_BINDING_REPEAT)) {
1612
0
      log_debug("found in key table %s (not repeating)",
1613
0
          table->name);
1614
0
      server_client_set_key_table(c, NULL);
1615
0
      first = table = c->keytable;
1616
0
      c->flags &= ~CLIENT_REPEAT;
1617
0
      server_status_client(c);
1618
0
      goto table_changed;
1619
0
    }
1620
0
    log_debug("found in key table %s", table->name);
1621
1622
    /*
1623
     * Take a reference to this table to make sure the key binding
1624
     * doesn't disappear.
1625
     */
1626
0
    table->references++;
1627
1628
    /*
1629
     * If this is a repeating key, start the timer. Otherwise reset
1630
     * the client back to the root table.
1631
     */
1632
0
    repeat = server_client_repeat_time(c, bd);
1633
0
    if (repeat != 0) {
1634
0
      c->flags |= CLIENT_REPEAT;
1635
0
      c->last_key = bd->key;
1636
1637
0
      tv.tv_sec = repeat / 1000;
1638
0
      tv.tv_usec = (repeat % 1000) * 1000L;
1639
0
      evtimer_add(&c->repeat_timer, &tv);
1640
0
    } else {
1641
0
      c->flags &= ~CLIENT_REPEAT;
1642
0
      server_client_set_key_table(c, NULL);
1643
0
    }
1644
0
    server_status_client(c);
1645
1646
    /* Execute the key binding. */
1647
0
    key_bindings_dispatch(bd, item, c, event, &fs);
1648
0
    key_bindings_unref_table(table);
1649
0
    goto out;
1650
0
  }
1651
1652
  /*
1653
   * No match, try the ANY key.
1654
   */
1655
0
  if (key0 != KEYC_ANY) {
1656
0
    key0 = KEYC_ANY;
1657
0
    goto try_again;
1658
0
  }
1659
1660
  /*
1661
   * Binding movement keys is useless since we only turn them on when the
1662
   * application requests, so don't let them exit the prefix table.
1663
   */
1664
0
  if (KEYC_IS_TYPE(key, KEYC_TYPE_MOUSEMOVE))
1665
0
    goto forward_key;
1666
1667
  /*
1668
   * No match in this table. If not in the root table or if repeating
1669
   * switch the client back to the root table and try again.
1670
   */
1671
0
  log_debug("not found in key table %s", table->name);
1672
0
  if (!server_client_is_default_key_table(c, table) ||
1673
0
      (c->flags & CLIENT_REPEAT)) {
1674
0
    log_debug("trying in root table");
1675
0
    server_client_set_key_table(c, NULL);
1676
0
    table = c->keytable;
1677
0
    if (c->flags & CLIENT_REPEAT)
1678
0
      first = table;
1679
0
    c->flags &= ~CLIENT_REPEAT;
1680
0
    server_status_client(c);
1681
0
    goto table_changed;
1682
0
  }
1683
1684
  /*
1685
   * No match in the root table either. If this wasn't the first table
1686
   * tried, don't pass the key to the pane.
1687
   */
1688
0
  if (first != table && (~flags & CLIENT_REPEAT)) {
1689
0
    server_client_set_key_table(c, NULL);
1690
0
    server_status_client(c);
1691
0
    goto out;
1692
0
  }
1693
1694
0
forward_key:
1695
0
  if (server_client_handle_dead_key(wp, key))
1696
0
    goto out;
1697
0
  if (c->flags & CLIENT_READONLY)
1698
0
    goto out;
1699
0
  if (wp != NULL)
1700
0
    window_pane_key(wp, c, s, wl, key, m);
1701
0
  goto out;
1702
1703
0
paste_key:
1704
0
  if (c->flags & CLIENT_READONLY)
1705
0
    goto out;
1706
0
  if (event->buf != NULL)
1707
0
    window_pane_paste(wp, key, event->buf, event->len);
1708
0
  key = KEYC_NONE;
1709
0
  goto out;
1710
1711
0
out:
1712
0
  if (s != NULL && key != KEYC_FOCUS_OUT)
1713
0
    server_client_update_latest(c);
1714
0
  if (ec != NULL)
1715
0
    server_client_unref(ec);
1716
0
  free(event->buf);
1717
0
  free(event);
1718
0
  return (CMD_RETURN_NORMAL);
1719
0
}
1720
1721
/* Handle a key event for the active window menu, if any. */
1722
static int
1723
server_client_handle_menu_key(struct client *c, struct key_event *event)
1724
0
{
1725
0
  struct window   *w = c->session->curw->window;
1726
0
  struct key_event   new_event;
1727
0
  struct mouse_event  *m;
1728
0
  u_int      ox, oy, sx, sy;
1729
1730
0
  if (w->menu == NULL)
1731
0
    return (0);
1732
1733
0
  memcpy(&new_event, event, sizeof new_event);
1734
0
  if (KEYC_IS_MOUSE(event->key)) {
1735
0
    m = &new_event.m;
1736
0
    m->statusat = status_at_line(c);
1737
0
    m->statuslines = status_line_size(c);
1738
0
    m->sideat = status_side_at_column(c);
1739
0
    m->sidewidth = status_side_size(c);
1740
1741
0
    tty_window_offset(&c->tty, &ox, &oy, &sx, &sy);
1742
0
    if (m->sideat == 0 && m->x < m->sidewidth)
1743
0
      m->x = m->y = UINT_MAX;
1744
0
    else if (m->sideat > 0 && m->x >= (u_int)m->sideat)
1745
0
      m->x = m->y = UINT_MAX;
1746
0
    else {
1747
0
      if (m->sideat == 0)
1748
0
        m->x -= m->sidewidth;
1749
0
      m->x += ox;
1750
0
      if (m->statusat == 0) {
1751
0
        if (m->y < m->statuslines)
1752
0
          m->x = m->y = UINT_MAX;
1753
0
        else
1754
0
          m->y = m->y - m->statuslines + oy;
1755
0
      } else if (m->statusat > 0 &&
1756
0
          m->y >= (u_int)m->statusat)
1757
0
        m->x = m->y = UINT_MAX;
1758
0
      else
1759
0
        m->y += oy;
1760
0
    }
1761
0
  }
1762
1763
0
  if (menu_key(c, w->menu, &new_event) == 1)
1764
0
    menu_close(w);
1765
0
  return (1);
1766
0
}
1767
1768
/* Handle a key; check skips queueing. Returns 0 if used, 1 otherwise. */
1769
static int
1770
server_client_handle_key0(struct client *c, struct key_event *event,
1771
    struct cmdq_item *after, struct cmdq_item **next, int check)
1772
0
{
1773
0
  struct session    *s = c->session;
1774
0
  struct mouse_event  *m = &event->m;
1775
0
  struct cmdq_item  *item;
1776
0
  struct window_pane  *wp;
1777
0
  key_code     key;
1778
0
  enum key_event_delivery  d = event->delivered;
1779
1780
  /* A consumed key only needs to be freed by the callback. */
1781
0
  if (check && d == KEY_EVENT_CONSUMED)
1782
0
    return (0);
1783
1784
  /* Check the client is good to accept input. */
1785
0
  if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
1786
0
    return (0);
1787
1788
0
  if (event->key == KEYC_REPORT_LIGHT_THEME) {
1789
0
    server_client_report_theme(c, THEME_LIGHT);
1790
0
    return (0);
1791
0
  }
1792
0
  if (event->key == KEYC_REPORT_DARK_THEME) {
1793
0
    server_client_report_theme(c, THEME_DARK);
1794
0
    return (0);
1795
0
  }
1796
1797
  /*
1798
   * Dead panes waiting for a key, modal cancel keys, panes capturing all
1799
   * keys and the command prompt are special cases. The queue might be
1800
   * blocked so they need to be processed immediately rather than queued.
1801
   */
1802
0
  if (~c->flags & CLIENT_READONLY) {
1803
0
    if (c->message_string != NULL) {
1804
0
      if (c->message_ignore_keys)
1805
0
        return (0);
1806
0
      status_message_clear(c);
1807
0
    }
1808
1809
0
    wp = s->curw->window->active;
1810
0
    if (server_client_handle_dead_key(wp, event->key))
1811
0
      return (0);
1812
0
    if (wp != NULL &&
1813
0
        wp == wp->window->modal &&
1814
0
        (wp->flags & PANE_CLOSEONCANCEL) &&
1815
0
        (event->key == '\033' || event->key == ('c'|KEYC_CTRL))) {
1816
0
      server_kill_pane(wp);
1817
0
      return (0);
1818
0
    }
1819
0
    if (wp != NULL &&
1820
0
        (wp->flags & PANE_CAPTUREALLKEYS) &&
1821
0
        (~wp->flags & PANE_EXITED) &&
1822
0
        TAILQ_EMPTY(&wp->modes) &&
1823
0
        (!KEYC_IS_MOUSE(event->key) || wp->wait_item != NULL)) {
1824
0
      key = event->key;
1825
0
      if (KEYC_IS_MOUSE(key)) {
1826
0
        key = server_client_check_mouse(c, event);
1827
0
        if (key == KEYC_UNKNOWN ||
1828
0
            (u_int)m->wp != wp->id)
1829
0
          return (0);
1830
0
        m->valid = 1;
1831
0
        m->key = key;
1832
0
      }
1833
0
      window_pane_key(wp, c, s, s->curw, key, m);
1834
0
      return (0);
1835
0
    }
1836
1837
0
    if (server_client_handle_menu_key(c, event))
1838
0
      return (0);
1839
0
    if (d == KEY_EVENT_NOT_OFFERED && c->prompt != NULL) {
1840
0
      switch (status_prompt_key(c, event->key, &event->m)) {
1841
0
      case PROMPT_KEY_HANDLED:
1842
0
      case PROMPT_KEY_CLOSE:
1843
0
        return (0);
1844
0
      case PROMPT_KEY_NOT_HANDLED:
1845
0
      case PROMPT_KEY_MOVE:
1846
0
        break;
1847
0
      }
1848
0
    }
1849
1850
0
    wp = s->curw->window->active;
1851
0
    if (wp == NULL || !window_pane_has_prompt(wp)) {
1852
0
      TAILQ_FOREACH(wp, &s->curw->window->panes, entry) {
1853
0
        if (window_pane_has_prompt(wp) &&
1854
0
            window_pane_is_visible(wp))
1855
0
          break;
1856
0
      }
1857
0
    }
1858
0
    if (d == KEY_EVENT_NOT_OFFERED &&
1859
0
        wp != NULL &&
1860
0
        window_pane_has_prompt(wp) &&
1861
0
        window_pane_is_visible(wp)) {
1862
0
      switch (window_pane_prompt_key(wp, c, event->key,
1863
0
          &event->m)) {
1864
0
      case PROMPT_KEY_HANDLED:
1865
0
      case PROMPT_KEY_CLOSE:
1866
0
      case PROMPT_KEY_MOVE:
1867
0
        return (0);
1868
0
      case PROMPT_KEY_NOT_HANDLED:
1869
0
        if (KEYC_IS_MOUSE(event->key))
1870
0
          return (0);
1871
0
        break;
1872
0
      }
1873
0
    }
1874
0
  }
1875
0
  if (check)
1876
0
    return (1);
1877
1878
  /*
1879
   * Queue after earlier commands. Mark injected keys too, so waiting
1880
   * prompts can consume them.
1881
   */
1882
0
  item = cmdq_get_callback(server_client_key_callback, event);
1883
0
  cmdq_add_flags(item, CMDQ_KEY);
1884
0
  if (after != NULL) {
1885
0
    event->client = c;
1886
0
    c->references++;
1887
0
    item = cmdq_insert_after(after, item);
1888
0
    if (next != NULL)
1889
0
      *next = item;
1890
0
    return (1);
1891
0
  }
1892
0
  cmdq_append(c, item);
1893
0
  return (1);
1894
0
}
1895
1896
/* Offer a queued key once. Returns 0 if used, 1 otherwise. */
1897
int
1898
server_client_key_prompt(struct cmdq_item *item, void *data)
1899
0
{
1900
0
  struct key_event  *event = data;
1901
0
  struct client   *c = event->client;
1902
0
  int      ret;
1903
1904
0
  if (event->delivered != KEY_EVENT_NOT_OFFERED) {
1905
0
    if (event->delivered == KEY_EVENT_CONSUMED)
1906
0
      return (0);
1907
0
    return (1);
1908
0
  }
1909
0
  if (c == NULL)
1910
0
    c = cmdq_get_client(item);
1911
0
  if (c == NULL)
1912
0
    return (1);
1913
0
  ret = server_client_handle_key0(c, event, NULL, NULL, 1);
1914
0
  if (ret == 0)
1915
0
    event->delivered = KEY_EVENT_CONSUMED;
1916
0
  else
1917
0
    event->delivered = KEY_EVENT_NOT_CONSUMED;
1918
0
  return (ret);
1919
0
}
1920
1921
/* Handle key and insert at end of queue. */
1922
int
1923
server_client_handle_key(struct client *c, struct key_event *event)
1924
0
{
1925
0
  return (server_client_handle_key0(c, event, NULL, NULL, 0));
1926
0
}
1927
1928
/* Handle key and insert after another item. */
1929
int
1930
server_client_handle_key_after(struct client *c, struct key_event *event,
1931
    struct cmdq_item *after, struct cmdq_item **next)
1932
0
{
1933
0
  return (server_client_handle_key0(c, event, after, next, 0));
1934
0
}
1935
1936
/* Client functions that need to happen every loop. */
1937
void
1938
server_client_loop(void)
1939
0
{
1940
0
  struct client     *c;
1941
0
  struct window     *w;
1942
0
  struct window_pane    *wp;
1943
0
  struct window_mode_entry  *wme;
1944
1945
  /* Check for window resize. This is done before redrawing. */
1946
0
  RB_FOREACH(w, windows, &windows)
1947
0
    server_client_check_window_resize(w);
1948
1949
  /* Notify modes that pane styles may have changed. */
1950
0
  RB_FOREACH(w, windows, &windows) {
1951
0
    TAILQ_FOREACH(wp, &w->panes, entry) {
1952
0
      if (wp->flags & PANE_STYLECHANGED) {
1953
0
        wme = TAILQ_FIRST(&wp->modes);
1954
0
        if (wme != NULL &&
1955
0
            wme->mode->style_changed != NULL)
1956
0
          wme->mode->style_changed(wme);
1957
0
      }
1958
0
    }
1959
0
  }
1960
1961
  /* Check clients. */
1962
0
  TAILQ_FOREACH(c, &clients, entry) {
1963
0
    server_client_check_exit(c, 0);
1964
0
    if (c->session != NULL && c->session->curw != NULL) {
1965
0
      server_client_check_modes(c);
1966
0
      server_client_check_redraw(c);
1967
0
      server_client_reset_state(c);
1968
0
    }
1969
0
  }
1970
1971
  /*
1972
   * Clear window redraw state after processing all clients. Deferred
1973
   * redraws are preserved in client flags.
1974
   */
1975
0
  RB_FOREACH(w, windows, &windows) {
1976
0
    TAILQ_FOREACH(wp, &w->panes, entry) {
1977
0
      if (wp->fd != -1) {
1978
0
        server_client_check_pane_resize(wp);
1979
0
        server_client_check_pane_buffer(wp);
1980
0
      }
1981
0
      wp->flags &= ~(PANE_REDRAW|PANE_REDRAWSCROLLBAR|
1982
0
          PANE_ACTIVITY);
1983
0
    }
1984
0
    redraw_free_damage(w);
1985
1986
0
    check_window_name(w);
1987
0
  }
1988
1989
  /* Send theme updates. */
1990
0
  RB_FOREACH(w, windows, &windows) {
1991
0
    TAILQ_FOREACH(wp, &w->panes, entry)
1992
0
      window_pane_send_theme_update(wp);
1993
0
  }
1994
0
}
1995
1996
/* Check if window needs to be resized. */
1997
static void
1998
server_client_check_window_resize(struct window *w)
1999
0
{
2000
0
  struct winlink  *wl;
2001
2002
0
  if (~w->flags & WINDOW_RESIZE)
2003
0
    return;
2004
2005
0
  TAILQ_FOREACH(wl, &w->winlinks, wentry) {
2006
0
    if (wl->session->attached != 0 && wl->session->curw == wl)
2007
0
      break;
2008
0
  }
2009
0
  if (wl == NULL)
2010
0
    return;
2011
2012
0
  log_debug("%s: resizing window @%u", __func__, w->id);
2013
0
  resize_window(w, w->new_sx, w->new_sy, w->new_xpixel, w->new_ypixel);
2014
0
}
2015
2016
/* Resize timer event. */
2017
static void
2018
server_client_resize_timer(__unused int fd, __unused short events, void *data)
2019
0
{
2020
0
  struct window_pane  *wp = data;
2021
2022
0
  log_debug("%s: %%%u resize timer expired", __func__, wp->id);
2023
0
  evtimer_del(&wp->resize_timer);
2024
0
}
2025
2026
/* Check if pane should be resized. */
2027
static void
2028
server_client_check_pane_resize(struct window_pane *wp)
2029
0
{
2030
0
  struct window_pane_resize *r, *first, *last;
2031
0
  struct timeval       tv = { .tv_usec = 250000 };
2032
2033
0
  if (TAILQ_EMPTY(&wp->resize_queue))
2034
0
    return;
2035
2036
0
  if (!event_initialized(&wp->resize_timer))
2037
0
    evtimer_set(&wp->resize_timer, server_client_resize_timer, wp);
2038
0
  if (evtimer_pending(&wp->resize_timer, NULL))
2039
0
    return;
2040
2041
0
  log_debug("%s: %%%u needs to be resized", __func__, wp->id);
2042
0
  TAILQ_FOREACH(r, &wp->resize_queue, entry) {
2043
0
    log_debug("queued resize: %ux%u -> %ux%u", r->osx, r->osy,
2044
0
        r->sx, r->sy);
2045
0
  }
2046
2047
  /*
2048
   * There are three cases that matter:
2049
   *
2050
   * - Only one resize. It can just be applied.
2051
   *
2052
   * - Multiple resizes and the ending size is different from the
2053
   *   starting size. We can discard all resizes except the most recent.
2054
   *
2055
   * - Multiple resizes and the ending size is the same as the starting
2056
   *   size. We must resize at least twice to force the application to
2057
   *   redraw. So apply the first and leave the last on the queue for
2058
   *   next time.
2059
   */
2060
0
  first = TAILQ_FIRST(&wp->resize_queue);
2061
0
  last = TAILQ_LAST(&wp->resize_queue, window_pane_resizes);
2062
0
  if (first == last) {
2063
    /* Only one resize. */
2064
0
    window_pane_send_resize(wp, first->sx, first->sy);
2065
0
    TAILQ_REMOVE(&wp->resize_queue, first, entry);
2066
0
    free(first);
2067
0
  } else if (last->sx != first->osx || last->sy != first->osy) {
2068
    /* Multiple resizes ending up with a different size. */
2069
0
    window_pane_send_resize(wp, last->sx, last->sy);
2070
0
    window_pane_clear_resizes(wp, NULL);
2071
0
  } else {
2072
    /*
2073
     * Multiple resizes ending up with the same size. There will
2074
     * not be more than one to the same size in succession so we
2075
     * can just use the last-but-one on the list and leave the last
2076
     * for later. We reduce the time until the next check to avoid
2077
     * a long delay between the resizes.
2078
     */
2079
0
    r = TAILQ_PREV(last, window_pane_resizes, entry);
2080
0
    window_pane_send_resize(wp, r->sx, r->sy);
2081
0
    window_pane_clear_resizes(wp, last);
2082
0
    tv.tv_usec = 10000;
2083
0
  }
2084
0
  evtimer_add(&wp->resize_timer, &tv);
2085
0
}
2086
2087
/* Check pane buffer size. */
2088
static void
2089
server_client_check_pane_buffer(struct window_pane *wp)
2090
0
{
2091
0
  struct evbuffer     *evb = wp->event->input;
2092
0
  size_t         minimum;
2093
0
  struct client     *c;
2094
0
  struct window_pane_offset *wpo;
2095
0
  int        off = 1, flag;
2096
0
  u_int        attached_clients = 0;
2097
0
  size_t         new_size;
2098
2099
  /*
2100
   * Work out the minimum used size. This is the most that can be removed
2101
   * from the buffer.
2102
   */
2103
0
  minimum = wp->offset.used;
2104
0
  if (wp->pipe_fd != -1 && wp->pipe_offset.used < minimum)
2105
0
    minimum = wp->pipe_offset.used;
2106
0
  TAILQ_FOREACH(c, &clients, entry) {
2107
0
    if (c->session == NULL)
2108
0
      continue;
2109
0
    attached_clients++;
2110
2111
0
    if (~c->flags & CLIENT_CONTROL) {
2112
0
      off = 0;
2113
0
      continue;
2114
0
    }
2115
0
    wpo = control_pane_offset(c, wp, &flag);
2116
0
    if (wpo == NULL) {
2117
0
      if (!flag)
2118
0
        off = 0;
2119
0
      continue;
2120
0
    }
2121
0
    if (!flag)
2122
0
      off = 0;
2123
2124
0
    window_pane_get_new_data(wp, wpo, &new_size);
2125
0
    log_debug("%s: %s has %zu bytes used and %zu left for %%%u",
2126
0
        __func__, c->name, wpo->used - wp->base_offset, new_size,
2127
0
        wp->id);
2128
0
    if (wpo->used < minimum)
2129
0
      minimum = wpo->used;
2130
0
  }
2131
0
  if (attached_clients == 0)
2132
0
    off = 0;
2133
0
  minimum -= wp->base_offset;
2134
0
  if (minimum == 0)
2135
0
    goto out;
2136
2137
  /* Drain the buffer. */
2138
0
  log_debug("%s: %%%u has %zu minimum (of %zu) bytes used", __func__,
2139
0
      wp->id, minimum, EVBUFFER_LENGTH(evb));
2140
0
  evbuffer_drain(evb, minimum);
2141
2142
  /*
2143
   * Adjust the base offset. If it would roll over, all the offsets into
2144
   * the buffer need to be adjusted.
2145
   */
2146
0
  if (wp->base_offset > SIZE_MAX - minimum) {
2147
0
    log_debug("%s: %%%u base offset has wrapped", __func__, wp->id);
2148
0
    wp->offset.used -= wp->base_offset;
2149
0
    if (wp->pipe_fd != -1)
2150
0
      wp->pipe_offset.used -= wp->base_offset;
2151
0
    TAILQ_FOREACH(c, &clients, entry) {
2152
0
      if (c->session == NULL || (~c->flags & CLIENT_CONTROL))
2153
0
        continue;
2154
0
      wpo = control_pane_offset(c, wp, &flag);
2155
0
      if (wpo != NULL && !flag)
2156
0
        wpo->used -= wp->base_offset;
2157
0
    }
2158
0
    wp->base_offset = minimum;
2159
0
  } else
2160
0
    wp->base_offset += minimum;
2161
2162
0
out:
2163
  /*
2164
   * If there is data remaining, and there are no clients able to consume
2165
   * it, do not read any more. This is true when there are attached
2166
   * clients, all of which are control clients which are not able to
2167
   * accept any more data.
2168
   */
2169
0
  log_debug("%s: pane %%%u is %s", __func__, wp->id, off ? "off" : "on");
2170
0
  if (off)
2171
0
    bufferevent_disable(wp->event, EV_READ);
2172
0
  else
2173
0
    bufferevent_enable(wp->event, EV_READ);
2174
0
}
2175
2176
/* Move cursor for pane prompt. */
2177
static int
2178
server_client_prompt_cursor(struct client *c, struct window_pane *wp, int *mode,
2179
    u_int *cx, u_int *cy)
2180
0
{
2181
0
  struct tty    *tty = &c->tty;
2182
0
  struct visible_ranges *r;
2183
0
  u_int      ox, oy, sx, sy;
2184
0
  int      px, py;
2185
2186
0
  if (!window_pane_has_prompt(wp))
2187
0
    return (0);
2188
0
  *mode &= ~MODE_CURSOR;
2189
2190
0
  tty_window_offset(tty, &ox, &oy, &sx, &sy);
2191
0
  if (status_at_line(c) == 0)
2192
0
    py = wp->yoff;
2193
0
  else
2194
0
    py = wp->yoff + wp->sy - 1;
2195
0
  px = wp->xoff + wp->prompt_cx;
2196
0
  if (px < (int)ox || px > (int)(ox + sx) ||
2197
0
      py < (int)oy || py > (int)(oy + sy))
2198
0
    return (1);
2199
2200
0
  *cx = px - ox;
2201
0
  *cy = py - oy;
2202
2203
0
  r = window_visible_ranges(wp, *cx, *cy, 1, NULL);
2204
0
  if (window_position_is_visible(r, *cx)) {
2205
0
    if (status_at_line(c) == 0)
2206
0
      *cy += status_line_size(c);
2207
0
    if (status_side_at_column(c) == 0)
2208
0
      *cx += status_side_size(c);
2209
0
    *mode |= MODE_CURSOR;
2210
0
  }
2211
0
  return (1);
2212
0
}
2213
2214
/*
2215
 * Update cursor position and mode settings. The scroll region and attributes
2216
 * are cleared when idle (waiting for an event) as this is the most likely time
2217
 * a user may interrupt tmux, for example with ~^Z in ssh(1). This is a
2218
 * compromise between excessive resets and likelihood of an interrupt.
2219
 *
2220
 * tty_region/tty_reset/tty_update_mode already take care of not resetting
2221
 * things that are already in their default state.
2222
 */
2223
static void
2224
server_client_reset_state(struct client *c)
2225
0
{
2226
0
  struct tty    *tty = &c->tty;
2227
0
  struct window   *w = c->session->curw->window;
2228
0
  struct window_pane  *wp = w->active, *loop;
2229
0
  struct screen   *s = NULL;
2230
0
  struct options    *oo = c->session->options;
2231
0
  int      mode = 0, cursor, flags, pane_mode = 0;
2232
0
  u_int      cx = 0, cy = 0, ox, oy, sx, sy, prompt = 0;
2233
0
  u_int      sb_w;
2234
0
  struct visible_ranges *r;
2235
2236
0
  if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
2237
0
    return;
2238
2239
  /* Disable the block flag. */
2240
0
  flags = (tty->flags & TTY_BLOCK);
2241
0
  tty->flags &= ~TTY_BLOCK;
2242
2243
  /* Get mode from the menu if any, else from the screen. */
2244
0
  if (w->menu != NULL) {
2245
0
    menu_get_cursor(w->menu, &cx, &cy);
2246
0
    s = menu_screen(w->menu);
2247
0
  } else if (wp != NULL && c->prompt == NULL)
2248
0
    s = wp->screen;
2249
0
  else
2250
0
    s = c->status.active;
2251
0
  if (s != NULL)
2252
0
    mode = s->mode;
2253
0
  if (log_get_level() != 0) {
2254
0
    log_debug("%s: client %s mode %s", __func__, c->name,
2255
0
        screen_mode_to_string(mode));
2256
0
  }
2257
2258
  /* Reset region and margin. */
2259
0
  tty_region_off(tty);
2260
0
  tty_margin_off(tty);
2261
2262
  /* Move cursor to pane cursor and offset. */
2263
0
  if (c->prompt != NULL) {
2264
0
    prompt = 1;
2265
0
    status_prompt_cursor(c, &cx, &cy);
2266
0
  } else if (wp != NULL) {
2267
0
    if (w->menu != NULL) {
2268
0
      tty_window_offset(tty, &ox, &oy, &sx, &sy);
2269
0
      if (cx < ox || cx >= ox + sx ||
2270
0
          cy < oy || cy >= oy + sy)
2271
0
        mode &= ~MODE_CURSOR;
2272
0
      else {
2273
0
        cx -= ox;
2274
0
        cy -= oy;
2275
0
        if (status_at_line(c) == 0)
2276
0
          cy += status_line_size(c);
2277
0
        if (status_side_at_column(c) == 0)
2278
0
          cx += status_side_size(c);
2279
0
      }
2280
0
      prompt = 1;
2281
0
    } else {
2282
0
      prompt = server_client_prompt_cursor(c, wp, &mode, &cx,
2283
0
          &cy);
2284
0
    }
2285
0
    if (!prompt) {
2286
0
      cursor = 0;
2287
0
      pane_mode = s->mode;
2288
2289
0
      tty_window_offset(tty, &ox, &oy, &sx, &sy);
2290
0
      if (wp->xoff + (int)s->cx >= (int)ox &&
2291
0
          wp->xoff + (int)s->cx <= (int)ox + (int)sx &&
2292
0
          wp->yoff + (int)s->cy >= (int)oy &&
2293
0
          wp->yoff + (int)s->cy <= (int)oy + (int)sy) {
2294
0
        cursor = 1;
2295
2296
0
        cx = wp->xoff + (int)s->cx - (int)ox;
2297
0
        cy = wp->yoff + (int)s->cy - (int)oy;
2298
2299
0
        r = window_visible_ranges(wp, cx, cy, 1, NULL);
2300
0
        if (!window_position_is_visible(r, cx))
2301
0
          cursor = 0;
2302
2303
0
        if (window_pane_scrollbar_overlay_visible(wp)) {
2304
0
          sb_w = wp->scrollbar_style.width;
2305
0
          if (sb_w > wp->sx)
2306
0
            sb_w = wp->sx;
2307
0
          if (sb_w != 0 &&
2308
0
              w->sb_pos == PANE_SCROLLBARS_LEFT) {
2309
0
            if (s->cx < sb_w)
2310
0
              cursor = 0;
2311
0
          } else if (sb_w != 0 &&
2312
0
              s->cx >= wp->sx - sb_w)
2313
0
            cursor = 0;
2314
0
        }
2315
2316
0
        if (status_at_line(c) == 0)
2317
0
          cy += status_line_size(c);
2318
0
        if (status_side_at_column(c) == 0)
2319
0
          cx += status_side_size(c);
2320
0
      }
2321
2322
0
      if (!cursor)
2323
0
        mode &= ~MODE_CURSOR;
2324
0
    }
2325
0
  } else if (s == NULL)
2326
0
    mode &= ~MODE_CURSOR;
2327
0
  if (~pane_mode & MODE_SYNC) {
2328
0
    log_debug("%s: cursor to %u,%u", __func__, cx, cy);
2329
0
    tty_cursor(tty, cx, cy);
2330
0
  } else {
2331
0
    mode &= ~CURSOR_MODES;
2332
0
    mode |= tty->mode & CURSOR_MODES;
2333
0
    s = NULL;
2334
0
  }
2335
2336
  /*
2337
   * Set mouse mode if requested. To support dragging, always use button
2338
   * mode. For focus-follows-mouse, we need all-motion mode to receive
2339
   * movement events.
2340
   */
2341
0
  if (options_get_number(oo, "mouse")) {
2342
0
    if (w->menu == NULL) {
2343
0
      mode &= ~ALL_MOUSE_MODES;
2344
0
      TAILQ_FOREACH(loop, &w->panes, entry) {
2345
0
        if (loop->screen->mode & MODE_MOUSE_ALL)
2346
0
          mode |= MODE_MOUSE_ALL;
2347
0
      }
2348
0
    }
2349
0
    if (options_get_number(oo, "focus-follows-mouse") ||
2350
0
        w->sb == PANE_SCROLLBARS_MODAL ||
2351
0
        w->sb == PANE_SCROLLBARS_AUTOHIDE)
2352
0
      mode |= MODE_MOUSE_ALL;
2353
0
    else if (~mode & MODE_MOUSE_ALL)
2354
0
      mode |= MODE_MOUSE_BUTTON;
2355
0
  }
2356
2357
  /* Clear bracketed paste mode if at the prompt. */
2358
0
  if (prompt)
2359
0
    mode &= ~MODE_BRACKETPASTE;
2360
2361
  /* Set the terminal mode and reset attributes. */
2362
0
  tty_update_mode(tty, mode, s);
2363
0
  tty_reset(tty);
2364
2365
  /* All writing must be done, send a sync end (if it was started). */
2366
0
  tty_sync_end(tty);
2367
0
  tty->flags |= flags;
2368
0
}
2369
2370
/* Repeat time callback. */
2371
static void
2372
server_client_repeat_timer(__unused int fd, __unused short events, void *data)
2373
0
{
2374
0
  struct client *c = data;
2375
2376
0
  if (c->flags & CLIENT_REPEAT) {
2377
0
    server_client_set_key_table(c, NULL);
2378
0
    c->flags &= ~CLIENT_REPEAT;
2379
0
    server_status_client(c);
2380
0
  }
2381
0
}
2382
2383
/* Double-click callback. */
2384
static void
2385
server_client_click_timer(__unused int fd, __unused short events, void *data)
2386
0
{
2387
0
  struct client   *c = data;
2388
0
  struct key_event  *event;
2389
2390
0
  log_debug("click timer expired");
2391
2392
0
  if (c->flags & CLIENT_TRIPLECLICK) {
2393
    /*
2394
     * Waiting for a third click that hasn't happened, so this must
2395
     * have been a double click.
2396
     */
2397
0
    event = xcalloc(1, sizeof *event);
2398
0
    event->key = KEYC_DOUBLECLICK;
2399
0
    memcpy(&event->m, &c->click_event, sizeof event->m);
2400
0
    if (!server_client_handle_key(c, event)) {
2401
0
      free(event->buf);
2402
0
      free(event);
2403
0
    }
2404
0
  }
2405
0
  c->flags &= ~(CLIENT_DOUBLECLICK|CLIENT_TRIPLECLICK);
2406
0
}
2407
2408
/* Start client exit timer. */
2409
static void
2410
server_client_start_exit_timer(struct client *c)
2411
0
{
2412
0
  struct timeval  tv = { .tv_sec = 10 };
2413
2414
0
  if (!evtimer_pending(&c->exit_timer, NULL))
2415
0
    evtimer_add(&c->exit_timer, &tv);
2416
0
}
2417
2418
/* Exit timer has expired: stop waiting for the client. */
2419
static void
2420
server_client_exit_timer(__unused int fd, __unused short events, void *data)
2421
0
{
2422
0
  struct client *c = data;
2423
2424
0
  if (c->flags & (CLIENT_DEAD|CLIENT_SUSPENDED))
2425
0
    return;
2426
2427
0
  if (c->flags & CLIENT_EXITED) {
2428
0
    log_debug("%s: %s took too long to exit", __func__, c->name);
2429
0
    server_client_lost(c);
2430
0
  } else if (c->flags & CLIENT_EXIT) {
2431
0
    log_debug("%s: %s took too long to flush", __func__, c->name);
2432
0
    server_client_check_exit(c, 1);
2433
0
  }
2434
0
}
2435
2436
/* Check if client should be exited, abandoning buffered output if forced. */
2437
static void
2438
server_client_check_exit(struct client *c, int force)
2439
0
{
2440
0
  struct client_file  *cf;
2441
0
  const char    *name = c->exit_session;
2442
0
  char      *data;
2443
0
  size_t       size, msize;
2444
2445
0
  if (c->flags & (CLIENT_DEAD|CLIENT_EXITED))
2446
0
    return;
2447
0
  if (~c->flags & CLIENT_EXIT)
2448
0
    return;
2449
2450
0
  if ((c->flags & CLIENT_CONTROL) && c->control_state != NULL) {
2451
0
    if (force)
2452
0
      control_discard_all(c);
2453
0
    else {
2454
0
      control_discard(c);
2455
0
      if (!control_all_done(c)) {
2456
0
        server_client_start_exit_timer(c);
2457
0
        return;
2458
0
      }
2459
0
    }
2460
0
  }
2461
0
  if (!force) {
2462
0
    RB_FOREACH(cf, client_files, &c->files) {
2463
0
      if (EVBUFFER_LENGTH(cf->buffer) != 0) {
2464
0
        server_client_start_exit_timer(c);
2465
0
        return;
2466
0
      }
2467
0
    }
2468
0
  }
2469
0
  c->flags |= CLIENT_EXITED;
2470
2471
0
  evtimer_del(&c->exit_timer);
2472
0
  server_client_start_exit_timer(c);
2473
2474
0
  switch (c->exit_type) {
2475
0
  case CLIENT_EXIT_RETURN:
2476
0
    if (c->exit_message != NULL)
2477
0
      msize = strlen(c->exit_message) + 1;
2478
0
    else
2479
0
      msize = 0;
2480
0
    size = (sizeof c->retval) + msize;
2481
0
    data = xmalloc(size);
2482
0
    memcpy(data, &c->retval, sizeof c->retval);
2483
0
    if (c->exit_message != NULL)
2484
0
      memcpy(data + sizeof c->retval, c->exit_message, msize);
2485
0
    proc_send(c->peer, MSG_EXIT, -1, data, size);
2486
0
    free(data);
2487
0
    break;
2488
0
  case CLIENT_EXIT_SHUTDOWN:
2489
0
    proc_send(c->peer, MSG_SHUTDOWN, -1, NULL, 0);
2490
0
    break;
2491
0
  case CLIENT_EXIT_DETACH:
2492
0
    proc_send(c->peer, c->exit_msgtype, -1, name, strlen(name) + 1);
2493
0
    break;
2494
0
  }
2495
0
}
2496
2497
/* Redraw timer callback. */
2498
static void
2499
server_client_redraw_timer(__unused int fd, __unused short events,
2500
    __unused void *data)
2501
0
{
2502
0
  log_debug("redraw timer fired");
2503
0
}
2504
2505
/*
2506
 * Check if modes need to be updated. Only modes in the current window are
2507
 * updated and it is done when the status line is redrawn.
2508
 */
2509
static void
2510
server_client_check_modes(struct client *c)
2511
0
{
2512
0
  struct window     *w = c->session->curw->window;
2513
0
  struct window_pane    *wp;
2514
0
  struct window_mode_entry  *wme;
2515
2516
0
  if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
2517
0
    return;
2518
0
  if (~c->flags & CLIENT_REDRAWSTATUS)
2519
0
    return;
2520
0
  TAILQ_FOREACH(wp, &w->panes, entry) {
2521
0
    wme = TAILQ_FIRST(&wp->modes);
2522
0
    if (wme != NULL && wme->mode->update != NULL)
2523
0
      wme->mode->update(wme);
2524
0
  }
2525
0
}
2526
2527
/* Check if any panes need to be redrawn. */
2528
static int
2529
server_client_any_pane_redraw(struct client *c)
2530
0
{
2531
0
  struct session    *s = c->session;
2532
0
  struct window   *w = s->curw->window;
2533
0
  struct window_pane  *wp;
2534
2535
0
  if (c->flags & CLIENT_REDRAWWINDOW)
2536
0
    return (1);
2537
0
  if (!TAILQ_EMPTY(&w->damage))
2538
0
    return (1);
2539
0
  TAILQ_FOREACH(wp, &w->panes, entry) {
2540
0
    if (wp->flags & (PANE_REDRAW|PANE_REDRAWSCROLLBAR))
2541
0
      return (1);
2542
0
  }
2543
0
  return (0);
2544
0
}
2545
2546
/* Check for client redraws. */
2547
static void
2548
server_client_check_redraw(struct client *c)
2549
0
{
2550
0
  struct session    *s = c->session;
2551
0
  struct tty    *tty = &c->tty;
2552
0
  struct window   *w = s->curw->window;
2553
0
  struct window_pane  *wp;
2554
0
  int      needed, tflags, mode = tty->mode;
2555
0
  int      damaged = !TAILQ_EMPTY(&w->damage);
2556
0
  struct timeval     tv = { .tv_usec = 1000 };
2557
0
  static struct event  ev;
2558
0
  size_t       n;
2559
2560
0
  if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
2561
0
    return;
2562
0
  if (c->flags & CLIENT_ALLREDRAWFLAGS) {
2563
0
    log_debug("%s: redraw%s%s%s%s", c->name,
2564
0
        (c->flags & CLIENT_REDRAWWINDOW) ? " window" : "",
2565
0
        (c->flags & CLIENT_REDRAWSTATUS) ? " status" : "",
2566
0
        (c->flags & CLIENT_REDRAWBORDERS) ? " borders" : "",
2567
0
        (c->flags & CLIENT_REDRAWMENU) ? " menu" : "");
2568
0
  }
2569
2570
  /* Work out if a redraw is actually needed. */
2571
0
  needed = 0;
2572
0
  if (c->flags & (CLIENT_ALLREDRAWFLAGS|CLIENT_REDRAWSCROLLBARS))
2573
0
    needed = 1;
2574
0
  else if (server_client_any_pane_redraw(c))
2575
0
    needed = 1;
2576
0
  if (!needed) {
2577
0
    c->flags &= ~CLIENT_STATUSFORCE;
2578
0
    return;
2579
0
  }
2580
2581
  /* Ignore output queued within the current synchronized frame. */
2582
0
  n = EVBUFFER_LENGTH(tty->out);
2583
0
  if ((tty->flags & TTY_SYNCING) && n > tty->sync_offset)
2584
0
    n = tty->sync_offset;
2585
2586
  /* Defer until output drains, preserving damage in client flags. */
2587
0
  if (n != 0 || (tty->flags & TTY_BLOCK)) {
2588
0
    if (n != 0)
2589
0
      log_debug("%s: redraw deferred (%zu left)", c->name, n);
2590
0
    else
2591
0
      log_debug("%s: redraw deferred (blocked)", c->name);
2592
0
    if (!evtimer_initialized(&ev))
2593
0
      evtimer_set(&ev, server_client_redraw_timer, NULL);
2594
0
    if (!evtimer_pending(&ev, NULL)) {
2595
0
      log_debug("redraw timer started");
2596
0
      evtimer_add(&ev, &tv);
2597
0
    }
2598
0
    if (damaged) {
2599
0
      c->flags |= CLIENT_REDRAWWINDOW;
2600
0
      return;
2601
0
    }
2602
0
    TAILQ_FOREACH(wp, &w->panes, entry) {
2603
0
      if (wp->flags & PANE_REDRAW) {
2604
0
        c->flags |= CLIENT_REDRAWWINDOW;
2605
0
        break;
2606
0
      }
2607
0
      if (wp->flags & PANE_REDRAWSCROLLBAR)
2608
0
        c->flags |= CLIENT_REDRAWSCROLLBARS;
2609
0
    }
2610
0
    return;
2611
0
  }
2612
2613
  /* Unfreeze the tty and turn off the cursor. */
2614
0
  log_debug("%s: redraw needed", c->name);
2615
0
  tflags = tty->flags & (TTY_BLOCK|TTY_FREEZE|TTY_NOCURSOR);
2616
0
  tty->flags = (tty->flags & ~(TTY_BLOCK|TTY_FREEZE))|TTY_NOCURSOR;
2617
2618
  /*
2619
   * If not redrawing the entire window, check whether each pane needs to
2620
   * be redrawn.
2621
   */
2622
0
  if (~c->flags & CLIENT_REDRAWWINDOW) {
2623
0
    TAILQ_FOREACH(wp, &w->panes, entry) {
2624
0
      if (wp->flags & PANE_REDRAW) {
2625
0
        log_debug("%s: redraw pane %%%u", __func__,
2626
0
            wp->id);
2627
0
        redraw_pane(c, wp);
2628
0
      } else if ((wp->flags & PANE_REDRAWSCROLLBAR) ||
2629
0
          (c->flags & CLIENT_REDRAWSCROLLBARS)) {
2630
0
        log_debug("%s: redraw scrollbar %%%u", __func__,
2631
0
            wp->id);
2632
0
        redraw_pane_scrollbar(c, wp);
2633
0
      }
2634
0
    }
2635
2636
    /* Draw damage here if no client redraw flags will handle it. */
2637
0
    if (damaged && (c->flags & CLIENT_ALLREDRAWFLAGS) == 0)
2638
0
      redraw_client_damage(c);
2639
0
  }
2640
2641
  /*
2642
   * Set titles etc and do the redraw if there are redraw flags (and we
2643
   * aren't here just to redraw panes).
2644
   */
2645
0
  if (c->flags & CLIENT_ALLREDRAWFLAGS) {
2646
0
    if (options_get_number(s->options, "set-titles")) {
2647
0
      server_client_set_title(c);
2648
0
      server_client_set_path(c);
2649
0
    }
2650
0
    server_client_set_progress_bar(c);
2651
0
    redraw_screen(c);
2652
0
    redraw_client_damage(c);
2653
0
  }
2654
2655
  /* Put the tty back how it was. */
2656
0
  tty->flags = (tty->flags & ~TTY_NOCURSOR)|(tflags & TTY_NOCURSOR);
2657
0
  tty_update_mode(tty, mode, NULL);
2658
0
  tty->flags = (tty->flags & ~(TTY_BLOCK|TTY_FREEZE|TTY_NOCURSOR))|tflags;
2659
2660
  /*
2661
   * All the redraw flags can now be cleared. Also record how many bytes
2662
   * were written.
2663
   */
2664
0
  c->flags &= ~(CLIENT_ALLREDRAWFLAGS|CLIENT_REDRAWSCROLLBARS|
2665
0
      CLIENT_STATUSFORCE);
2666
0
  c->redraw = EVBUFFER_LENGTH(tty->out);
2667
0
  log_debug("%s: redraw added %zu bytes", c->name, c->redraw);
2668
0
}
2669
2670
/* Set client title. */
2671
static void
2672
server_client_set_title(struct client *c)
2673
0
{
2674
0
  struct session    *s = c->session;
2675
0
  const char    *template;
2676
0
  char      *title;
2677
0
  struct format_tree  *ft;
2678
2679
0
  template = options_get_string(s->options, "set-titles-string");
2680
2681
0
  ft = format_create(c, NULL, FORMAT_NONE, 0);
2682
0
  format_defaults(ft, c, NULL, NULL, NULL);
2683
2684
0
  title = format_expand_time(ft, template);
2685
0
  if (c->title == NULL || strcmp(title, c->title) != 0) {
2686
0
    free(c->title);
2687
0
    c->title = xstrdup(title);
2688
0
    tty_set_title(&c->tty, c->title);
2689
0
  }
2690
0
  free(title);
2691
2692
0
  format_free(ft);
2693
0
}
2694
2695
/* Set client path. */
2696
static void
2697
server_client_set_path(struct client *c)
2698
0
{
2699
0
  struct session  *s = c->session;
2700
0
  const char  *path;
2701
2702
0
  if (s->curw == NULL || s->curw->window->active == NULL)
2703
0
    return;
2704
0
  if (s->curw->window->active->base.path == NULL)
2705
0
    path = "";
2706
0
  else
2707
0
    path = s->curw->window->active->base.path;
2708
0
  if (c->path == NULL || strcmp(path, c->path) != 0) {
2709
0
    free(c->path);
2710
0
    c->path = xstrdup(path);
2711
0
    tty_set_path(&c->tty, c->path);
2712
0
  }
2713
0
}
2714
2715
/* Set client progress bar. */
2716
static void
2717
server_client_set_progress_bar(struct client *c)
2718
0
{
2719
0
  struct session    *s = c->session;
2720
0
  struct progress_bar *pane_pb;
2721
2722
0
  if (s->curw == NULL || s->curw->window->active == NULL)
2723
0
    return;
2724
0
  pane_pb = &s->curw->window->active->base.progress_bar;
2725
0
  if (pane_pb->state == c->progress_bar.state &&
2726
0
      pane_pb->progress == c->progress_bar.progress)
2727
0
    return;
2728
0
  memcpy(&c->progress_bar, pane_pb, sizeof c->progress_bar);
2729
0
  tty_set_progress_bar(&c->tty, &c->progress_bar);
2730
0
}
2731
2732
/* Dispatch message from client. */
2733
static void
2734
server_client_dispatch(struct imsg *imsg, void *arg)
2735
0
{
2736
0
  struct client *c = arg;
2737
0
  ssize_t    datalen;
2738
0
  struct session  *s;
2739
0
  u_int    old_sx, old_sy;
2740
2741
0
  if (c->flags & CLIENT_DEAD)
2742
0
    return;
2743
2744
0
  if (imsg == NULL) {
2745
0
    server_client_lost(c);
2746
0
    return;
2747
0
  }
2748
2749
0
  datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
2750
2751
0
  switch (imsg->hdr.type) {
2752
0
  case MSG_IDENTIFY_CLIENTPID:
2753
0
  case MSG_IDENTIFY_CWD:
2754
0
  case MSG_IDENTIFY_ENVIRON:
2755
0
  case MSG_IDENTIFY_FEATURES:
2756
0
  case MSG_IDENTIFY_FLAGS:
2757
0
  case MSG_IDENTIFY_LONGFLAGS:
2758
0
  case MSG_IDENTIFY_STDIN:
2759
0
  case MSG_IDENTIFY_STDOUT:
2760
0
  case MSG_IDENTIFY_TERM:
2761
0
  case MSG_IDENTIFY_TERMINFO:
2762
0
  case MSG_IDENTIFY_TTYNAME:
2763
0
  case MSG_IDENTIFY_DONE:
2764
0
    if (server_client_dispatch_identify(c, imsg) != 0)
2765
0
      goto bad;
2766
0
    break;
2767
0
  case MSG_COMMAND:
2768
0
    if (server_client_dispatch_command(c, imsg) != 0)
2769
0
      goto bad;
2770
0
    break;
2771
0
  case MSG_RESIZE:
2772
0
    if (datalen != 0)
2773
0
      goto bad;
2774
2775
0
    if ((c->flags & CLIENT_CONTROL) || (~c->tty.flags & TTY_OPENED))
2776
0
      break;
2777
0
    server_client_update_latest(c);
2778
0
    old_sx = c->tty.sx;
2779
0
    old_sy = c->tty.sy;
2780
0
    tty_resize(&c->tty);
2781
0
    tty_repeat_requests(&c->tty, 0);
2782
0
    server_client_apply_resize(c, old_sx, old_sy);
2783
0
    break;
2784
0
  case MSG_EXITING:
2785
0
    if (datalen != 0)
2786
0
      goto bad;
2787
0
    server_client_set_session(c, NULL);
2788
0
    recalculate_sizes();
2789
0
    tty_close(&c->tty);
2790
0
    proc_send(c->peer, MSG_EXITED, -1, NULL, 0);
2791
0
    break;
2792
0
  case MSG_WAKEUP:
2793
0
  case MSG_UNLOCK:
2794
0
    if (datalen != 0)
2795
0
      goto bad;
2796
2797
0
    if (!(c->flags & CLIENT_SUSPENDED))
2798
0
      break;
2799
0
    c->flags &= ~CLIENT_SUSPENDED;
2800
2801
0
    if (c->fd == -1 || c->session == NULL) /* exited already */
2802
0
      break;
2803
0
    s = c->session;
2804
2805
0
    if (gettimeofday(&c->activity_time, NULL) != 0)
2806
0
      fatal("gettimeofday failed");
2807
2808
0
    tty_start_tty(&c->tty);
2809
0
    server_redraw_client(c);
2810
0
    recalculate_sizes();
2811
2812
0
    if (s != NULL)
2813
0
      session_update_activity(s, &c->activity_time);
2814
0
    break;
2815
0
  case MSG_SHELL:
2816
0
    if (datalen != 0)
2817
0
      goto bad;
2818
0
    if (server_client_dispatch_shell(c) != 0)
2819
0
      goto bad;
2820
0
    break;
2821
0
  case MSG_WRITE_READY:
2822
0
    if (file_write_ready(&c->files, imsg) != 0)
2823
0
      goto bad;
2824
0
    break;
2825
0
  case MSG_WRITE_DONE:
2826
0
    if (file_write_done(&c->files, imsg) != 0)
2827
0
      goto bad;
2828
0
    break;
2829
0
  case MSG_READ:
2830
0
    if (file_read_data(&c->files, imsg) != 0)
2831
0
      goto bad;
2832
0
    break;
2833
0
  case MSG_READ_DONE:
2834
0
    if (file_read_done(&c->files, imsg) != 0)
2835
0
      goto bad;
2836
0
    break;
2837
0
  }
2838
2839
0
  return;
2840
2841
0
bad:
2842
0
  log_debug("client %p invalid message type %d", c, imsg->hdr.type);
2843
0
  proc_kill_peer(c->peer);
2844
0
}
2845
2846
/* Callback when command is not allowed. */
2847
static enum cmd_retval
2848
server_client_read_only(struct cmdq_item *item, __unused void *data)
2849
0
{
2850
0
  cmdq_error(item, "client is read-only");
2851
0
  return (CMD_RETURN_ERROR);
2852
0
}
2853
2854
/* Callback for default command. */
2855
static enum cmd_retval
2856
server_client_default_command(struct cmdq_item *item, __unused void *data)
2857
0
{
2858
0
  struct client   *c = cmdq_get_client(item);
2859
0
  struct cmd_list   *cmdlist;
2860
0
  struct cmdq_item  *new_item;
2861
2862
0
  cmdlist = options_get_command(global_options, "default-client-command");
2863
0
  if ((c->flags & CLIENT_READONLY) &&
2864
0
      !cmd_list_all_have(cmdlist, CMD_READONLY))
2865
0
    new_item = cmdq_get_callback(server_client_read_only, NULL);
2866
0
  else
2867
0
    new_item = cmdq_get_command(cmdlist, NULL);
2868
0
  cmdq_insert_after(item, new_item);
2869
0
  return (CMD_RETURN_NORMAL);
2870
0
}
2871
2872
/* Callback when command is done. */
2873
static enum cmd_retval
2874
server_client_command_done(struct cmdq_item *item, __unused void *data)
2875
0
{
2876
0
  struct client *c = cmdq_get_client(item);
2877
2878
0
  if (~c->flags & CLIENT_ATTACHED)
2879
0
    c->flags |= CLIENT_EXIT;
2880
0
  else if (~c->flags & CLIENT_EXIT) {
2881
0
    if (c->flags & CLIENT_CONTROL)
2882
0
      control_ready(c);
2883
0
    tty_send_requests(&c->tty);
2884
0
  }
2885
0
  return (CMD_RETURN_NORMAL);
2886
0
}
2887
2888
/* Handle command message. */
2889
static int
2890
server_client_dispatch_command(struct client *c, struct imsg *imsg)
2891
0
{
2892
0
  struct msg_command    data;
2893
0
  char       *buf;
2894
0
  size_t        len;
2895
0
  int       argc = 0;
2896
0
  char      **argv, *cause;
2897
0
  struct cmd_parse_result  *pr;
2898
0
  struct args_value  *values;
2899
0
  struct cmdq_item   *new_item;
2900
2901
0
  if (c->flags & CLIENT_EXIT)
2902
0
    return (0);
2903
2904
0
  if (imsg->hdr.len - IMSG_HEADER_SIZE < sizeof data)
2905
0
    return (-1);
2906
0
  memcpy(&data, imsg->data, sizeof data);
2907
2908
0
  buf = (char *)imsg->data + sizeof data;
2909
0
  len = imsg->hdr.len - IMSG_HEADER_SIZE - sizeof data;
2910
0
  if (len > 0 && buf[len - 1] != '\0')
2911
0
    return (-1);
2912
2913
0
  if (cmd_unpack_argv(buf, len, data.argc, &argv) != 0) {
2914
0
    cause = xstrdup("command too long");
2915
0
    goto error;
2916
0
  }
2917
2918
0
  argc = data.argc;
2919
0
  if (argc == 0) {
2920
0
    new_item = cmdq_get_callback(server_client_default_command,
2921
0
        NULL);
2922
0
  } else {
2923
0
    values = args_from_vector(argc, argv);
2924
0
    pr = cmd_parse_from_arguments(values, argc, NULL);
2925
0
    args_free_values(values, argc);
2926
0
    free(values);
2927
0
    switch (pr->status) {
2928
0
    case CMD_PARSE_ERROR:
2929
0
      cause = pr->error;
2930
0
      goto error;
2931
0
    case CMD_PARSE_SUCCESS:
2932
0
      break;
2933
0
    }
2934
0
    cmd_free_argv(argc, argv);
2935
0
    if ((c->flags & CLIENT_READONLY) &&
2936
0
        !cmd_list_all_have(pr->cmdlist, CMD_READONLY)) {
2937
0
      new_item = cmdq_get_callback(server_client_read_only,
2938
0
          NULL);
2939
0
    } else
2940
0
      new_item = cmdq_get_command(pr->cmdlist, NULL);
2941
0
    cmd_list_free(pr->cmdlist);
2942
0
  }
2943
0
  cmdq_append(c, new_item);
2944
0
  cmdq_append(c, cmdq_get_callback(server_client_command_done, NULL));
2945
2946
0
  return (0);
2947
2948
0
error:
2949
0
  cmd_free_argv(argc, argv);
2950
2951
0
  cmdq_append(c, cmdq_get_error(cause));
2952
0
  free(cause);
2953
2954
0
  c->flags |= CLIENT_EXIT;
2955
0
  return (0);
2956
0
}
2957
2958
/* Handle identify message. */
2959
static int
2960
server_client_dispatch_identify(struct client *c, struct imsg *imsg)
2961
0
{
2962
0
  const char  *data, *home;
2963
0
  size_t     datalen;
2964
0
  int    flags, feat;
2965
0
  uint64_t   longflags;
2966
0
  char    *name;
2967
2968
0
  if (c->flags & CLIENT_IDENTIFIED)
2969
0
    return (-1);
2970
2971
0
  data = imsg->data;
2972
0
  datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
2973
2974
0
  switch (imsg->hdr.type) {
2975
0
  case MSG_IDENTIFY_FEATURES:
2976
0
    if (datalen != sizeof feat)
2977
0
      return (-1);
2978
0
    memcpy(&feat, data, sizeof feat);
2979
0
    c->term_features |= feat;
2980
0
    log_debug("client %p IDENTIFY_FEATURES %s", c,
2981
0
        tty_get_features(feat));
2982
0
    break;
2983
0
  case MSG_IDENTIFY_FLAGS:
2984
0
    if (datalen != sizeof flags)
2985
0
      return (-1);
2986
0
    memcpy(&flags, data, sizeof flags);
2987
0
    c->flags |= flags;
2988
0
    log_debug("client %p IDENTIFY_FLAGS %#x", c, flags);
2989
0
    break;
2990
0
  case MSG_IDENTIFY_LONGFLAGS:
2991
0
    if (datalen != sizeof longflags)
2992
0
      return (-1);
2993
0
    memcpy(&longflags, data, sizeof longflags);
2994
0
    c->flags |= longflags;
2995
0
    log_debug("client %p IDENTIFY_LONGFLAGS %#llx", c,
2996
0
        (unsigned long long)longflags);
2997
0
    break;
2998
0
  case MSG_IDENTIFY_TERM:
2999
0
    if (datalen == 0 || data[datalen - 1] != '\0')
3000
0
      return (-1);
3001
0
    c->term_name = xstrdup(data);
3002
0
    log_debug("client %p IDENTIFY_TERM %s", c, data);
3003
0
    break;
3004
0
  case MSG_IDENTIFY_TERMINFO:
3005
0
    if (datalen == 0 || data[datalen - 1] != '\0')
3006
0
      return (-1);
3007
0
    c->term_caps = xreallocarray(c->term_caps, c->term_ncaps + 1,
3008
0
        sizeof *c->term_caps);
3009
0
    c->term_caps[c->term_ncaps++] = xstrdup(data);
3010
0
    log_debug("client %p IDENTIFY_TERMINFO %s", c, data);
3011
0
    break;
3012
0
  case MSG_IDENTIFY_TTYNAME:
3013
0
    if (datalen == 0 || data[datalen - 1] != '\0')
3014
0
      return (-1);
3015
0
    c->ttyname = xstrdup(data);
3016
0
    log_debug("client %p IDENTIFY_TTYNAME %s", c, data);
3017
0
    break;
3018
0
  case MSG_IDENTIFY_CWD:
3019
0
    if (datalen == 0 || data[datalen - 1] != '\0')
3020
0
      return (-1);
3021
0
    if (access(data, X_OK) == 0)
3022
0
      c->cwd = xstrdup(data);
3023
0
    else if ((home = find_home()) != NULL)
3024
0
      c->cwd = xstrdup(home);
3025
0
    else
3026
0
      c->cwd = xstrdup("/");
3027
0
    log_debug("client %p IDENTIFY_CWD %s", c, data);
3028
0
    break;
3029
0
  case MSG_IDENTIFY_STDIN:
3030
0
    if (datalen != 0)
3031
0
      return (-1);
3032
0
    c->fd = imsg_get_fd(imsg);
3033
0
    log_debug("client %p IDENTIFY_STDIN %d", c, c->fd);
3034
0
    break;
3035
0
  case MSG_IDENTIFY_STDOUT:
3036
0
    if (datalen != 0)
3037
0
      return (-1);
3038
0
    c->out_fd = imsg_get_fd(imsg);
3039
0
    log_debug("client %p IDENTIFY_STDOUT %d", c, c->out_fd);
3040
0
    break;
3041
0
  case MSG_IDENTIFY_ENVIRON:
3042
0
    if (datalen == 0 || data[datalen - 1] != '\0')
3043
0
      return (-1);
3044
0
    if (strchr(data, '=') != NULL)
3045
0
      environ_put(c->environ, data, 0);
3046
0
    log_debug("client %p IDENTIFY_ENVIRON %s", c, data);
3047
0
    break;
3048
0
  case MSG_IDENTIFY_CLIENTPID:
3049
0
    if (datalen != sizeof c->pid)
3050
0
      return (-1);
3051
0
    memcpy(&c->pid, data, sizeof c->pid);
3052
0
    log_debug("client %p IDENTIFY_CLIENTPID %ld", c, (long)c->pid);
3053
0
    break;
3054
0
  default:
3055
0
    break;
3056
0
  }
3057
3058
0
  if (imsg->hdr.type != MSG_IDENTIFY_DONE)
3059
0
    return (0);
3060
0
  c->flags |= CLIENT_IDENTIFIED;
3061
3062
0
  if (c->term_name == NULL || *c->term_name == '\0') {
3063
0
    free(c->term_name);
3064
0
    c->term_name = xstrdup("unknown");
3065
0
  }
3066
3067
0
  if (c->ttyname != NULL && *c->ttyname != '\0')
3068
0
    name = xstrdup(c->ttyname);
3069
0
  else
3070
0
    xasprintf(&name, "client-%ld", (long)c->pid);
3071
0
  c->name = name;
3072
0
  log_debug("client %p name is %s", c, c->name);
3073
3074
#ifdef __CYGWIN__
3075
  c->fd = open(c->ttyname, O_RDWR|O_NOCTTY);
3076
  c->out_fd = dup(c->fd);
3077
#endif
3078
3079
0
  if (c->flags & CLIENT_CONTROL)
3080
0
    control_start(c);
3081
0
  else if (c->fd != -1) {
3082
0
    if (tty_init(&c->tty, c) != 0) {
3083
0
      close(c->fd);
3084
0
      c->fd = -1;
3085
0
    } else {
3086
0
      tty_resize(&c->tty);
3087
0
      c->flags |= CLIENT_TERMINAL;
3088
0
    }
3089
0
    if (c->out_fd != -1)
3090
0
      close(c->out_fd);
3091
0
    c->out_fd = -1;
3092
0
  }
3093
0
  if (c->flags & (CLIENT_CONTROL|CLIENT_TERMINAL))
3094
0
    events_fire_client("client-created", c);
3095
3096
  /* If pasting has taken too long, turn it off. */
3097
0
  if (c->flags & (CLIENT_BRACKETPASTING|CLIENT_ASSUMEPASTING) &&
3098
0
      current_time - c->paste_time > CLIENT_PASTE_TIME_LIMIT) {
3099
0
    log_debug("%s: paste time limit exceeded", c->name);
3100
0
    c->flags &= ~(CLIENT_BRACKETPASTING|CLIENT_ASSUMEPASTING);
3101
0
  }
3102
3103
  /*
3104
   * If this is the first client, load configuration files. Any later
3105
   * clients are allowed to continue with their command even if the
3106
   * config has not been loaded - they might have been run from inside it
3107
   */
3108
0
  if ((~c->flags & CLIENT_EXIT) &&
3109
0
       !cfg_finished &&
3110
0
       c == TAILQ_FIRST(&clients))
3111
0
    start_cfg();
3112
3113
0
  return (0);
3114
0
}
3115
3116
/* Handle shell message. */
3117
static int
3118
server_client_dispatch_shell(struct client *c)
3119
0
{
3120
0
  const char  *shell;
3121
3122
0
  shell = options_get_string(global_s_options, "default-shell");
3123
0
  if (!checkshell(shell))
3124
0
    shell = _PATH_BSHELL;
3125
0
  proc_send(c->peer, MSG_SHELL, -1, shell, strlen(shell) + 1);
3126
3127
0
  proc_kill_peer(c->peer);
3128
0
  return (0);
3129
0
}
3130
3131
/* Get client working directory. */
3132
const char *
3133
server_client_get_cwd(struct client *c, struct session *s)
3134
0
{
3135
0
  const char  *home;
3136
3137
0
  if (!cfg_finished && cfg_client != NULL)
3138
0
    return (cfg_client->cwd);
3139
0
  if (c != NULL && c->session == NULL && c->cwd != NULL)
3140
0
    return (c->cwd);
3141
0
  if (s != NULL && s->cwd != NULL)
3142
0
    return (s->cwd);
3143
0
  if (c != NULL && (s = c->session) != NULL && s->cwd != NULL)
3144
0
    return (s->cwd);
3145
0
  if ((home = find_home()) != NULL)
3146
0
    return (home);
3147
0
  return ("/");
3148
0
}
3149
3150
/* Get control client flags. */
3151
static uint64_t
3152
server_client_control_flags(struct client *c, const char *next)
3153
0
{
3154
0
  if (strcmp(next, "pause-after") == 0) {
3155
0
    c->pause_age = 0;
3156
0
    return (CLIENT_CONTROL_PAUSEAFTER);
3157
0
  }
3158
0
  if (sscanf(next, "pause-after=%u", &c->pause_age) == 1) {
3159
0
    c->pause_age *= 1000;
3160
0
    return (CLIENT_CONTROL_PAUSEAFTER);
3161
0
  }
3162
0
  if (strcmp(next, "no-output") == 0)
3163
0
    return (CLIENT_CONTROL_NOOUTPUT);
3164
0
  if (strcmp(next, "wait-exit") == 0)
3165
0
    return (CLIENT_CONTROL_WAITEXIT);
3166
0
  if (strcmp(next, "new-layouts") == 0)
3167
0
    return (CLIENT_CONTROL_NEWLAYOUTS);
3168
0
  return (0);
3169
0
}
3170
3171
/* Set client flags. */
3172
void
3173
server_client_set_flags(struct client *c, const char *flags)
3174
0
{
3175
0
  char  *s, *copy, *next;
3176
0
  uint64_t flag;
3177
0
  int  not;
3178
3179
0
  s = copy = xstrdup(flags);
3180
0
  while ((next = strsep(&s, ",")) != NULL) {
3181
0
    not = (*next == '!');
3182
0
    if (not)
3183
0
      next++;
3184
3185
0
    if (c->flags & CLIENT_CONTROL)
3186
0
      flag = server_client_control_flags(c, next);
3187
0
    else
3188
0
      flag = 0;
3189
0
    if (strcmp(next, "read-only") == 0)
3190
0
      flag = CLIENT_READONLY;
3191
0
    else if (strcmp(next, "ignore-size") == 0)
3192
0
      flag = CLIENT_IGNORESIZE;
3193
0
    else if (strcmp(next, "no-detach-on-destroy") == 0)
3194
0
      flag = CLIENT_NO_DETACH_ON_DESTROY;
3195
0
    if (flag == 0)
3196
0
      continue;
3197
3198
0
    log_debug("client %s set flag %s", c->name, next);
3199
0
    if (not) {
3200
0
      if (c->flags & CLIENT_READONLY)
3201
0
        flag &= ~CLIENT_READONLY;
3202
0
      c->flags &= ~flag;
3203
0
    } else
3204
0
      c->flags |= flag;
3205
0
    if (flag == CLIENT_CONTROL_NOOUTPUT)
3206
0
      control_reset_offsets(c);
3207
0
  }
3208
0
  free(copy);
3209
0
  proc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);
3210
0
}
3211
3212
/* Get client flags. This is only flags useful to show to users. */
3213
const char *
3214
server_client_get_flags(struct client *c)
3215
0
{
3216
0
  static char s[256];
3217
0
  char    tmp[32];
3218
3219
0
  *s = '\0';
3220
0
  if (c->flags & CLIENT_ATTACHED)
3221
0
    strlcat(s, "attached,", sizeof s);
3222
0
  if (c->flags & CLIENT_FOCUSED)
3223
0
    strlcat(s, "focused,", sizeof s);
3224
0
  if (c->flags & CLIENT_CONTROL)
3225
0
    strlcat(s, "control-mode,", sizeof s);
3226
0
  if (c->flags & CLIENT_IGNORESIZE)
3227
0
    strlcat(s, "ignore-size,", sizeof s);
3228
0
  if (c->flags & CLIENT_NO_DETACH_ON_DESTROY)
3229
0
    strlcat(s, "no-detach-on-destroy,", sizeof s);
3230
0
  if (c->flags & CLIENT_CONTROL_NOOUTPUT)
3231
0
    strlcat(s, "no-output,", sizeof s);
3232
0
  if (c->flags & CLIENT_CONTROL_WAITEXIT)
3233
0
    strlcat(s, "wait-exit,", sizeof s);
3234
0
  if (c->flags & CLIENT_CONTROL_NEWLAYOUTS)
3235
0
    strlcat(s, "new-layouts,", sizeof s);
3236
0
  if (c->flags & CLIENT_CONTROL_PAUSEAFTER) {
3237
0
    xsnprintf(tmp, sizeof tmp, "pause-after=%u,",
3238
0
        c->pause_age / 1000);
3239
0
    strlcat(s, tmp, sizeof s);
3240
0
  }
3241
0
  if (c->flags & CLIENT_READONLY)
3242
0
    strlcat(s, "read-only,", sizeof s);
3243
0
  if (c->flags & CLIENT_SUSPENDED)
3244
0
    strlcat(s, "suspended,", sizeof s);
3245
0
  if (c->flags & CLIENT_UTF8)
3246
0
    strlcat(s, "UTF-8,", sizeof s);
3247
0
  if (*s != '\0')
3248
0
    s[strlen(s) - 1] = '\0';
3249
0
  return (s);
3250
0
}
3251
3252
/* Remove pane from client state. */
3253
void
3254
server_client_remove_pane(struct window_pane *wp)
3255
0
{
3256
0
  struct client     *c;
3257
3258
0
  TAILQ_FOREACH(c, &clients, entry) {
3259
0
    if (c->tty.mouse_last_pane == (int)wp->id) {
3260
0
      c->tty.mouse_last_pane = -1;
3261
0
      c->tty.mouse_drag_update = NULL;
3262
0
      c->tty.mouse_scrolling_flag = 0;
3263
0
    }
3264
0
  }
3265
0
}
3266
3267
/* Print to a client. */
3268
void
3269
server_client_print(struct client *c, int parse, struct evbuffer *evb)
3270
0
{
3271
0
  void        *data = EVBUFFER_DATA(evb);
3272
0
  size_t         size = EVBUFFER_LENGTH(evb);
3273
0
  struct window_pane    *wp;
3274
0
  struct window_mode_entry  *wme;
3275
0
  char        *sanitized, *msg, *line, empty = '\0';
3276
3277
0
  if (!parse) {
3278
0
    utf8_stravisx(&msg, data, size,
3279
0
        VIS_OCTAL|VIS_CSTYLE|VIS_NOSLASH);
3280
0
  } else {
3281
0
    if (size == 0)
3282
0
      msg = &empty;
3283
0
    else {
3284
0
      msg = EVBUFFER_DATA(evb);
3285
0
      if (msg[size - 1] != '\0')
3286
0
        evbuffer_add(evb, "", 1);
3287
0
    }
3288
0
  }
3289
0
  log_debug("%s: %s", __func__, msg);
3290
3291
0
  if (c == NULL)
3292
0
    goto out;
3293
3294
0
  if (c->session == NULL || (c->flags & CLIENT_CONTROL)) {
3295
0
    if (~c->flags & CLIENT_UTF8) {
3296
0
      sanitized = utf8_sanitize(msg);
3297
0
      if (c->flags & CLIENT_CONTROL)
3298
0
        control_write(c, "%s", sanitized);
3299
0
      else
3300
0
        file_print(c, "%s\n", sanitized);
3301
0
      free(sanitized);
3302
0
    } else {
3303
0
      if (c->flags & CLIENT_CONTROL)
3304
0
        control_write(c, "%s", msg);
3305
0
      else
3306
0
        file_print(c, "%s\n", msg);
3307
0
    }
3308
0
    goto out;
3309
0
  }
3310
3311
0
  wp = c->session->curw->window->active;
3312
0
  wme = TAILQ_FIRST(&wp->modes);
3313
0
  if (wme == NULL || wme->mode != &window_view_mode)
3314
0
    window_pane_set_mode(wp, NULL, &window_view_mode, NULL, NULL,
3315
0
        NULL);
3316
0
  if (parse) {
3317
0
    do {
3318
0
      line = evbuffer_readln(evb, NULL, EVBUFFER_EOL_LF);
3319
0
      if (line != NULL) {
3320
0
        window_copy_add(wp, 1, "%s", line);
3321
0
        free(line);
3322
0
      }
3323
0
    } while (line != NULL);
3324
3325
0
    size = EVBUFFER_LENGTH(evb);
3326
0
    if (size != 0) {
3327
0
      line = EVBUFFER_DATA(evb);
3328
0
      window_copy_add(wp, 1, "%.*s", (int)size, line);
3329
0
    }
3330
0
  } else
3331
0
    window_copy_add(wp, 0, "%s", msg);
3332
3333
0
out:
3334
0
  if (!parse)
3335
0
    free(msg);
3336
0
}
3337
3338
static void
3339
server_client_report_theme(struct client *c, enum client_theme theme)
3340
0
{
3341
0
  enum client_theme  old = c->theme;
3342
3343
0
  if (theme == THEME_LIGHT) {
3344
0
    c->theme = THEME_LIGHT;
3345
0
    events_fire_client("client-light-theme", c);
3346
0
  } else {
3347
0
    c->theme = THEME_DARK;
3348
0
    events_fire_client("client-dark-theme", c);
3349
0
  }
3350
3351
  /*
3352
   * If the theme has changed, update the theme colours and redraw the
3353
   * client.
3354
   */
3355
0
  if (c->theme != old) {
3356
0
    server_client_update_theme_colours(c);
3357
0
    if (c->tty.flags & TTY_OPENED)
3358
0
      tty_invalidate(&c->tty);
3359
0
    server_redraw_client(c);
3360
0
  }
3361
3362
  /*
3363
   * Request foreground and background colour again. Don't forward 2031 to
3364
   * panes until a response is received.
3365
   */
3366
0
  tty_repeat_requests(&c->tty, 1);
3367
0
}