/*
**		BRIEF -- Basic Reconfigurable Interactive Editing Facility
**
**		Written by Dave Nanian and Michael Strickman.
*/

/*
**		restore.cb:
**
**		This macro saves and restore search and translate global
**	variables, as well as the buffers (and positions therein)
**	active when BRIEF was last exited.	There are five parts/macros:
**	part one (save_state) saves the fixed state information, part two
**	(_save_state) saves the variable information (and can be replaced
**	by the user), part three (.rst) restores the list of files and
**	their positions, part four (restore) restores the fixed editing
**	information, and part five (_restore) restores the variable
**	editing information (and can be replaced by the user).
*/

#define REG_EXIT_ACTION 5
#define TRUE				1
#define FALSE				0
#define SYSTEM 			1

extern int	_reg_exp,				//	Current regular expression setting.
				_dir,						//	Current search direction.
				_t_dir,					//	Current translate direction.
				_block_search,			//	Current block search setting.
				_check_warnings,		//	"Check output for warnings" setting.
				_background;			//	Whether or not to compile in the bg.

extern string	_s_pat,				//	Last search pattern.
					_t_pat,				//	Last translate pattern.
					_r_pat;				//	Last translate replacement.

int _save_state (int start_buf_id);
void _save_file_info (int start_buf_id);
string _remove_newlines (string trans_str);

/*
**		save_state:
**
**		This macro, when registered as an EXIT_ACTION (type 5)
**	registered macro, saves the state of the search variables
**	as well as the names and positions of the current files.
**
**		The state file is broken up into several sections.  Each section
**	is preceded by a tag that describes the type of information stored in
**	the section.
*/

void save_state ()
{
	int	save_buf_id,
			start_buf_id,
			old_backup;

	string	file_name;

	/*
	**		If the user hasn't specified a BFILE as yet (if there
	**	isn't any BFILE in the environment, (inq_environment) returns
	**	the null string), or the given BFILE is invalid in some other
	**	way,	we can't save the state.  We display a message to this
	**	effect and exit.
	*/

	file_name = trim (ltrim (lower (inq_environment ("BFILE"))));

	if (substr (file_name, strlen (file_name) - 3) != ".rst")
		error ("Invalid BFILE specified, state not saved.");
	else
		{
		/*
		**		Here we create a buffer for the state file.	It's created
		**	as a system buffer to prevent it from appearing in the buffer
		**	list (and getting saved along with the other files).
		**
		**		We delete it first to save time in the normal case.
		*/

		del (file_name);

		/*		This prevents the reset file from ending up as
		**	an file to edit in the reset file.
		*/

		if ((save_buf_id = create_buffer ("State", file_name, SYSTEM)))
			delete_buffer(save_buf_id);

		if (!(save_buf_id = create_buffer ("State", file_name, SYSTEM)))
			error ("Invalid BFILE specified, state not saved.");
		else
			{
			int	screen_lines,
					screen_cols;

			/*
			**		We need to reset the current buffer later, since
			**	other macros could run after we do and we don't want
			**	to leave BRIEF in an unstable state.  We save its
			**	buffer id before continuing.
			*/

			start_buf_id = set_buffer (save_buf_id);

			/*
			**		Because of certain problems with the APPEND and
			**	DPATH commands, we make sure the file is empty before
			**	adding additional information.
			*/

			top_of_buffer ();
			drop_anchor ();
			end_of_buffer ();
			delete_block ();

			/*
			**		First, we save the "global" save information.
			**	This includes the screen size, search and translate
			**	directions, regular expression setting, block search
			**	setting, and search and translate patterns.
			*/

			inq_screen_size (screen_lines, screen_cols);

			insert ("[edit-]\nscreen=%d %d\ntoggles=%d %d %d %d %d %d\n",
									screen_cols, screen_lines,
									_dir, _reg_exp, _block_search,
									_t_dir, _check_warnings, _background);

			/*
			**		The search and translate patterns could,
			**	potentially, have newline characters in them.
			**	The _remove_newlines subroutine replaces those
			**	newline characters with \n, the regular expression
			**	that means "newline".
			*/

			insert ("srch=" + _remove_newlines (_s_pat));
			insert ("src=" + _remove_newlines (_t_pat));
			insert ("rpl=" + _remove_newlines (_r_pat));

			/*
			**		Now we call the _save_state macro to save the
			**	remainder of the state information.  Note that
			**	this macro can be replaced to extend restore's
			**	capabilities.
			*/

			_save_file_info (start_buf_id);
			_save_state (start_buf_id);
			set_buffer (save_buf_id);

			/*
			**		Finally, we write the restore file to disk.
			**	Since we don't want backup files created, we
			**	turn those off.  We put it back the way it was
			**	before exiting, since other macros could run
			**	once we're through.
			*/

			old_backup = set_backup (FALSE);
			write_buffer ();
			set_backup (old_backup);
			delete_buffer (save_buf_id);
			set_buffer (start_buf_id);
			}
		}
}

/*
**		_save_state:
**
**		This macro is the end of the save_state chain; other macros can
**	replace it to save state information in the state file.
*/

int _save_state (int)
{
	returns (0);
}

/*
**		_save_file_info:
**
**		This macro gets called to save the variable length state information.
*/

void _save_file_info (int start_buf_id)
{
	int	save_buf_id = inq_buffer (),
			curr_buf_id,
			curr_win_id = inq_window (),
			start_win_id = curr_win_id,
			line,
			col,
			top_line,
			top_col,
			cursor_line,
			cursor_col,
			lx,
			by,
			rx,
			ty,
			i;

	string	info;

	/*
	**		Now that the global state information has been saved, we save the
	**	information about the buffers and windows in the [brief] section.
	**
	**		But first, we just save a partial accounting of the current
	**	buffer in the [edit-] section.  This field isn't used for much.
	**
	**		Then, we save all the buffers that are being displayed in tiled
	**	windows.  These windows are recreated along with the buffers if no
	**	filename is specified.
	**
	**		Finally, we save information about the buffers that aren't being
	**	viewed in a window.
	**
	**		We skip system buffers manually, rather than with the (next_buffer)
	**	parameter, because we could have been entered with a system buffer as
	**	the current buffer.  If we made use of the (next_buffer) parameter,
	**	we'd never come back to the starting buffer and would infinite loop.
	*/

	set_buffer (start_buf_id);
	inq_position (line, col);
	inq_top_left (top_line, top_col, NULL, NULL, NULL, start_buf_id);
	inq_names (info);
	set_buffer (save_buf_id);
	insert ("file=%s %u %u %u %u\n[brief]\n", info, top_col, top_line, col, line);

	do
		{
		/*
		**		We don't save the state of overlapping windows.  Exit if there's
		**	one on the screen.
		*/

		if (inq_window_info (curr_win_id, curr_buf_id, lx, by, rx, ty))
			break;

		/*
		**		If there's a buffer in the window, save all the appropriate
		**	information, including:
		**
		**			The fully qualified filename.
		**			The column and line of the file in the top left corner
		**			of the window.
		**			The column and line of the file the cursor's on.
		**			The window's coordinates (lx, by, rx, ty).
		**			The window's colors.
		*/

		if (curr_buf_id)
			{
			set_buffer (curr_buf_id);
			inq_names (info);
			inq_top_left (top_line, top_col, curr_win_id, cursor_line, cursor_col);
			set_buffer (save_buf_id);
			insert ("file=%s %u %u %u %u %d %d %d %d c=%d\n", info,
										top_col, top_line, cursor_col, cursor_line,
										lx, by, rx, ty, inq_window_color (curr_win_id));
			}
		curr_win_id = next_window (curr_win_id);
		}
	while (start_win_id != curr_win_id);

	/*
	**		Now we save all the buffers that aren't viewed in windows.
	*/

	set_buffer (start_buf_id);

	do
		{
		/*
		**		If there was an overlapping window on the screen, we save
		**	_all_ the buffers, not just the ones that weren't being viewed.
		*/

		if (!inq_system () && (!inq_views (curr_buf_id) || inq_window_info ()))
			{
			inq_names (info);
			inq_position (line, col);
			inq_top_left (top_line, top_col, NULL, NULL, NULL, curr_buf_id);

			set_buffer (save_buf_id);
			insert ("file=%s %u %u %u %u\n", info, top_col, top_line, col, line);
			set_buffer (curr_buf_id);
			}
		set_buffer (curr_buf_id = next_buffer (1));
		}
	while (start_buf_id != curr_buf_id);

	set_buffer (save_buf_id);
	insert ("[shared-]\n");

	/*
	**		Finally, we save the bookmarks.
	*/

	for ( ; i < 10 ; i++)
		if (goto_bookmark (i, curr_buf_id, line, col))
			{
			set_buffer (curr_buf_id);
			inq_names (info);
			set_buffer (save_buf_id);
			insert ("mark=edit %s %u %u bnumber=%u\n", info, col, line, i);
			}
	set_buffer (start_buf_id);
	inq_position (line, col);
	inq_names (info);
	set_buffer (save_buf_id);
	insert ("pmark=%s %u %u\n", info, col, line);
}

/*
**		.rst:
**
**		This macro is, quite frankly, a mite strange.  When the
**	user types "b" with no arguments, BRIEF automatically loads
**	the file specified by the BFILE environment variable.  If
**	that file has the extension ".rst", this macro runs.
**
**		This macro then restores the files that were active
**	during the last editing session.  The state file buffer
**	(specified in the BFILE) isn't deleted -- the restore macro,
**	which runs after the file loading sequence, does that after
**	restoring the state of the search and translate variables.
*/

void .rst ()
{
	string	file_name;

	/*
	**		We need the name of the current file for the next test.
	**	All we need is the buffer name, which is the last parameter.
	**	The NULL placeholder is used to omit the additional information.
	*/

	inq_names (NULL, NULL, file_name);

	/*
	**		This logic only makes sense the first time this file extension
	**	macro is called.  If we're running it for the second time, or the file
	**	isn't the same as the state file (maintained in the BFILE environment
	**	variable), we skip it.	Initialization logic for "real" .rst files can
	**	be placed in the "true" clause of the if statement (replacing or
	**	supplementing the (tabs) statement).
	**
	**		We use "index" here because the only thing we really care about is
	**	that the file name matches the name of the file specified in BFILE:
	**	remember that the path specified could be relative.
	*/

	if (!(first_time () && index (trim (lower (inq_environment ("BFILE"))) + "\xff", file_name + "\xff")))
		tabs (9);
	else
		{
		int	save_buf_id = inq_buffer (),
				curr_buf,
				line,
				col,
				top_line,
				top_col,
				lx,
				by,
				rx,
				ty,
				bg_color,
				loc,
				has_window,
				window_to_select,
				old_msg_level = inq_msg_level (),
				have_a_file = 0;

		string	file_line;

		/*
		**		BRIEF has already edited the state file (because of normal BFILE
		**	processing) and made it the current buffer.	We get its buffer id
		**	for future use, search for the [brief] string that tells us where
		**	the file data starts, and process the file information, which
		**	is in the following format:
		**
		**		The string "file=".
		**		Full, qualified filename.
		**		The column at the left hand side of the last/this window.
		**		The line displayed at the top of the last/this window.
		**		The current column number in this window/in the buffer.
		**		The current line number in this window/in the buffer.
		**
		**		The rest of the information is optional, and is only there if
		**	there were views of the buffer.
		**
		**		The coordinates of the window (lx, by, rx, ty).
		**		The string "c=".
		**		The window color.
		**
		**		Note that if the telltale [brief] string isn't found, we can't
		**	process the .rst file.  In addition, if the screen size specified
		**	in the [edit-] section isn't the same as the current screen size,
		**	we can't continue.
		*/

		if (search_fwd ("[edit-]\n", 0))
			{
			int	curr_win_lines,
					curr_win_cols,
					old_win_lines,
					old_win_cols,
					create_windows;

			inq_screen_size (curr_win_lines, curr_win_cols);
			search_fwd ("screen=", 0);
			next_char (7);
			old_win_cols = atoi (file_line = trim (ltrim (compress (read ()))));
			old_win_lines = atoi (substr (file_line, index (file_line, " ") + 1));

			if (search_fwd ("[brief]\n", 0))
				{
				lx = 1;
				rx = curr_win_cols - 2;
				ty = 1;
				by = curr_win_lines - 3;
				bg_color = inq_window_color ();
				create_windows = ((curr_win_lines == old_win_lines) && (curr_win_cols == old_win_cols));

				down ();

				/*
				**		Here's the loop that processes the file information.  We
				**	continue restoring files until there's no more information in
				**	the file to restore (signaled by EOF or another section).
				*/
			
				while (substr (file_line = trim (read ()), 1, 5) == "file=")
					{
					
					/*		If this is the first time thru, destroy all windows
					*/

					if (!have_a_file)
						{
						display_windows (0);
						have_a_file = 1;
						}

					/*
					**		The string "c=" is only present if this is a window/file
					**	declaration.
					*/

					if (loc = rindex (file_line, " c="))
						{
						has_window = TRUE;

						if (create_windows)
							{
							bg_color = atoi (substr (file_line, loc + 3));
							loc = rindex (substr (file_line, 1, loc - 1), " ");
							ty = atoi (substr (file_line, loc + 1));
							loc = rindex (substr (file_line, 1, loc - 1), " ");
							rx = atoi (substr (file_line, loc + 1));
							loc = rindex (substr (file_line, 1, loc - 1), " ");
							by = atoi (substr (file_line, loc + 1));
							loc = rindex (substr (file_line, 1, loc - 1), " ");
							lx = atoi (substr (file_line, loc + 1));
							file_line = substr (file_line, 1, loc - 1);
							}
						else
							{
							int	i;

							for ( ; i < 5 ; i++)
								{
								file_line = substr (file_line, 1, loc - 1);
								loc = rindex (file_line, " ");
								}
							}
						}
					else if (!window_to_select)
						has_window = TRUE;

					loc = rindex (file_line, " ");
					line = atoi (substr (file_line, loc + 1));
					loc = rindex (substr (file_line, 1, loc - 1), " ");
					col = atoi (substr (file_line, loc + 1));
					loc = rindex (substr (file_line, 1, loc - 1), " ");
					top_line = atoi (substr (file_line, loc + 1));
					loc = rindex (substr (file_line, 1, loc - 1), " ");
					top_col = atoi (substr (file_line, loc + 1));

					file_name = trim (ltrim (substr (file_line, 6, loc - 6)));
					down ();

					/*
					**		edit_file is used to load the file back in because it
					**	deals with all the details of attaching the buffer to the
					**	window, calling the proper initialization routines, setting
					**	the current buffer, etc.
					**
					**		If the call to edit_file fails, we know something has
					**	gone wrong.  So we ignore this file and continue to the
					**	next.
					*/

					set_msg_level (0);

					if (curr_buf = inq_buffer (file_name))
						set_buffer (curr_buf);

					if (curr_buf || edit_file (file_name) > 0)
						{
						if (has_window && (create_windows || !window_to_select))
							{
							int	window_id = create_tiled_window (lx, by, rx, ty, inq_buffer ());

							if (!window_to_select)
								window_to_select = window_id;

							set_top_left (top_line, top_col, window_id, line, col);
							window_color (bg_color, window_id);
							}
						else
							{
							move_abs (line, col);
							set_top_left (top_line, top_col, NULL, NULL, NULL, inq_buffer ());
							}
						/*
						**		At this point, the restored file has been made the
						**	current buffer.	We have to make our state file current
						**	so the top of the loop works correctly.
						*/

						set_buffer (save_buf_id);
						}
					else if (has_window && (create_windows || !window_to_select))
						{
						int	window_id = create_tiled_window (lx, by, rx, ty, save_buf_id);

						if (!window_to_select)
							window_to_select = window_id;
						}
					set_msg_level (old_msg_level);
					has_window = FALSE;
					}

				if (have_a_file)
					{
					display_windows (1);

					set_window (window_to_select);
					}
				}
			}

		/*		If there were no files int the state file, prompt the
		**	user to edit a file
		*/

		if (!have_a_file)
			{
			int	buf,
					curr_win_lines,
					curr_win_cols;

			/* destroy all windows */

			set_msg_level(0);

			display_windows(0);

			/* create a temp buffer */
									
			buf = create_buffer ("???", NULL);

			inq_screen_size (curr_win_lines, curr_win_cols);

			lx = 1;
			rx = curr_win_cols - 2;
			ty = 1;
			by = curr_win_lines - 3;

			/* create one big window */

			create_tiled_window (lx, by, rx, ty, buf);

			display_windows(1);

			/* get a file from the user */

			if (edit_file() <= 0)
				exit();

			/* destroy temp buffer */

			delete_buffer(buf);

			set_msg_level (old_msg_level);
			}
		}
}

/*
**		restore:
**
**		This macro restores the state of the search and translate
**	global variables, as well as the list of bookmarks for each
**	currently edited file.
**
**		Note that if the ".rst" macro ran when BRIEF was started,
**	the state file (BFILE) has already been loaded.  In this case,
**	(create_buffer) just gives us its buffer ID, and doesn't bother
**	loading the file again.
*/

void restore ()
{
	if (first_time ())
		{
		string	file_name;

		/*
		**		First, we register the macro that will end up saving the state of
		**	the session for the next time around.
		*/

		register_macro (REG_EXIT_ACTION, "save_state");

		/*
		**		If this macro runs, and no BFILE is specified, we can't restore
		**	the state (you can't restore what isn't there).  So we put up an
		**	error message and exit.  If the file doesn't exist, we don't
		**	proceed -- once again, there's nothing to restore!
		*/

		file_name = trim (ltrim (lower (inq_environment ("BFILE"))));

		if (substr (file_name, strlen (file_name) - 3) != ".rst")
			error ("Invalid BFILE specified, state not restored.");
		else if (exist (file_name))
			{
			/*
			**		Before we make the state file buffer current, we have to
			**	ensure the old buffer (which is in the main window) is saved
			**	away.  Before we exit the macro, we have to reset it:  otherwise,
			**	BRIEF gets very unhappy.
			*/

			int	buffer_id,
					old_buffer = inq_buffer ();

			string	file_line;

			/*
			**		If the buffer creation fails ((create_buffer) returns 0), we
			**	tell the user about the problem and stop.  Otherwise, we continue
			**	with the restore.
			*/

			if (!(buffer_id = create_buffer ("Restore", file_name)))
				error ("Invalid BFILE specified.");
			else
				{
				/*
				**		Here we make the restore buffer current and parse the
				**	information in the state file.  This includes:
				**
				**	 The size of the screen.
				**	 The search direction, regular expression setting,
				**	  search block setting, translate direction, warnings-only
				**	  and background compile settings.
				**	 The search pattern.
				**	 The translate pattern.
				**	 The replacement string.
				**
				**		No error checking is done on the results of the parse:  if
				**	the numbers aren't right, the (atoi) call will fail and
				**	things will default to 0 (if the strings don't exist, they'll
				**	probably be null).
				*/

				set_buffer (buffer_id);
				top_of_buffer ();

				if (search_fwd ("[edit-]\n", 0))
					{
					down ();

					while (substr (file_line = ltrim (read ()), 1, 1) != "[")
						{
						switch (substr (file_line, 1, index (file_line, "=")))
							{
							case "toggles=":
								{
								file_line = trim (compress (file_line));
								_dir = atoi (substr (file_line, 9));
								file_line = substr (file_line, index (file_line, " ") + 1);
								_reg_exp = atoi (file_line);
								file_line = substr (file_line, index (file_line, " ") + 1);
								_block_search = atoi (file_line);
								file_line = substr (file_line, index (file_line, " ") + 1);
								_t_dir = atoi (file_line);
								file_line = substr (file_line, index (file_line, " ") + 1);
								_check_warnings = atoi (file_line);
								file_line = substr (file_line, index (file_line, " ") + 1);
								_background = atoi (file_line);
								}
							case "srch=":
								_s_pat = substr (file_line, 6, strlen (file_line) - 6);

							case "src=":
								_t_pat = substr (file_line, 5, strlen (file_line) - 5);

							case "rpl=":
								_r_pat = substr (file_line, 5, strlen (file_line) - 5);
							}
						down ();
						}
					/*
					**		Now we call the _restore macro to finish up the
					**	restoration.  Note that this macro can be replaced to
					**	extend restore's capabilities.
					*/

					_restore (old_buffer);
					}
				}
			set_buffer (buffer_id);

			/*
			**		Here we make sure the state file buffer isn't the same as
			**	the buffer that was current when we entered the macro.  This
			**	shouldn't happen, but it could.
			*/

			if (old_buffer != buffer_id && !inq_views (buffer_id))
				{
				set_buffer (old_buffer);
				delete_buffer (buffer_id);
				}
			}
		}
}

/*
**		_restore:
**
**		This macro restores the variable editing information.  It can be
**	replaced by the user to extend restore's capabilities.
*/

_restore (int)
{
	/*
	**		Now, we restore the list of bookmarks.  We check to see if each
	**	buffer in the file list is being edited in this session.  If so, its
	**	bookmarks are restored.
	*/

	top_of_buffer ();

	if (search_fwd ("[shared-]\n", 0))
		{
		int	bookmark_num,
				loc,
				mark_buf,
				line,
				col;

		string	file_line;

		down ();

		while (!inq_position () && read (1) != "[")
			{
			file_line = trim (ltrim (compress (read ())));

			if (substr (file_line, 1, 9) == "mark=edit")
				{
				file_line = substr (file_line, 11);

				if ((mark_buf = inq_buffer (substr (file_line, 1, index (file_line, " ") - 1)))
						&& (loc = rindex (file_line, " bnumber=")))
					{
					bookmark_num = atoi (substr (file_line, loc + 9));
					loc = rindex (substr (file_line, 1, loc - 1), " ");
					line = atoi (substr (file_line, loc + 1));
					loc = rindex (substr (file_line, 1, loc - 1), " ");
					col = atoi (substr (file_line, loc + 1));
					drop_bookmark (bookmark_num, "y", mark_buf, line, col);
					}
				}
			down ();
			}
		}
}

/*
**		_remove_newlines:
**
**		This macro replaces all newline characters with the character sequence
**	"\n".  This prevents problems when a search pattern with a newline in it
**	is inserted.  Note that a hard carriage return is also inserted at the
**	end of the line as a step saver.
*/

string _remove_newlines (string trans_str)
{
	int	loc;

	/*
	**		This loop checks for newlines in the passed string.  If
	**	once is found, the string is split into two parts:  the part
	**	before the newline, and the part after.  The two halves are
	**	then put back together again, with a newline regular expression
	**	("\n") in between.
	*/

	while (loc = index (trans_str, "\n"))
		trans_str = substr (trans_str, 1, loc - 1) + "\\n" + substr (trans_str, loc + 1);

	returns (trans_str + "\n");
}
