1/*
2
3    Minimum Profit - A Text Editor
4    Session handling.
5
6    ttcdt <dev@triptico.com> et al.
7
8    This software is released into the public domain.
9    NO WARRANTY. See file LICENSE for details.
10
11*/
12
13/* automatically load / save sessions */
14mp.config.auto_sessions = 0;
15
16/* local sessions */
17mp.config.local_sessions = 0;
18
19/** session actions **/
20
21mp.actions['save_session'] = sub { mp.long_op(mp.save_session); };
22mp.actions['load_session'] = sub { mp.long_op(mp.load_session); };
23
24/** default keybindings **/
25
26/** action descriptions **/
27
28mp.actdesc['load_session'] = LL("Load session");
29mp.actdesc['save_session'] = LL("Save session");
30
31/** code **/
32
33sub mp.session_file()
34/* returns the appropriate session saving file */
35{
36    return (mp.config.local_sessions && './' || HOMEDIR) + '.mp_session';
37}
38
39
40sub mp.save_session()
41/* saves currently open files as a session. Returns: -1, nothing to save;
42   -2, error saving; or 0, session correctly saved */
43{
44    local fh, filenames;
45
46    filenames = [];
47
48    /* no named files? exit doing nothing */
49    if (grep(mp.docs, sub (e) { e.name != L("<unnamed>"); }) == NULL)
50        return -1;
51
52    if ((fh = open(mp.session_file(), "w")) == NULL) {
53        return -2;
54    }
55
56    foreach (doc, mp.docs) {
57        if (doc.name != L("<unnamed>"))
58            write (fh,
59                sprintf("%s\t%i\t%i\t%s\n",
60                    doc.name, doc.txt.x, doc.txt.y,
61                    (cmp(doc, mp.active()) == 0 && 'a' || '')
62                )
63            );
64    }
65
66    close(fh);
67
68    return 0;
69}
70
71
72sub mp.load_session()
73/* loads a session. Returns: -1, no session, -2, user cancellation on closing
74   currently open documents and 0, ok */
75{
76    local fh, l;
77
78    /* check to see if a session file can actually be opened before closing
79       all the editing windows */
80    if ((fh = open(mp.session_file(), "r")) == NULL) {
81        return -1;
82    }
83
84    if (!mp.actions.close_all()) {
85        close(fh);
86        return -2;
87    }
88
89    local active = -1;
90
91    while (l = read(fh)) {
92        local data, doc;
93        data = split (mp.chomp(l), "\t");
94
95        if (stat(data[0]) != NULL) {
96            doc = mp.open(data[0]);
97
98            doc->set_y(integer(data[2]))->set_x(integer(data[1]));
99
100            /* if it has the 'a' flag, set as active */
101            if (regex(data[3], '/a/'))
102                active = seek(mp.docs, doc);
103        }
104    }
105
106    if (active != -1)
107        mp.set_active(active);
108
109    close(fh);
110
111    return 0;
112}
113