1/* $OpenBSD$ */
2
3/*
4 * Copyright (c) 2009 Tiago Cunha <[email protected]>
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
21#include <errno.h>
22#include <fcntl.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <unistd.h>
27
28#include "tmux.h"
29
30/*
31 * Loads a paste buffer from a file.
32 */
33
34static enum cmd_retval cmd_load_buffer_exec(struct cmd *, struct cmdq_item *);
35
36const struct cmd_entry cmd_load_buffer_entry = {
37 .name = "load-buffer",
38 .alias = "loadb",
39
40 .args = { "b:", 1, 1 },
41 .usage = CMD_BUFFER_USAGE " path",
42
43 .flags = CMD_AFTERHOOK,
44 .exec = cmd_load_buffer_exec
45};
46
47struct cmd_load_buffer_data {
48 struct cmdq_item *item;
49 char *name;
50};
51
52static void
53cmd_load_buffer_done(__unused struct client *c, const char *path, int error,
54 int closed, struct evbuffer *buffer, void *data)
55{
56 struct cmd_load_buffer_data *cdata = data;
57 struct cmdq_item *item = cdata->item;
58 void *bdata = EVBUFFER_DATA(buffer);
59 size_t bsize = EVBUFFER_LENGTH(buffer);
60 void *copy;
61 char *cause;
62
63 if (!closed)
64 return;
65
66 if (error != 0)
67 cmdq_error(item, "%s: %s", path, strerror(error));
68 else if (bsize != 0) {
69 copy = xmalloc(bsize);
70 memcpy(copy, bdata, bsize);
71 if (paste_set(copy, bsize, cdata->name, &cause) != 0) {
72 cmdq_error(item, "%s", cause);
73 free(cause);
74 free(copy);
75 }
76 }
77 cmdq_continue(item);
78
79 free(cdata->name);
80 free(cdata);
81}
82
83static enum cmd_retval
84cmd_load_buffer_exec(struct cmd *self, struct cmdq_item *item)
85{
86 struct args *args = self->args;
87 struct cmd_load_buffer_data *cdata;
88 struct client *c = cmd_find_client(item, NULL, 1);
89 struct session *s = item->target.s;
90 struct winlink *wl = item->target.wl;
91 struct window_pane *wp = item->target.wp;
92 const char *bufname = args_get(args, 'b');
93 char *path;
94
95 cdata = xmalloc(sizeof *cdata);
96 cdata->item = item;
97 if (bufname != NULL)
98 cdata->name = xstrdup(bufname);
99 else
100 cdata->name = NULL;
101
102 path = format_single(item, args->argv[0], c, s, wl, wp);
103 file_read(item->client, path, cmd_load_buffer_done, cdata);
104 free(path);
105
106 return (CMD_RETURN_WAIT);
107}
108