/*

    Minimum Profit 5.x
    A Programmer's Text Editor

    Session handling.

    Copyright (C) 1991-2007 Jeremy Cowgar, Angel Ortega

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    http://www.triptico.com

*/

/* automatically load / save sessions */
mp.config.auto_sessions = 0;

/* local sessions */
mp.config.local_sessions = 0;

/* session actions */

mp.actions['save_session'] = sub (d) { mp.long_op(mp.save_session); };
mp.actions['load_session'] = sub (d) { mp.long_op(mp.load_session); };

/* default keybindings */

/* action descriptions */

mp.actdesc['load_session'] = LL("Load session");
mp.actdesc['save_session'] = LL("Save session");

/* code */

sub mp.session_file()
/* returns the appropriate session saving file */
{
	return (mp.config.local_sessions && './' || HOMEDIR) ~ '.mp_session';
}


sub mp.save_session()
/* saves currently open files as a session. Returns: -1, nothing to save;
   -2, error saving; or 0, session correctly saved */
{
	local fh, filenames;
	
	filenames = [];
	
	/* no named files? exit doing nothing */
	if (grep(sub (e) { e.name ne L("<unnamed>"); }, mp.docs) == NULL)
		return -1;

	if ((fh = open(mp.session_file(), "w")) == NULL) {
		return -2;
	}
	
	foreach (doc, mp.docs) {
		if (doc.name ne L("<unnamed>"))
			write (fh,
				sprintf("%s\t%i\t%i\t%s\n",
					doc.name, doc.txt.x, doc.txt.y,
					(cmp(doc, mp.active()) == 0 && 'a' || '')
				)
			);
	}
	
	close(fh);

	return 0;
}


sub mp.load_session()
/* loads a session. Returns: -1, no session, -2, user cancellation on closing
   currently open documents and 0, ok */
{
	local fh, l;
	
	/* check to see if a session file can actually be opened before closing
	   all the editing windows */
	if ((fh = open(mp.session_file(), "r")) == NULL) {
		return -1;
	}

	if (!mp.actions.close_all()) {
		close(fh);
		return -2;
	}

	local active = -1;

	while (l = read(fh)) {
		local data, doc;
		data = split ("\t", mp.chomp(l));
		
		if (stat(data[0]) != NULL) {
			doc = mp.open(data[0]);
			
			doc.txt.x = data[1];
			doc.txt.y = data[2];

			/* if it has the 'a' flag, set as active */
			if (regex('/a/', data[3]))
				active = seek(mp.docs, doc);
		}
	}

	if (active != -1)
		mp.active_i = active;
	
	close(fh);

	return 0;
}
