/**
 * \file FormPreferences.C
 * This file is part of LyX, the document processor.
 * Licence details can be found in the file COPYING.
 *
 * \author Angus Leeming
 *
 * Full author contact details are available in file CREDITS.
 */

#include <config.h>

#include "FormPreferences.h"
#include "forms/form_preferences.h"

#include "FormColorpicker.h"
#include "forms_gettext.h"
#include "input_validators.h"
#include "xformsBC.h"
#include "xforms_helpers.h"

#include "controllers/ControlPrefs.h"
#include "controllers/frnt_lang.h"
#include "controllers/helper_funcs.h" // getSecond

#include "buffer.h"
#include "lastfiles.h"
#include "LColor.h"
#include "lyxfont.h"

#include "support/convert.h"
#include "support/lstrings.h"
#include "support/package.h"
#include "support/filetools.h"

#include "lyx_forms.h"
#include "combox.h"

#include <iomanip>

using std::endl;
using std::make_pair;
using std::max;
using std::min;

using std::pair;
using std::vector;
using std::string;

namespace lyx {

using support::AddName;
using support::ChangeExtension;
using support::package;
using support::rtrim;
using support::trim;

namespace frontend {

namespace {

string makeFontName(string const & family, string const & foundry)
{
	if (foundry.empty())
		return family;
	return family + ',' + foundry;
}


pair<string,string> parseFontName(string const & name)
{
	string::size_type const idx = name.find(',');
	if (idx == string::npos)
		return make_pair(name, string());
	return make_pair(name.substr(0, idx),
			 name.substr(idx+1));
}



#if FL_VERSION == 0 || (FL_REVISION == 0 && FL_FIXLEVEL < 2)
bool const scalableTabfolders = false;
#else
bool const scalableTabfolders = true;
#endif

} // namespace anon


typedef FormController<ControlPrefs, FormView<FD_preferences> > base_class;


FormPreferences::FormPreferences(Dialog & parent)
	: base_class(parent, _("Preferences"), scalableTabfolders),
	  colors_(*this), converters_(*this), copiers_(*this),
	  formats_(*this), identity_(*this), inputs_misc_(*this),
	  interface_(*this), language_(*this), lnf_misc_(*this),
	  outputs_misc_(*this), paths_(*this), printer_(*this),
	  screen_fonts_(*this), spelloptions_(*this)
{}


void FormPreferences::redraw()
{
	if (!(form() && form()->visible))
		return;
	fl_redraw_form(form());

	FL_FORM * form2 = fl_get_active_folder(dialog_->tabfolder_prefs);
	if (!(form2 && form2->visible))
		return;
	fl_redraw_form(form2);

	FL_FORM * form3 = 0;
	if (form2 == converters_tab_->form)
		form3 = fl_get_active_folder(converters_tab_->tabfolder_inner);

	else if (form2 == look_n_feel_tab_->form)
		form3 = fl_get_active_folder(look_n_feel_tab_->tabfolder_inner);

	else if (form2 == inputs_tab_->form)
		form3 = fl_get_active_folder(inputs_tab_->tabfolder_inner);

	else if (form2 == outputs_tab_->form)
		form3 = fl_get_active_folder(outputs_tab_->tabfolder_inner);

	else if (form2 == lang_opts_tab_->form)
		form3 = fl_get_active_folder(lang_opts_tab_->tabfolder_inner);

	if (form3 && form3->visible)
		fl_redraw_form(form3);
}


void FormPreferences::hide()
{
	// We need to hide the active tabfolder otherwise we get a
	// BadDrawable error from X window and LyX crashes without saving.
	FL_FORM * inner_form = fl_get_active_folder(dialog_->tabfolder_prefs);
	if (inner_form && inner_form->visible)
		fl_hide_form(inner_form);
	FormDialogView::hide();
}


void FormPreferences::build()
{
	dialog_.reset(build_preferences(this));

	// Manage the restore, save, apply and cancel/close buttons
	bcview().setOK(dialog_->button_ok);
	bcview().setApply(dialog_->button_apply);
	bcview().setCancel(dialog_->button_close);
	bcview().setRestore(dialog_->button_restore);

	// Allow the base class to control messages
	setMessageWidget(dialog_->text_warning);

	// build the tab folders
	converters_tab_.reset(build_preferences_inner_tab(this));
	look_n_feel_tab_.reset(build_preferences_inner_tab(this));
	inputs_tab_.reset(build_preferences_inner_tab(this));
	outputs_tab_.reset(build_preferences_inner_tab(this));
	lang_opts_tab_.reset(build_preferences_inner_tab(this));

	// build actual tabfolder contents
	// these will become nested tabfolders
	colors_.build();
	converters_.build();
	copiers_.build();
	formats_.build();
	inputs_misc_.build();
	interface_.build();
	language_.build();
	lnf_misc_.build();
	identity_.build();
	outputs_misc_.build();
	paths_.build();
	printer_.build();
	screen_fonts_.build();
	spelloptions_.build();

	// Enable the tabfolders to be rescaled correctly.
	if (scalableTabfolders) {
		FL_OBJECT * folder = dialog_->tabfolder_prefs;
		fl_set_tabfolder_autofit(folder, FL_FIT);

		folder = look_n_feel_tab_->tabfolder_inner;
		fl_set_tabfolder_autofit(folder, FL_FIT);

		folder = converters_tab_->tabfolder_inner;
		fl_set_tabfolder_autofit(folder, FL_FIT);

		folder = inputs_tab_->tabfolder_inner;
		fl_set_tabfolder_autofit(folder, FL_FIT);

		folder = outputs_tab_->tabfolder_inner;
		fl_set_tabfolder_autofit(folder, FL_FIT);

		folder = lang_opts_tab_->tabfolder_inner;
		fl_set_tabfolder_autofit(folder, FL_FIT);
	}

	// Stack tabs
	// Now add them to the tabfolder
	fl_addto_tabfolder(dialog_->tabfolder_prefs,
			   _("Look & Feel").c_str(),
			   look_n_feel_tab_->form);
	fl_addto_tabfolder(dialog_->tabfolder_prefs,
			   _("Lang Opts").c_str(),
			   lang_opts_tab_->form);
	fl_addto_tabfolder(dialog_->tabfolder_prefs,
			   _("Conversion").c_str(),
			   converters_tab_->form);
	fl_addto_tabfolder(dialog_->tabfolder_prefs,
			   _("Inputs").c_str(),
			   inputs_tab_->form);
	fl_addto_tabfolder(dialog_->tabfolder_prefs,
			   _("Outputs").c_str(),
			   outputs_tab_->form);

	// now build the nested tabfolders
	// Starting with look and feel
	fl_addto_tabfolder(look_n_feel_tab_->tabfolder_inner,
			   _("Screen Fonts").c_str(),
			   screen_fonts_.dialog()->form);
	fl_addto_tabfolder(look_n_feel_tab_->tabfolder_inner,
			   _("Interface").c_str(),
			   interface_.dialog()->form);
	fl_addto_tabfolder(look_n_feel_tab_->tabfolder_inner,
			   _("Colors").c_str(),
			   colors_.dialog()->form);
	fl_addto_tabfolder(look_n_feel_tab_->tabfolder_inner,
			   _("Misc").c_str(),
			   lnf_misc_.dialog()->form);
	fl_addto_tabfolder(look_n_feel_tab_->tabfolder_inner,
			   _("Identity").c_str(),
			   identity_.dialog()->form);

	// then build converters
	fl_addto_tabfolder(converters_tab_->tabfolder_inner,
			   _("Formats").c_str(),
			   formats_.dialog()->form);
	fl_addto_tabfolder(converters_tab_->tabfolder_inner,
			   _("Converters").c_str(),
			   converters_.dialog()->form);
	fl_addto_tabfolder(converters_tab_->tabfolder_inner,
			   _("Copiers").c_str(),
			   copiers_.dialog()->form);

	// then build inputs
	// Paths should probably go in a few inner_tab called Files
	fl_addto_tabfolder(inputs_tab_->tabfolder_inner,
			   _("Paths").c_str(),
			   paths_.dialog()->form);
	fl_addto_tabfolder(inputs_tab_->tabfolder_inner,
			   _("Misc").c_str(),
			   inputs_misc_.dialog()->form);

	// then building outputs
	fl_addto_tabfolder(outputs_tab_->tabfolder_inner,
			   _("Printer").c_str(),
			   printer_.dialog()->form);
	fl_addto_tabfolder(outputs_tab_->tabfolder_inner,
			   _("Misc").c_str(),
			   outputs_misc_.dialog()->form);

	// then building usage
	fl_addto_tabfolder(lang_opts_tab_->tabfolder_inner,
			   _("Spellchecker").c_str(),
			   spelloptions_.dialog()->form);
	fl_addto_tabfolder(lang_opts_tab_->tabfolder_inner,
			   _("Language").c_str(),
			   language_.dialog()->form);
}


void FormPreferences::apply()
{
	// set the new lyxrc entries
	// many of these need to trigger other functions when the assignment
	// is made.  For example, screen zoom and font types.  These could be
	// handled either by signals/slots in lyxrc or just directly call the
	// associated functions here.
	// There are other problems with this scheme.  We really should check
	// what we copy to make sure that it really is necessary to do things
	// like update the screen fonts because that flushes the textcache
	// and other stuff which may cost us a lot on slower/high-load
	// machines.

	LyXRC & rc(controller().rc());

	colors_.apply();
	inputs_misc_.apply(rc);
	interface_.apply(rc);
	language_.apply(rc);
	lnf_misc_.apply(rc);
	identity_.apply(rc);
	outputs_misc_.apply(rc);
	paths_.apply(rc);
	printer_.apply(rc);
	screen_fonts_.apply(rc);
	spelloptions_.apply(rc);

	// The "Save" button has been pressed.
	if (dialog().isClosing() && colors_.modifiedXformsPrefs) {
		string const filename =
			AddName(package().user_support(), "preferences.xform");
		colors_.modifiedXformsPrefs = !XformsColor::write(filename);
	}
}


string const FormPreferences::getFeedback(FL_OBJECT * ob)
{
	BOOST_ASSERT(ob);

	if (ob->form->fdui == colors_.dialog())
		return colors_.feedback(ob);
	if (ob->form->fdui == converters_.dialog())
		return converters_.feedback(ob);
	if (ob->form->fdui == copiers_.dialog())
		return copiers_.feedback(ob);
	if (ob->form->fdui == formats_.dialog())
		return formats_.feedback(ob);
	if (ob->form->fdui == inputs_misc_.dialog())
		return inputs_misc_.feedback(ob);
	if (ob->form->fdui == interface_.dialog())
		return interface_.feedback(ob);
	if (ob->form->fdui == language_.dialog())
		return language_.feedback(ob);
	if (ob->form->fdui == lnf_misc_.dialog())
		return lnf_misc_.feedback(ob);
	if (ob->form->fdui == outputs_misc_.dialog())
		return outputs_misc_.feedback(ob);
	if (ob->form->fdui == paths_.dialog())
		return paths_.feedback(ob);
	if (ob->form->fdui == printer_.dialog())
		return printer_.feedback(ob);
	if (ob->form->fdui == screen_fonts_.dialog())
		return screen_fonts_.feedback(ob);
	if (ob->form->fdui == spelloptions_.dialog())
		return spelloptions_.feedback(ob);

	return string();
}


ButtonPolicy::SMInput FormPreferences::input(FL_OBJECT * ob, long)
{
	BOOST_ASSERT(ob);

	bool valid = true;

	// whatever checks you need to ensure the user hasn't entered
	// some totally ridiculous value somewhere.  Change activate to suit.
	// comments before each test describe what is _valid_

	if (ob->form->fdui == colors_.dialog()) {
		colors_.input(ob);
	} else if (ob->form->fdui == converters_.dialog()) {
		valid = converters_.input(ob);
	} else if (ob->form->fdui == copiers_.dialog()) {
		valid = copiers_.input(ob);
	} else if (ob->form->fdui == formats_.dialog()) {
		valid = formats_.input(ob);
	} else if  (ob->form->fdui == interface_.dialog()) {
		valid = interface_.input(ob);
	} else if  (ob->form->fdui == language_.dialog()) {
		valid = language_.input(ob);
	} else if  (ob->form->fdui == paths_.dialog()) {
		valid = paths_.input(ob);
	} else if  (ob->form->fdui == screen_fonts_.dialog()) {
		valid = screen_fonts_.input();
	} else if  (ob->form->fdui == spelloptions_.dialog()) {
		valid = spelloptions_.input(ob);
	}

	return valid ? ButtonPolicy::SMI_VALID : ButtonPolicy::SMI_INVALID;
}


void FormPreferences::update()
{
	if (!dialog_.get()) return;

	LyXRC const & rc(controller().rc());

	// read lyxrc entries
	colors_.update();
	formats_.update();   // Must be before converters_.update()
	converters_.update();
	copiers_.update();
	inputs_misc_.update(rc);
	interface_.update(rc);
	language_.update(rc);
	lnf_misc_.update(rc);
	identity_.update(rc);
	outputs_misc_.update(rc);
	paths_.update(rc);
	printer_.update(rc);
	screen_fonts_.update(rc);
	spelloptions_.update(rc);
}


FormPreferences::Colors::Colors(FormPreferences & p)
	: modifiedXformsPrefs(false), parent_(p)
{}


FD_preferences_colors const * FormPreferences::Colors::dialog()
{
	return dialog_.get();
}


void FormPreferences::Colors::apply()
{
	bool modifiedText = false;
	bool modifiedBackground = false;

	for (vector<XformsColor>::const_iterator cit = xformsColorDB.begin();
	     cit != xformsColorDB.end(); ++cit) {
		RGBColor col;
		fl_getmcolor(cit->colorID, &col.r, &col.g, &col.b);
		if (col != cit->color()) {
			modifiedXformsPrefs = true;
			if (cit->colorID == FL_BLACK)
				modifiedText = true;
			if (cit->colorID == FL_COL1)
				modifiedBackground = true;
		}
	}

	if (modifiedXformsPrefs) {
		for (vector<XformsColor>::const_iterator cit =
			     xformsColorDB.begin();
		     cit != xformsColorDB.end(); ++cit) {
			fl_mapcolor(cit->colorID, cit->r, cit->g, cit->b);

			if (modifiedText && cit->colorID == FL_BLACK) {
				AdjustVal(FL_INACTIVE, FL_BLACK, 0.5);
			}

			if (modifiedBackground && cit->colorID == FL_COL1) {
				AdjustVal(FL_MCOL,      FL_COL1, 0.1);
				AdjustVal(FL_TOP_BCOL,  FL_COL1, 0.1);
				AdjustVal(FL_LEFT_BCOL, FL_COL1, 0.1);

				AdjustVal(FL_RIGHT_BCOL,  FL_COL1, -0.5);
				AdjustVal(FL_BOTTOM_BCOL, FL_COL1, -0.5);
			}

			if (cit->colorID == GUI_COLOR_CURSOR) {
				fl_mapcolor(GUI_COLOR_CURSOR,
					    cit->r, cit->g, cit->b);
				setCursorColor(GUI_COLOR_CURSOR);
			}
		}
		parent_.controller().redrawGUI();
	}

	// Now do the same for the LyX LColors...
	for (vector<NamedColor>::const_iterator cit = lyxColorDB.begin();
	     cit != lyxColorDB.end(); ++cit) {
		LColor::color lc = lcolor.getFromLyXName(cit->lyxname);
		if (lc == LColor::inherit) continue;

		// Create a valid X11 name of the form "#rrggbb"
		string const hexname = X11hexname(cit->color());

		if (lcolor.getX11Name(lc) != hexname) {
			lyxerr[Debug::GUI]
				<< "FormPreferences::Colors::apply: "
				<< "resetting LColor " << lcolor.getGUIName(lc)
				<< " from \"" << lcolor.getX11Name(lc)
				<< "\" to \"" << hexname << "\"."
				<< endl;

			parent_.controller().setColor(lc, hexname);
		}
	}
}


void FormPreferences::Colors::build()
{
	picker_.reset(new FormColorpicker);
	dialog_.reset(build_preferences_colors(&parent_));

	fl_set_object_color(dialog_->button_color,
			    GUI_COLOR_CHOICE, GUI_COLOR_CHOICE);

	// set up the feedback mechanism
	setPrehandler(dialog_->browser_lyx_objs);
	setPrehandler(dialog_->button_color);
	setPrehandler(dialog_->button_modify);
}


string const
FormPreferences::Colors::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->browser_lyx_objs)
		return _("LyX objects that can be assigned a color.");

	if (ob == dialog_->button_modify)
		return _("Modify the LyX object's color. Note: you must then \"Apply\" the change.");

	return string();
}


void FormPreferences::Colors::input(FL_OBJECT const * const ob)
{
	if (ob == dialog_->browser_lyx_objs) {
		InputBrowserLyX();

	} else if (ob == dialog_->button_modify) {
		Modify();
	}
}


void FormPreferences::Colors::AdjustVal(int colAdjust, int colParent,
					double addVal) const
{
	RGBColor rgb;
	fl_getmcolor(colParent, &rgb.r, &rgb.g, &rgb.b);

	HSVColor hsv(rgb);
	hsv.v += addVal;
	hsv.v = min(1.0, max(0.0, hsv.v));

	rgb = RGBColor(hsv);
	fl_mapcolor(colAdjust, rgb.r, rgb.g, rgb.b);
}


void FormPreferences::Colors::InputBrowserLyX() const
{
	vector<NamedColor>::size_type const selLyX =
		fl_get_browser(dialog_->browser_lyx_objs);
	if (selLyX < 1) return;

	// Is the choice an Xforms color...
	RGBColor col;

	if (selLyX - 1 < xformsColorDB.size()) {
		vector<XformsColor>::size_type const i = selLyX - 1;
		col = xformsColorDB[i].color();
	}
	// or a LyX Logical color?
	else {
		vector<NamedColor>::size_type const i = selLyX - 1 -
			xformsColorDB.size();
		col = lyxColorDB[i].color();
	}

	fl_freeze_form(dialog_->form);

	fl_mapcolor(GUI_COLOR_CHOICE, col.r, col.g, col.b);
	fl_redraw_object(dialog_->button_color);

	fl_unfreeze_form(dialog_->form);
}


void FormPreferences::Colors::LoadBrowserLyX()
{
	if (!dialog_->browser_lyx_objs->visible)
		return;

	// First, define the modifiable xforms colors
	xformsColorDB.clear();
	XformsColor xcol;

	xcol.lyxname = "GUI background";
	xcol.guiname = _("GUI background");
	xcol.colorID = FL_COL1;
	fl_getmcolor(FL_COL1, &xcol.r, &xcol.g, &xcol.b);

	xformsColorDB.push_back(xcol);

	xcol.lyxname = "GUI text";
	xcol.guiname = _("GUI text");
	xcol.colorID = FL_BLACK;
	fl_getmcolor(FL_BLACK, &xcol.r, &xcol.g, &xcol.b);

	xformsColorDB.push_back(xcol);

	xcol.lyxname = "GUI selection";
	xcol.guiname = _("GUI selection");
	xcol.colorID = FL_YELLOW;
	fl_getmcolor(FL_YELLOW, &xcol.r, &xcol.g, &xcol.b);

	xformsColorDB.push_back(xcol);

	xcol.lyxname = "GUI pointer";
	xcol.guiname = _("GUI pointer");
	xcol.colorID = GUI_COLOR_CURSOR;
	fl_getmcolor(GUI_COLOR_CURSOR, &xcol.r, &xcol.g, &xcol.b);

	xformsColorDB.push_back(xcol);

	// Now create the the LyX LColors database
	lyxColorDB.clear();
	for (int i=0; i<LColor::ignore; ++i) {
		LColor::color lc = static_cast<LColor::color>(i);
		if (lc == LColor::none
		    || lc == LColor::black
		    || lc == LColor::white
		    || lc == LColor::red
		    || lc == LColor::green
		    || lc == LColor::blue
		    || lc == LColor::cyan
		    || lc == LColor::magenta
		    || lc == LColor::yellow
		    || lc == LColor::inherit
		    || lc == LColor::ignore) continue;

		RGBColor col;
		bool const success = getRGBColor(lc, col.r, col.g, col.b);
		if (!success) {
			lyxerr << "FormPreferences::Colors::LoadBrowserLyX:\n"
			       << "LColor " << lcolor.getLyXName(lc)
			       << ": X can't find color \""
			       << lcolor.getX11Name(lc)
			       << "\". Set to \"black\"!" << endl;

			string const arg = lcolor.getLyXName(lc) + " black";
			parent_.controller().setColor(lc, "black");
			continue;
		}

		// Create a valid X11 name of the form "#rrggbb" and change the
		// LColor X11name to this. Don't want to trigger a redraw,
		// as we're just changing the name not the RGB values.
		// Also reset the system_lcolor names, so that we don't output
		// unnecessary changes.
		string const hexname = X11hexname(col);

		if (lcolor.getX11Name(lc) != hexname) {
			lcolor.setColor(lc, hexname);
			system_lcolor.setColor(lc, hexname);
		}

		// Finally, push the color onto the database
		NamedColor ncol(lcolor.getLyXName(lc), lcolor.getGUIName(lc), col);
		lyxColorDB.push_back(ncol);
	}

	// Now construct the browser
	FL_OBJECT * colbr = dialog_->browser_lyx_objs;
	fl_freeze_form(dialog_->form);
	fl_clear_browser(colbr);
	for (vector<XformsColor>::const_iterator cit = xformsColorDB.begin();
	     cit != xformsColorDB.end(); ++cit) {
		fl_addto_browser(colbr, cit->guiname.c_str());
	}
	for (vector<NamedColor>::const_iterator cit = lyxColorDB.begin();
	     cit != lyxColorDB.end(); ++cit) {
		fl_addto_browser(colbr, cit->guiname.c_str());
	}

	// just to be safe...
	fl_set_browser_topline(dialog_->browser_lyx_objs, 1);
	fl_select_browser_line(dialog_->browser_lyx_objs, 1);
	fl_unfreeze_form(dialog_->form);

	InputBrowserLyX();
}


void FormPreferences::Colors::Modify()
{
	vector<NamedColor>::size_type const selLyX =
		fl_get_browser(dialog_->browser_lyx_objs);
	if (selLyX < 1)
		return;

	RGBColor before;
	fl_getmcolor(GUI_COLOR_CHOICE, &before.r, &before.g, &before.b);

	RGBColor col = picker_->requestColor(before);
	if (before == col)
		return;

	fl_mapcolor(GUI_COLOR_CHOICE, col.r, col.g, col.b);
	fl_redraw_object(dialog_->button_color);

	// Is the choice an Xforms color...
	if (selLyX - 1 < xformsColorDB.size()) {
		vector<XformsColor>::size_type const i = selLyX - 1;
		xformsColorDB[i].r  = col.r;
		xformsColorDB[i].g  = col.g;
		xformsColorDB[i].b  = col.b;
	}
	// or a LyX Logical color?
	else {
		vector<NamedColor>::size_type const i = selLyX - 1 -
			xformsColorDB.size();
		lyxColorDB[i].r  = col.r;
		lyxColorDB[i].g  = col.g;
		lyxColorDB[i].b  = col.b;
	}
}


FormPreferences::Converters::Converters(FormPreferences & p)
	: parent_(p)
{}


FD_preferences_converters const * FormPreferences::Converters::dialog()
{
	return dialog_.get();
}


::Converters & FormPreferences::Converters::converters()
{
	return parent_.controller().converters();
}


::Formats & FormPreferences::Converters::formats()
{
	return parent_.controller().formats();
}


void FormPreferences::Converters::build()
{
	dialog_.reset(build_preferences_converters(&parent_));

	fl_set_input_return(dialog_->input_converter, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_flags, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->browser_all);
	setPrehandler(dialog_->button_delete);
	setPrehandler(dialog_->button_add);
	setPrehandler(dialog_->input_converter);
	setPrehandler(dialog_->choice_from);
	setPrehandler(dialog_->choice_to);
	setPrehandler(dialog_->input_flags);
}


string const
FormPreferences::Converters::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->browser_all)
		return _("All explicitly defined converters for LyX");

	if (ob == dialog_->choice_from)
		return _("Convert \"from\" this format");

	if (ob == dialog_->choice_to)
		return _("Convert \"to\" this format");

	if (ob == dialog_->input_converter)
		return _("The conversion command. $$i is the input file name, "
			 "$$b is the file name without its extension and $$o "
			 "is the name of the output file. $$s can be used "
			 "as the path to the user/library directory.");

	if (ob == dialog_->input_flags)
		return _("Extra information for the Converter class, e.g., whether and "
			 "how to parse the result.");

	if (ob == dialog_->button_delete)
		return _("Remove the current converter from the list of available "
			 "converters. Note: you must then \"Apply\" the change.");

	if (ob == dialog_->button_add) {
		if (string(ob->label) == _("Add"))
			return _("Add the current converter to the list of available "
				 "converters. Note: you must then \"Apply\" the change.");
		else
			return _("Modify the contents of the current converter. "
				 "Note: you must then \"Apply\" the change.");
	}

	return string();
}


bool FormPreferences::Converters::input(FL_OBJECT const * const ob)
{
	if (ob == dialog_->browser_all)
		return Browser();

	if (ob == dialog_->choice_from
	    || ob == dialog_->choice_to
	    || ob == dialog_->input_converter
	    || ob == dialog_->input_flags)
		return Input();

	if (ob == dialog_->button_add)
		return Add();

	if (ob == dialog_->button_delete)
		return erase();

	return true;
}


void FormPreferences::Converters::update()
{
	UpdateBrowser();
}


void FormPreferences::Converters::UpdateBrowser()
{
	converters().sort();

	fl_freeze_form(dialog_->form);
	fl_clear_browser(dialog_->browser_all);
	for (::Converters::const_iterator cit = converters().begin();
	     cit != converters().end(); ++cit) {
		string const name = cit->From->prettyname() + " -> "
			+ cit->To->prettyname();
		fl_addto_browser(dialog_->browser_all, name.c_str());
	}
	Input();
	fl_unfreeze_form(dialog_->form);
}


bool FormPreferences::Converters::Add()
{
	string const from = GetFrom();
	string const to = GetTo();
	string const command = getString(dialog_->input_converter);
	string const flags = getString(dialog_->input_flags);

	Converter const * old = converters().getConverter(from, to);
	converters().add(from, to, command, flags);
	if (!old) {
		converters().updateLast(formats());
		UpdateBrowser();
	}
	setEnabled(dialog_->button_add, false);

	return true;
}


bool FormPreferences::Converters::Browser()
{
	int const i = fl_get_browser(dialog_->browser_all);
	if (i <= 0) return false;

	fl_freeze_form(dialog_->form);

	Converter const & c = converters().get(i - 1);
	int j = formats().getNumber(c.from);
	if (j >= 0)
		fl_set_choice(dialog_->choice_from, j + 1);

	j = formats().getNumber(c.to);
	if (j >= 0)
		fl_set_choice(dialog_->choice_to, j + 1);

	fl_set_input(dialog_->input_converter, c.command.c_str());
	fl_set_input(dialog_->input_flags, c.flags.c_str());

	fl_set_object_label(dialog_->button_add, idex(_("Modify|#M")).c_str());
	fl_set_button_shortcut(dialog_->button_add,
			       scex(_("Modify|#M")).c_str(), 1);

	setEnabled(dialog_->button_add,    false);
	setEnabled(dialog_->button_delete, true);

	fl_unfreeze_form(dialog_->form);
	return false;
}


bool FormPreferences::Converters::erase()
{
	string const from = GetFrom();
	string const to = GetTo();

	converters().erase(from, to);
	UpdateBrowser();
	return true;
}


bool FormPreferences::Converters::Input()
{
	string const from = GetFrom();
	string const to = GetTo();
	int const sel = converters().getNumber(from, to);

	fl_freeze_form(dialog_->form);

	if (sel < 0) {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Add|#A")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Add|#A")).c_str(), 1);

		fl_deselect_browser(dialog_->browser_all);
		setEnabled(dialog_->button_delete, false);

	} else {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Modify|#M")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Modify|#M")).c_str(), 1);

		int top = max(sel-5, 0);
		fl_set_browser_topline(dialog_->browser_all, top);
		fl_select_browser_line(dialog_->browser_all, sel+1);
		setEnabled(dialog_->button_delete, true);
	}

	string const command = rtrim(getString(dialog_->input_converter));
	bool const enable = !(command.empty() || from == to);
	setEnabled(dialog_->button_add, enable);

	fl_unfreeze_form(dialog_->form);
	return false;
}


string const FormPreferences::Converters::GetFrom()
{
	::Formats::FormatList::size_type const i =
		  fl_get_choice(dialog_->choice_from);

	if (i > 0 && i <= formats().size())
		return formats().get(i - 1).name();

	lyxerr << "FormPreferences::Converters::GetFrom: No choice!" << endl;
	return "???";
}


string const FormPreferences::Converters::GetTo()
{
	::Formats::FormatList::size_type const i =
		  fl_get_choice(dialog_->choice_to);

	if (i > 0 && i <= formats().size())
		return formats().get(i - 1).name();

	lyxerr << "FormPreferences::Converters::GetTo: No choice!" << endl;
	return "???";
}


void FormPreferences::Converters::UpdateChoices()
{
	string choice;
	for (::Formats::const_iterator cit = formats().begin();
	     cit != formats().end(); ++cit) {
		if (!choice.empty())
			choice += " | ";
		else
			choice += ' ';
		choice += cit->prettyname();
	}
	choice += ' ';

	fl_clear_choice(dialog_->choice_from);
	fl_addto_choice(dialog_->choice_from, choice.c_str());

	fl_clear_choice(dialog_->choice_to);
	fl_addto_choice(dialog_->choice_to, choice.c_str());
}


FormPreferences::Copiers::Copiers(FormPreferences & p)
	: parent_(p)
{}


FD_preferences_copiers const * FormPreferences::Copiers::dialog()
{
	return dialog_.get();
}


::Movers & FormPreferences::Copiers::movers()
{
	return parent_.controller().movers();
}


void FormPreferences::Copiers::build()
{
	dialog_.reset(build_preferences_copiers(&parent_));

	fl_set_input_return(dialog_->input_copier, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->browser_all);
	setPrehandler(dialog_->button_delete);
	setPrehandler(dialog_->button_add);
	setPrehandler(dialog_->choice_format);
	setPrehandler(dialog_->input_copier);
}


string const
FormPreferences::Copiers::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->browser_all)
		return _("All explicitly defined copiers for LyX");

	if (ob == dialog_->choice_format)
		return _("Copier for this format");

	if (ob == dialog_->input_copier)

		return _("The command used to copy the file. "
			 "$$i is the \"from\" file name and "
			 "$$o is the \"to\" file name.\n"
			 "$$s can be used as the path to the user/library "
			 "directory.");

	if (ob == dialog_->button_delete)
		return _("Remove the current copier from the list of available "
			 "copiers. Note: you must then \"Apply\" the change.");

	if (ob == dialog_->button_add) {
		if (string(ob->label) == _("Add"))
			return _("Add the current copier to the list of available "
				 "copiers. Note: you must then \"Apply\" the change.");
		else
			return _("Modify the contents of the current copier. "
				 "Note: you must then \"Apply\" the change.");
	}

	return string();
}


bool FormPreferences::Copiers::input(FL_OBJECT const * const ob)
{
	if (ob == dialog_->browser_all)
		return Browser();

	if (ob == dialog_->choice_format
	    || ob == dialog_->input_copier)
		return Input();

	if (ob == dialog_->button_add)
		return Add();

	if (ob == dialog_->button_delete)
		return Erase();

	return true;
}


void FormPreferences::Copiers::update()
{
	// Build data for the browser widget
	Movers::iterator const begin = movers().begin();
	Movers::iterator const end = movers().end();

	vector<string> fmts;
	fmts.reserve(std::distance(begin, end));
	for (Movers::iterator it = begin; it != end; ++it) {
		std::string const & command = it->second.command();
		if (command.empty())
			continue;
		std::string const & fmt = it->first;
		fmts.push_back(::formats.prettyName(fmt));
	}

	std::sort(fmts.begin(), fmts.end());

	// Build data for the choice widget
	string choice;
	for (::Formats::const_iterator it = ::formats.begin();
	     it != ::formats.end(); ++it) {
		if (!choice.empty())
			choice += " | ";
		else
			choice += ' ';
		choice += it->prettyname();
	}
	choice += ' ';

	// The input widget
	fl_freeze_form(dialog_->form);
	fl_set_input(dialog_->input_copier, "");

	// The browser widget
	fl_clear_browser(dialog_->browser_all);

	vector<string>::const_iterator it = fmts.begin();
	vector<string>::const_iterator const fmts_end = fmts.end();
	for (; it != fmts_end; ++it)
		fl_addto_browser(dialog_->browser_all, it->c_str());

	// The choice widget
	fl_clear_choice(dialog_->choice_format);
	fl_addto_choice(dialog_->choice_format, choice.c_str());
	fl_set_choice(dialog_->choice_format, 1);

	Input();
	fl_unfreeze_form(dialog_->form);
}


namespace {

struct SamePrettyName {
	SamePrettyName(string const & n) : pretty_name_(n) {}

	bool operator()(::Format const & fmt) const {
		return fmt.prettyname() == pretty_name_;
	}

private:
	string const pretty_name_;
};


::Format const * getFormat(std::string const & prettyname)
{
	::Formats::const_iterator it = ::formats.begin();
	::Formats::const_iterator const end = ::formats.end();
	it = std::find_if(it, end, SamePrettyName(prettyname));
	return it == end ? 0 : &*it;
}

} // namespace anon


bool FormPreferences::Copiers::Add()
{
	::Format const * fmt = getFormat(getString(dialog_->choice_format));
	if (fmt == 0)
		return false;

	string const command = getString(dialog_->input_copier);
	if (command.empty())
		return false;

	fl_freeze_form(dialog_->form);

	movers().set(fmt->name(), command);
	update();
	setEnabled(dialog_->button_add, false);

	fl_unfreeze_form(dialog_->form);
	return true;
}


bool FormPreferences::Copiers::Browser()
{
	int const i = fl_get_browser(dialog_->browser_all);
	if (i <= 0) return false;

	::Format const * fmt = getFormat(getString(dialog_->browser_all, i));
	if (fmt == 0)
		return false;

	string const & fmt_name = fmt->name();
	string const & gui_name = fmt->prettyname();
	string const & command = movers().command(fmt_name);

	fl_freeze_form(dialog_->form);

	int const choice_size = fl_get_choice_maxitems(dialog_->choice_format);
	for (int i = 1; i <= choice_size; ++i) {
		char const * const c_str =
			fl_get_choice_item_text(dialog_->choice_format, i);
		string const line = c_str ? trim(c_str) : string();
		if (line == gui_name) {
			fl_set_choice(dialog_->choice_format, i);
			break;
		}
	}

	fl_set_input(dialog_->input_copier, command.c_str());

	fl_set_object_label(dialog_->button_add, idex(_("Modify|#M")).c_str());
	fl_set_button_shortcut(dialog_->button_add,
			       scex(_("Modify|#M")).c_str(), 1);

	setEnabled(dialog_->button_add,    false);
	setEnabled(dialog_->button_delete, true);

	fl_unfreeze_form(dialog_->form);
	return false;
}


bool FormPreferences::Copiers::Erase()
{
	::Format const * fmt = getFormat(getString(dialog_->choice_format));
	if (fmt == 0)
		return false;

	string const & fmt_name = fmt->name();

	movers().set(fmt_name, string());
	update();
	return true;
}


bool FormPreferences::Copiers::Input()
{
	::Format const * fmt = getFormat(getString(dialog_->choice_format));
	if (fmt == 0)
		return false;

	string const & gui_name = fmt->prettyname();
	string const command = getString(dialog_->input_copier);

	fl_freeze_form(dialog_->form);
	fl_deselect_browser(dialog_->browser_all);
	bool found_line = false;
	int const browser_size = fl_get_browser_maxline(dialog_->browser_all);
	for (int i = 1; i <= browser_size; ++i) {
		char const * const c_str =
			fl_get_browser_line(dialog_->browser_all, i);
		string const line = c_str ? trim(c_str) : string();
		if (line == gui_name) {
			fl_select_browser_line(dialog_->browser_all, i);
			int top = max(i-5, 1);
			fl_set_browser_topline(dialog_->browser_all, top);
			found_line = true;
			break;
		}
	}

	if (!found_line) {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Add|#A")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Add|#A")).c_str(), 1);

		setEnabled(dialog_->button_delete, false);
	} else {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Modify|#M")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Modify|#M")).c_str(), 1);

		setEnabled(dialog_->button_delete, true);
	}

	setEnabled(dialog_->button_add, !command.empty());

	fl_unfreeze_form(dialog_->form);
	return false;
}


FormPreferences::Formats::Formats(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_formats const * FormPreferences::Formats::dialog()
{
	return dialog_.get();
}


::Converters & FormPreferences::Formats::converters()
{
	return parent_.controller().converters();
}


::Formats & FormPreferences::Formats::formats()
{
	return parent_.controller().formats();
}


void FormPreferences::Formats::build()
{
	dialog_.reset(build_preferences_formats(&parent_));

	fl_set_input_return(dialog_->input_format, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_viewer, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_editor, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_shrtcut, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_gui_name, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_extension, FL_RETURN_CHANGED);

	fl_set_input_filter(dialog_->input_format, fl_lowercase_filter);

	// set up the feedback mechanism
	setPrehandler(dialog_->browser_all);
	setPrehandler(dialog_->input_format);
	setPrehandler(dialog_->input_gui_name);
	setPrehandler(dialog_->button_delete);
	setPrehandler(dialog_->button_add);
	setPrehandler(dialog_->input_extension);
	setPrehandler(dialog_->input_viewer);
	setPrehandler(dialog_->input_editor);
	setPrehandler(dialog_->input_shrtcut);
}


string const
FormPreferences::Formats::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->browser_all)
		return  _("All the currently defined formats known to LyX.");

	if (ob == dialog_->input_format)
		return  _("The format identifier.");

	if (ob == dialog_->input_gui_name)
		return  _("The format name as it will appear in the menus.");

	if (ob == dialog_->input_shrtcut)
		return  _("The keyboard accelerator. Use a letter in the GUI name. "
			  "Case sensitive.");

	if (ob == dialog_->input_extension)
		return  _("Used to recognize the file. E.g., ps, pdf, tex.");

	if (ob == dialog_->input_viewer)
		return  _("The command used to launch the viewer application.");

	if (ob == dialog_->input_editor)
		return  _("The command used to launch the editor application.");

	if (ob == dialog_->button_delete)
		return  _("Remove the current format from the list of available "
			  "formats. Note: you must then \"Apply\" the change.");

	if (ob == dialog_->button_add) {
		if (string(ob->label) == _("Add"))
			return  _("Add the current format to the list of available "
				  "formats. Note: you must then \"Apply\" the change.");
		else
			return  _("Modify the contents of the current format. Note: "
				  "you must then \"Apply\" the change.");
	}

	return string();
}


bool FormPreferences::Formats::input(FL_OBJECT const * const ob)
{
	if (ob == dialog_->browser_all)
		return Browser();

	if (ob == dialog_->input_format
	    || ob == dialog_->input_gui_name
	    || ob == dialog_->input_shrtcut
	    || ob == dialog_->input_extension
	    || ob == dialog_->input_viewer
	    || ob == dialog_->input_editor)
		return Input();

	if (ob == dialog_->button_add)
		return Add();

	if (ob == dialog_->button_delete)
		return erase();

	return false;
}


void FormPreferences::Formats::update()
{
	UpdateBrowser();
}


void FormPreferences::Formats::UpdateBrowser()
{
	formats().sort();

	fl_freeze_form(dialog_->form);
	fl_deselect_browser(dialog_->browser_all);
	fl_clear_browser(dialog_->browser_all);
	for (::Formats::const_iterator cit = formats().begin();
	     cit != formats().end(); ++cit)
		fl_addto_browser(dialog_->browser_all,
				 cit->prettyname().c_str());

	Input();
	fl_unfreeze_form(dialog_->form);

	// Mustn't forget to update the Formats available to the converters_
	parent_.converters_.UpdateChoices();
	converters().update(formats());
}


bool FormPreferences::Formats::Add()
{
	string const name = getString(dialog_->input_format);
	string const prettyname = getString(dialog_->input_gui_name);
	string const extension = getString(dialog_->input_extension);
	string const shortcut =  getString(dialog_->input_shrtcut);
	string const viewer =  getString(dialog_->input_viewer);
	string const editor =  getString(dialog_->input_editor);

	Format const * old = formats().getFormat(name);
	string const old_prettyname = old ? old->prettyname() : string();
	formats().add(name, extension, prettyname, shortcut, viewer, editor);
	if (!old || prettyname != old_prettyname) {
		UpdateBrowser();
		if (old)
			parent_.converters_.UpdateBrowser();
	}
	setEnabled(dialog_->button_add, false);

	return true;
}


bool FormPreferences::Formats::Browser()
{
	int const i = fl_get_browser(dialog_->browser_all);
	if (i <= 0)
		return false;

	fl_freeze_form(dialog_->form);

	Format const & f = formats().get(i - 1);

	fl_set_input(dialog_->input_format, f.name().c_str());
	fl_set_input(dialog_->input_gui_name, f.prettyname().c_str());
	fl_set_input(dialog_->input_shrtcut, f.shortcut().c_str());
	fl_set_input(dialog_->input_extension, f.extension().c_str());
	fl_set_input(dialog_->input_viewer, f.viewer().c_str());
	fl_set_input(dialog_->input_editor, f.editor().c_str());

	fl_set_object_label(dialog_->button_add,
			    idex(_("Modify|#M")).c_str());
	fl_set_button_shortcut(dialog_->button_add,
			       scex(_("Modify|#M")).c_str(), 1);

	setEnabled(dialog_->button_add,    false);
	setEnabled(dialog_->button_delete, true);

	fl_unfreeze_form(dialog_->form);
	return false;
}


bool FormPreferences::Formats::erase()
{
	string const name = getString(dialog_->input_format);

	if (converters().formatIsUsed(name)) {
		parent_.postWarning(_("Cannot remove a Format used by a Converter. "
				      "Remove the converter first."));
		setEnabled(dialog_->button_delete, false);
		return false;
	}

	formats().erase(name);
	UpdateBrowser();
	return true;
}


bool FormPreferences::Formats::Input()
{
	string const name = getString(dialog_->input_format);
	int const sel = formats().getNumber(name);
	fl_freeze_form(dialog_->form);

	if (sel < 0) {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Add|#A")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Add|#A")).c_str(), 1);

		fl_deselect_browser(dialog_->browser_all);
		setEnabled(dialog_->button_delete, false);

	} else {
		fl_set_object_label(dialog_->button_add,
				    idex(_("Modify|#M")).c_str());
		fl_set_button_shortcut(dialog_->button_add,
				       scex(_("Modify|#M")).c_str(), 1);

		int const top = max(sel-5, 0);
		fl_set_browser_topline(dialog_->browser_all, top);
		fl_select_browser_line(dialog_->browser_all, sel+1);

		setEnabled(dialog_->button_add, true);
		setEnabled(dialog_->button_delete, true);
	}

	string const prettyname = getString(dialog_->input_gui_name);
	bool const enable = !(name.empty() || prettyname.empty());
	setEnabled(dialog_->button_add, enable);

	fl_unfreeze_form(dialog_->form);
	return false;
}


FormPreferences::Identity::Identity(FormPreferences & p)
	: parent_(p)
{}


FD_preferences_identity const * FormPreferences::Identity::dialog()
{
	return dialog_.get();
}


void FormPreferences::Identity::apply(LyXRC & rc) const
{
	rc.user_name = getString(dialog_->input_user_name);
	rc.user_email = getString(dialog_->input_user_email);
}


void FormPreferences::Identity::build()
{
	dialog_.reset(build_preferences_identity(&parent_));
	fl_set_input_return(dialog_->input_user_name, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_user_email, FL_RETURN_CHANGED);
}


void FormPreferences::Identity::update(LyXRC const & rc)
{
	fl_set_input(dialog_->input_user_name, rc.user_name.c_str());
	fl_set_input(dialog_->input_user_email, rc.user_email.c_str());
}


FormPreferences::InputsMisc::InputsMisc(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_inputs_misc const * FormPreferences::InputsMisc::dialog()
{
	return dialog_.get();
}


void FormPreferences::InputsMisc::apply(LyXRC & rc) const
{
	rc.date_insert_format =
		getString(dialog_->input_date_format);
}


void FormPreferences::InputsMisc::build()
{
	dialog_.reset(build_preferences_inputs_misc(&parent_));

	fl_set_input_return(dialog_->input_date_format, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_date_format);
}


string const
FormPreferences::InputsMisc::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->input_date_format)
		return LyXRC::getDescription(LyXRC::RC_DATE_INSERT_FORMAT);
	return string();
}


void FormPreferences::InputsMisc::update(LyXRC const & rc)
{
	fl_set_input(dialog_->input_date_format,
		     rc.date_insert_format.c_str());
}


FormPreferences::Interface::Interface(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_interface const * FormPreferences::Interface::dialog()
{
	return dialog_.get();
}


void FormPreferences::Interface::apply(LyXRC & rc) const
{
	rc.popup_normal_font =
		getString(dialog_->input_popup_normal_font);
	rc.popup_bold_font = getString(dialog_->input_popup_bold_font);
	rc.popup_font_encoding =
		getString(dialog_->input_popup_font_encoding);
	rc.bind_file = getString(dialog_->input_bind_file);
	rc.ui_file = getString(dialog_->input_ui_file);
}


void FormPreferences::Interface::build()
{
	dialog_.reset(build_preferences_interface(&parent_));

	fl_set_input_return(dialog_->input_popup_normal_font, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_popup_bold_font, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_popup_font_encoding, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_bind_file, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_ui_file, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_popup_normal_font);
	setPrehandler(dialog_->input_popup_bold_font);
	setPrehandler(dialog_->input_popup_font_encoding);
	setPrehandler(dialog_->input_bind_file);
	setPrehandler(dialog_->button_bind_file_browse);
	setPrehandler(dialog_->input_ui_file);
	setPrehandler(dialog_->button_ui_file_browse);
}


string const
FormPreferences::Interface::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->input_popup_normal_font)
		return LyXRC::getDescription(LyXRC::RC_POPUP_NORMAL_FONT);
	if (ob == dialog_->input_popup_bold_font)
		return LyXRC::getDescription(LyXRC::RC_POPUP_BOLD_FONT);
	if (ob == dialog_->input_popup_font_encoding)
		return LyXRC::getDescription(LyXRC::RC_POPUP_FONT_ENCODING);
	if (ob == dialog_->input_bind_file)
		return LyXRC::getDescription(LyXRC::RC_BINDFILE);
	if (ob == dialog_->input_ui_file)
		return LyXRC::getDescription(LyXRC::RC_UIFILE);
	return string();
}


bool FormPreferences::Interface::input(FL_OBJECT const * const ob)
{
	if (ob == dialog_->button_bind_file_browse) {
		string f = parent_.controller().browsebind(
			getString(dialog_->input_bind_file));

		fl_set_input(dialog_->input_bind_file, f.c_str());
	} else if (ob == dialog_->button_ui_file_browse) {
		string f = parent_.controller().browseUI(
			getString(dialog_->input_ui_file));

		fl_set_input(dialog_->input_ui_file, f.c_str());
	}

	return true;
}


void FormPreferences::Interface::update(LyXRC const & rc)
{
	fl_set_input(dialog_->input_popup_normal_font,
		     rc.popup_normal_font.c_str());
	fl_set_input(dialog_->input_popup_bold_font,
		     rc.popup_bold_font.c_str());
	fl_set_input(dialog_->input_popup_font_encoding,
		     rc.popup_font_encoding.c_str());
	fl_set_input(dialog_->input_bind_file,
		     rc.bind_file.c_str());
	fl_set_input(dialog_->input_ui_file,
		     rc.ui_file.c_str());
}


FormPreferences::Language::Language(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_language const * FormPreferences::Language::dialog()
{
	return dialog_.get();
}


void FormPreferences::Language::apply(LyXRC & rc)
{
	int const pos = fl_get_combox(dialog_->combox_default_lang);
	rc.default_language = lang_[pos-1];

	int button = fl_get_button(dialog_->check_use_kbmap);
	string const name_1 = getString(dialog_->input_kbmap1);
	string const name_2 = getString(dialog_->input_kbmap2);
	if (button)
		button = !(name_1.empty() && name_2.empty());
	rc.use_kbmap = static_cast<bool>(button);

	if (rc.use_kbmap) {
		rc.primary_kbmap = name_1;
		rc.secondary_kbmap = name_2;
	}

	button = fl_get_button(dialog_->check_rtl_support);
	rc.rtl_support = static_cast<bool>(button);

	button = fl_get_button(dialog_->check_mark_foreign);
	rc.mark_foreign_language = static_cast<bool>(button);

	button = fl_get_button(dialog_->check_auto_begin);
	rc.language_auto_begin = static_cast<bool>(button);

	button = fl_get_button(dialog_->check_auto_end);
	rc.language_auto_end = static_cast<bool>(button);

	button = fl_get_button(dialog_->check_use_babel);
	rc.language_use_babel = static_cast<bool>(button);

	button = fl_get_button(dialog_->check_global_options);
	rc.language_global_options = static_cast<bool>(button);

	rc.language_package = getString(dialog_->input_package);
	rc.language_command_begin = getString(dialog_->input_command_begin);
	rc.language_command_end = getString(dialog_->input_command_end);

	// Ensure that all is self-consistent.
	update(rc);
}


void FormPreferences::Language::build()
{
	dialog_.reset(build_preferences_language(&parent_));

	fl_set_input_return(dialog_->input_package, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_command_begin, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_command_end, FL_RETURN_CHANGED);

	// Store the lang identifiers for later
	vector<LanguagePair> const langs = getLanguageData(false);
	lang_ = getSecond(langs);

	FL_OBJECT * obj = dialog_->combox_default_lang;
	vector<LanguagePair>::const_iterator lit  = langs.begin();
	vector<LanguagePair>::const_iterator lend = langs.end();
	for (; lit != lend; ++lit) {
		fl_addto_combox(obj, lit->first.c_str());
	}
	fl_set_combox_browser_height(obj, 400);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_package);
	setPrehandler(dialog_->check_use_kbmap);
	setPrehandler(dialog_->combox_default_lang);
	setPrehandler(dialog_->input_kbmap1);
	setPrehandler(dialog_->input_kbmap2);
	setPrehandler(dialog_->check_rtl_support);
	setPrehandler(dialog_->check_mark_foreign);
	setPrehandler(dialog_->check_auto_begin);
	setPrehandler(dialog_->check_auto_end);
	setPrehandler(dialog_->check_use_babel);
	setPrehandler(dialog_->check_global_options);
	setPrehandler(dialog_->input_command_begin);
	setPrehandler(dialog_->input_command_end);

	// Activate/Deactivate the input fields dependent on the state of the
	// buttons.
	input(0);
}


string const
FormPreferences::Language::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->combox_default_lang)
		return LyXRC::getDescription(LyXRC::RC_DEFAULT_LANGUAGE);
	if (ob == dialog_->check_use_kbmap)
		return LyXRC::getDescription(LyXRC::RC_KBMAP);
	if (ob == dialog_->input_kbmap1)
		return LyXRC::getDescription(LyXRC::RC_KBMAP_PRIMARY);
	if (ob == dialog_->input_kbmap2)
		return LyXRC::getDescription(LyXRC::RC_KBMAP_SECONDARY);
	if (ob == dialog_->check_rtl_support)
		return LyXRC::getDescription(LyXRC::RC_RTL_SUPPORT);
	if (ob == dialog_->check_mark_foreign)
		return LyXRC::getDescription(LyXRC::RC_MARK_FOREIGN_LANGUAGE);
	if (ob == dialog_->check_auto_begin)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_AUTO_BEGIN);
	if (ob == dialog_->check_auto_end)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_AUTO_END);
	if (ob == dialog_->check_use_babel)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_USE_BABEL);
	if (ob == dialog_->check_global_options)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS);
	if (ob == dialog_->input_package)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_PACKAGE);
	if (ob == dialog_->input_command_begin)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_COMMAND_BEGIN);
	if (ob == dialog_->input_command_end)
		return LyXRC::getDescription(LyXRC::RC_LANGUAGE_COMMAND_END);
	return string();
}


bool FormPreferences::Language::input(FL_OBJECT const * const ob)
{
	bool activate = true;

	// !ob if function is called from Language::build() to de/activate
	// objects,
	// otherwise the function is called by an xforms CB via input().
	if (!ob || ob == dialog_->check_use_kbmap) {
		bool const enable = fl_get_button(dialog_->check_use_kbmap);
		setEnabled(dialog_->button_kbmap1_browse, enable);
		setEnabled(dialog_->button_kbmap2_browse, enable);
		setEnabled(dialog_->input_kbmap1, enable);
		setEnabled(dialog_->input_kbmap2, enable);
	}

	if (ob == dialog_->button_kbmap1_browse) {
		string f = parent_.controller().browsekbmap(
			getString(dialog_->input_kbmap1));

		fl_set_input(dialog_->input_kbmap1, f.c_str());
	} else if (ob == dialog_->button_kbmap2_browse) {
		string f = parent_.controller().browsekbmap(
			getString(dialog_->input_kbmap2));

		fl_set_input(dialog_->input_kbmap2, f.c_str());
	}

	return activate;
}


void FormPreferences::Language::update(LyXRC const & rc)
{
	fl_set_button(dialog_->check_use_kbmap,
		      rc.use_kbmap);

	int const pos = int(findPos(lang_, rc.default_language));
	fl_set_combox(dialog_->combox_default_lang, pos + 1);

	if (rc.use_kbmap) {
		fl_set_input(dialog_->input_kbmap1,
			     rc.primary_kbmap.c_str());
		fl_set_input(dialog_->input_kbmap2,
			     rc.secondary_kbmap.c_str());
	} else {
		fl_set_input(dialog_->input_kbmap1, "");
		fl_set_input(dialog_->input_kbmap2, "");
	}

	fl_set_button(dialog_->check_rtl_support, rc.rtl_support);
	fl_set_button(dialog_->check_mark_foreign,
		      rc.mark_foreign_language);
	fl_set_button(dialog_->check_auto_begin, rc.language_auto_begin);
	fl_set_button(dialog_->check_auto_end, rc.language_auto_end);
	fl_set_button(dialog_->check_use_babel, rc.language_use_babel);
	fl_set_button(dialog_->check_global_options,
		      rc.language_global_options);

	fl_set_input(dialog_->input_package,
		     rc.language_package.c_str());
	fl_set_input(dialog_->input_command_begin,
		     rc.language_command_begin.c_str());
	fl_set_input(dialog_->input_command_end,
		     rc.language_command_end.c_str());

	// Activate/Deactivate the input fields dependent on the state of the
	// buttons.
	input(0);
}


FormPreferences::LnFmisc::LnFmisc(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_lnf_misc const * FormPreferences::LnFmisc::dialog()
{
	return dialog_.get();
}


void FormPreferences::LnFmisc::apply(LyXRC & rc) const
{
	rc.auto_region_delete =
		fl_get_button(dialog_->check_auto_region_delete);
	rc.cursor_follows_scrollbar =
		fl_get_button(dialog_->check_cursor_follows_scrollbar);
	rc.dialogs_iconify_with_main =
		fl_get_button(dialog_->check_dialogs_iconify_with_main);

	switch (fl_get_choice(dialog_->choice_instant_preview)) {
	case 1:
		rc.preview = LyXRC::PREVIEW_OFF;
		break;
	case 2:
		rc.preview = LyXRC::PREVIEW_NO_MATH;
		break;
	case 3:
		rc.preview = LyXRC::PREVIEW_ON;
		break;
	}

	rc.autosave = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_autosave));
	rc.wheel_jump = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_wm_jump));

	// See FIXME below
	// graphics::DisplayType old_value = rc.display_graphics;
	switch (fl_get_choice(dialog_->choice_graphics_display)) {
	case 4:
		rc.display_graphics = graphics::NoDisplay;
		break;
	case 3:
		rc.display_graphics = graphics::ColorDisplay;
		break;
	case 2:
		rc.display_graphics = graphics::GrayscaleDisplay;
		break;
	case 1:
		rc.display_graphics = graphics::MonochromeDisplay;
		break;
	default:
		rc.display_graphics = graphics::ColorDisplay;
		break;
	}

#ifdef WITH_WARNINGS
#warning FIXME!! The graphics cache no longer has a changeDisplay method.
#endif
#if 0
	if (old_value != rc.display_graphics) {
		graphics::GCache & gc = graphics::GCache::get();
		gc.changeDisplay();
	}
#endif
}


void FormPreferences::LnFmisc::build()
{
	dialog_.reset(build_preferences_lnf_misc(&parent_));

	fl_set_counter_step(dialog_->counter_autosave, 1, 10);
	fl_set_counter_step(dialog_->counter_wm_jump, 1, 10);

	fl_set_counter_return(dialog_->counter_autosave, FL_RETURN_CHANGED);
	fl_set_counter_return(dialog_->counter_wm_jump, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->check_auto_region_delete);
	setPrehandler(dialog_->counter_autosave);
	setPrehandler(dialog_->check_cursor_follows_scrollbar);
	setPrehandler(dialog_->check_dialogs_iconify_with_main);
	setPrehandler(dialog_->choice_instant_preview);
	setPrehandler(dialog_->counter_wm_jump);

	fl_addto_choice(dialog_->choice_graphics_display,
			_("Monochrome|Grayscale|Color|Do not display").c_str());

	fl_addto_choice(dialog_->choice_instant_preview,
			_("Off|No math|On").c_str());
}


string const
FormPreferences::LnFmisc::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->check_auto_region_delete)
		return LyXRC::getDescription(LyXRC::RC_AUTOREGIONDELETE);
	if (ob == dialog_->check_cursor_follows_scrollbar)
		return LyXRC::getDescription(LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR);
	if (ob == dialog_->check_dialogs_iconify_with_main)
		return LyXRC::getDescription(LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN);
	if (ob == dialog_->choice_instant_preview)
		return LyXRC::getDescription(LyXRC::RC_PREVIEW);
	if (ob == dialog_->counter_autosave)
		return LyXRC::getDescription(LyXRC::RC_AUTOSAVE);
	if (ob == dialog_->counter_wm_jump)
		return LyXRC::getDescription(LyXRC::RC_WHEEL_JUMP);
	if (ob == dialog_->choice_graphics_display)
		return LyXRC::getDescription(LyXRC::RC_DISPLAY_GRAPHICS);
	return string();
}


void FormPreferences::LnFmisc::update(LyXRC const & rc)
{
	fl_set_button(dialog_->check_auto_region_delete,
		      rc.auto_region_delete);
	fl_set_button(dialog_->check_cursor_follows_scrollbar,
		      rc.cursor_follows_scrollbar);
	fl_set_button(dialog_->check_dialogs_iconify_with_main,
		      rc.dialogs_iconify_with_main);

	switch (rc.preview) {
	case LyXRC::PREVIEW_OFF:
		fl_set_choice(dialog_->choice_instant_preview, 1);
		break;
	case LyXRC::PREVIEW_NO_MATH:
		fl_set_choice(dialog_->choice_instant_preview, 2);
		break;
	case LyXRC::PREVIEW_ON:
		fl_set_choice(dialog_->choice_instant_preview, 3);
		break;
	}

	fl_set_counter_value(dialog_->counter_autosave, rc.autosave);
	fl_set_counter_value(dialog_->counter_wm_jump, rc.wheel_jump);

	switch (rc.display_graphics) {
	case graphics::NoDisplay:
		fl_set_choice(dialog_->choice_graphics_display, 4);
		break;
	case graphics::ColorDisplay:
		fl_set_choice(dialog_->choice_graphics_display, 3);
		break;
	case graphics::GrayscaleDisplay:
		fl_set_choice(dialog_->choice_graphics_display, 2);
		break;
	case graphics::MonochromeDisplay:
		fl_set_choice(dialog_->choice_graphics_display, 1);
		break;
	default:
		fl_set_choice(dialog_->choice_graphics_display, 3);
		break;
	}
}


FormPreferences::OutputsMisc::OutputsMisc(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_outputs_misc const * FormPreferences::OutputsMisc::dialog()
{
	return dialog_.get();
}


void FormPreferences::OutputsMisc::apply(LyXRC & rc) const
{
	rc.ascii_linelen = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_line_len));
	rc.fontenc = getString(dialog_->input_tex_encoding);

	int const choice =
		fl_get_choice(dialog_->choice_default_papersize) - 1;
	rc.default_papersize = parent_.controller().toPaperSize(choice);

	rc.ascii_roff_command = getString(dialog_->input_ascii_roff);
	rc.chktex_command = getString(dialog_->input_checktex);
	rc.bibtex_command = getString(dialog_->input_bibtex);
	rc.index_command = getString(dialog_->input_index);
	rc.view_dvi_paper_option = getString(dialog_->input_paperoption);
	rc.auto_reset_options = fl_get_button(dialog_->check_autoreset_classopt);

#if defined(__CYGWIN__) || defined(__CYGWIN32__)
	rc.windows_style_tex_paths =
		fl_get_button(dialog_->check_windows_style_tex_paths);
#endif
}


void FormPreferences::OutputsMisc::build()
{
	dialog_.reset(build_preferences_outputs_misc(&parent_));

	fl_set_counter_step(dialog_->counter_line_len, 1, 10);

	fl_set_counter_return(dialog_->counter_line_len, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_tex_encoding, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_ascii_roff,   FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_bibtex,       FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_checktex,     FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_index,        FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_paperoption,  FL_RETURN_CHANGED);

#if defined(__CYGWIN__) || defined(__CYGWIN32__)
#else
	setEnabled(dialog_->check_windows_style_tex_paths, false);
#endif

	fl_addto_choice(dialog_->choice_default_papersize,
			_(" default | US letter | US legal "
			  "| US executive | A3 | A4 | A5 | B5 ").c_str());

	// set up the feedback mechanism
	setPrehandler(dialog_->counter_line_len);
	setPrehandler(dialog_->input_tex_encoding);
	setPrehandler(dialog_->choice_default_papersize);
	setPrehandler(dialog_->input_ascii_roff);
	setPrehandler(dialog_->input_bibtex);
	setPrehandler(dialog_->input_checktex);
	setPrehandler(dialog_->input_index);
	setPrehandler(dialog_->input_paperoption);
	setPrehandler(dialog_->check_autoreset_classopt);
#if defined(__CYGWIN__) || defined(__CYGWIN32__)
	setPrehandler(dialog_->check_windows_style_tex_paths);
#endif
}


string const
FormPreferences::OutputsMisc::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->counter_line_len)
		return LyXRC::getDescription(LyXRC::RC_ASCII_LINELEN);
	if (ob == dialog_->input_tex_encoding)
		return LyXRC::getDescription(LyXRC::RC_FONT_ENCODING);
	if (ob == dialog_->input_ascii_roff)
		return LyXRC::getDescription(LyXRC::RC_ASCIIROFF_COMMAND);
	if (ob == dialog_->input_bibtex)
		return LyXRC::getDescription(LyXRC::RC_BIBTEX_COMMAND);
	if (ob == dialog_->input_checktex)
		return LyXRC::getDescription(LyXRC::RC_CHKTEX_COMMAND);
	if (ob == dialog_->input_index)
		return LyXRC::getDescription(LyXRC::RC_INDEX_COMMAND);
	if (ob == dialog_->choice_default_papersize)
		return LyXRC::getDescription(LyXRC::RC_DEFAULT_PAPERSIZE);
	if (ob == dialog_->input_paperoption)
		return LyXRC::getDescription(LyXRC::RC_VIEWDVI_PAPEROPTION);
	if (ob == dialog_->check_autoreset_classopt)
		return LyXRC::getDescription(LyXRC::RC_AUTORESET_OPTIONS);
#if defined(__CYGWIN__) || defined(__CYGWIN32__)
	if (ob == dialog_->check_windows_style_tex_paths)
		return _("Select if LyX should output Windows-style paths "
			 "rather than Posix-style paths to LaTeX files. "
			 "Useful if you're using the native Windows MikTeX "
			 "rather than the Cygwin teTeX.");
#endif
	return string();
}


void FormPreferences::OutputsMisc::update(LyXRC const & rc)
{
	fl_set_counter_value(dialog_->counter_line_len,
			     rc.ascii_linelen);
	fl_set_input(dialog_->input_tex_encoding,
		     rc.fontenc.c_str());
	fl_set_choice(dialog_->choice_default_papersize,
		      parent_.controller().fromPaperSize(rc.default_papersize) + 1);
	fl_set_input(dialog_->input_ascii_roff,
		     rc.ascii_roff_command.c_str());
	fl_set_input(dialog_->input_checktex,
		     rc.chktex_command.c_str());
	fl_set_input(dialog_->input_bibtex,
		     rc.bibtex_command.c_str());
	fl_set_input(dialog_->input_index,
		     rc.index_command.c_str());
	fl_set_input(dialog_->input_paperoption,
		     rc.view_dvi_paper_option.c_str());
	fl_set_button(dialog_->check_autoreset_classopt,
		      rc.auto_reset_options);
#if defined(__CYGWIN__) || defined(__CYGWIN32__)
	fl_set_button(dialog_->check_windows_style_tex_paths,
		      rc.windows_style_tex_paths);
#endif
}


FormPreferences::Paths::Paths(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_paths const * FormPreferences::Paths::dialog()
{
	return dialog_.get();
}


void FormPreferences::Paths::apply(LyXRC & rc)
{
	rc.document_path = getString(dialog_->input_default_path);
	rc.template_path = getString(dialog_->input_template_path);
	rc.tempdir_path  = getString(dialog_->input_temp_dir);
	rc.path_prefix  = getString(dialog_->input_path_prefix);

	int button = fl_get_button(dialog_->check_last_files);
	string str = getString(dialog_->input_lastfiles);
	if (!button) str.erase();

	rc.check_lastfiles = button;
	rc.lastfiles = str;
	rc.num_lastfiles = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_lastfiles));

	button = fl_get_button(dialog_->check_make_backups);
	str = getString(dialog_->input_backup_path);
	if (!button)
		str.erase();

	rc.make_backup = button;
	rc.backupdir_path = str;

	rc.lyxpipes = getString(dialog_->input_serverpipe);

	// update view
	update(rc);
}


void FormPreferences::Paths::build()
{
	dialog_.reset(build_preferences_paths(&parent_));

	fl_set_input_return(dialog_->input_default_path, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_template_path, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_temp_dir, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_path_prefix, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_lastfiles, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_backup_path, FL_RETURN_CHANGED);
	fl_set_counter_bounds(dialog_->counter_lastfiles, 0, maxlastfiles);
	fl_set_counter_return(dialog_->counter_lastfiles, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_serverpipe, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_default_path);
	setPrehandler(dialog_->counter_lastfiles);
	setPrehandler(dialog_->input_template_path);
	setPrehandler(dialog_->input_path_prefix);
	setPrehandler(dialog_->check_last_files);
	setPrehandler(dialog_->input_lastfiles);
	setPrehandler(dialog_->check_make_backups);
	setPrehandler(dialog_->input_backup_path);
	setPrehandler(dialog_->input_serverpipe);
	setPrehandler(dialog_->input_temp_dir);
}


string const
FormPreferences::Paths::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->input_default_path)
		return LyXRC::getDescription(LyXRC::RC_DOCUMENTPATH);
	if (ob == dialog_->input_template_path)
		return LyXRC::getDescription(LyXRC::RC_TEMPLATEPATH);
	if (ob == dialog_->input_temp_dir)
		return LyXRC::getDescription(LyXRC::RC_TEMPDIRPATH);
	if (ob == dialog_->check_last_files)
		return LyXRC::getDescription(LyXRC::RC_CHECKLASTFILES);
	if (ob == dialog_->input_lastfiles)
		return LyXRC::getDescription(LyXRC::RC_LASTFILES);
	if (ob == dialog_->counter_lastfiles)
		return LyXRC::getDescription(LyXRC::RC_NUMLASTFILES);
	if (ob == dialog_->check_make_backups)
		return LyXRC::getDescription(LyXRC::RC_MAKE_BACKUP);
	if (ob == dialog_->input_backup_path)
		return LyXRC::getDescription(LyXRC::RC_BACKUPDIR_PATH);
	if (ob == dialog_->input_serverpipe)
		return LyXRC::getDescription(LyXRC::RC_SERVERPIPE);
	if (ob == dialog_->input_path_prefix)
		return LyXRC::getDescription(LyXRC::RC_PATH_PREFIX);
	return string();
}


bool FormPreferences::Paths::input(FL_OBJECT const * const ob)
{
	bool activate = true;

	// !ob if function is called from Paths::update() to de/activate
	// objects,
	// otherwise the function is called by an xforms CB via input().
	if (!ob || ob == dialog_->check_last_files) {
		bool const enable = fl_get_button(dialog_->check_last_files);
		setEnabled(dialog_->input_lastfiles, enable);
	}

	if (!ob || ob == dialog_->check_make_backups) {
		bool const enable = fl_get_button(dialog_->check_make_backups);
		setEnabled(dialog_->input_backup_path, enable);
	}

	if (!ob || ob == dialog_->input_default_path) {
		string const name = getString(dialog_->input_default_path);
		if (!name.empty() && !RWInfo::WriteableDir(name)) {
			parent_.postWarning(RWInfo::ErrorMessage());
			return false;
		}
	}

	if (!ob || ob == dialog_->input_template_path) {
		string const name = getString(dialog_->input_template_path);
		if (!name.empty() && !RWInfo::ReadableDir(name)) {
			parent_.postWarning(RWInfo::ErrorMessage());
			return false;
		}
	}

	if (!ob || ob == dialog_->input_temp_dir) {
		string const name = getString(dialog_->input_temp_dir);
		if (fl_get_button(dialog_->check_make_backups)
		    && !name.empty()
		    && !RWInfo::WriteableDir(name)) {
			parent_.postWarning(RWInfo::ErrorMessage());
			return false;
		}
	}

	if (!ob || ob == dialog_->input_backup_path) {
		string const name = getString(dialog_->input_backup_path);
		if (fl_get_button(dialog_->check_make_backups)
		    && !name.empty()
		    && !RWInfo::WriteableDir(name)) {
			parent_.postWarning(RWInfo::ErrorMessage());
			return false;
		}
	}

	if (!ob || ob == dialog_->input_lastfiles) {
		string const name = getString(dialog_->input_lastfiles);
		if (fl_get_button(dialog_->check_last_files)
		    && !name.empty()
		    && !RWInfo::WriteableFile(name)) {
			parent_.postWarning(RWInfo::ErrorMessage());
			return false;
		}
	}

	if (!ob || ob == dialog_->input_serverpipe) {
		string const name = getString(dialog_->input_serverpipe);
		if (!name.empty()) {
			// strip off the extension
			string const str = ChangeExtension(name, "");
			if (!RWInfo::WriteableFile(str + ".in")) {
				parent_.postWarning(RWInfo::ErrorMessage());
				return false;
			}
			if (!RWInfo::WriteableFile(str + ".out")) {
				parent_.postWarning(RWInfo::ErrorMessage());
				return false;
			}
		}
	}

	if (ob == dialog_->button_default_path_browse) {
		string f = parent_.controller().browsedir(
			getString(dialog_->input_default_path), _("Default path"));
		if (!f.empty())
			fl_set_input(dialog_->input_default_path, f.c_str());
	} else if (ob == dialog_->button_template_path_browse) {
		string f = parent_.controller().browsedir(
			getString(dialog_->input_template_path), _("Template path"));
		if (!f.empty())
			fl_set_input(dialog_->input_template_path, f.c_str());
	} else if (ob == dialog_->button_temp_dir_browse) {
		string f = parent_.controller().browsedir(
			getString(dialog_->input_temp_dir), _("Temporary dir"));
		if (!f.empty())
			fl_set_input(dialog_->input_temp_dir, f.c_str());
	} else if (ob == dialog_->button_lastfiles_browse) {
		string f = parent_.controller().browse(
			getString(dialog_->input_lastfiles), _("Last files"));
		if (!f.empty())
			fl_set_input(dialog_->input_lastfiles, f.c_str());
	} else if (ob == dialog_->button_backup_path_browse) {
		string f = parent_.controller().browsedir(
			getString(dialog_->input_backup_path), _("Backup path"));
		if (!f.empty())
			fl_set_input(dialog_->input_backup_path, f.c_str());
	} else if (ob == dialog_->button_serverpipe_browse) {
		string f = parent_.controller().browse(
			getString(dialog_->input_serverpipe), _("LyX server pipes"));
		if (!f.empty())
			fl_set_input(dialog_->input_serverpipe, f.c_str());
	}

	return activate;
}


void FormPreferences::Paths::update(LyXRC const & rc)
{
	fl_set_input(dialog_->input_default_path,
		     rc.document_path.c_str());
	fl_set_input(dialog_->input_template_path,
		     rc.template_path.c_str());

	string str;
	if (rc.make_backup)
		str = rc.backupdir_path;

	fl_set_button(dialog_->check_make_backups,
		      rc.make_backup);
	fl_set_input(dialog_->input_backup_path, str.c_str());

	fl_set_input(dialog_->input_temp_dir, rc.tempdir_path.c_str());
	fl_set_input(dialog_->input_path_prefix, rc.path_prefix.c_str());

	str.erase();
	if (rc.check_lastfiles)
		str = rc.lastfiles;

	fl_set_button(dialog_->check_last_files,
		      rc.check_lastfiles);
	fl_set_input(dialog_->input_lastfiles, str.c_str());
	fl_set_counter_value(dialog_->counter_lastfiles,
			     rc.num_lastfiles);

	fl_set_input(dialog_->input_serverpipe, rc.lyxpipes.c_str());

	// Activate/Deactivate the input fields dependent on the state of the
	// buttons.
	input(0);
}


FormPreferences::Printer::Printer(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_printer const * FormPreferences::Printer::dialog()
{
	return dialog_.get();
}


void FormPreferences::Printer::apply(LyXRC & rc) const
{
	rc.print_adapt_output = fl_get_button(dialog_->check_adapt_output);
	rc.print_command = getString(dialog_->input_command);
	rc.print_pagerange_flag = getString(dialog_->input_page_range);
	rc.print_copies_flag = getString(dialog_->input_copies);
	rc.print_reverse_flag = getString(dialog_->input_reverse);
	rc.print_to_printer = getString(dialog_->input_to_printer);
	rc.print_file_extension =
		getString(dialog_->input_file_extension);
	rc.print_spool_command =
		getString(dialog_->input_spool_command);
	rc.print_paper_flag = getString(dialog_->input_paper_type);
	rc.print_evenpage_flag = getString(dialog_->input_even_pages);
	rc.print_oddpage_flag = getString(dialog_->input_odd_pages);
	rc.print_collcopies_flag = getString(dialog_->input_collated);
	rc.print_landscape_flag = getString(dialog_->input_landscape);
	rc.print_to_file = getString(dialog_->input_to_file);
	rc.print_extra_options =
		getString(dialog_->input_extra_options);
	rc.print_spool_printerprefix =
		getString(dialog_->input_spool_prefix);
	rc.print_paper_dimension_flag =
		getString(dialog_->input_paper_size);
	rc.printer = getString(dialog_->input_name);
}


string const
FormPreferences::Printer::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->input_command)
		return LyXRC::getDescription(LyXRC::RC_PRINT_COMMAND);
	if (ob == dialog_->check_adapt_output)
		return LyXRC::getDescription(LyXRC::RC_PRINT_ADAPTOUTPUT);
	if (ob == dialog_->input_to_printer)
		return LyXRC::getDescription(LyXRC::RC_PRINTTOPRINTER);
	if (ob == dialog_->input_to_file)
		return LyXRC::getDescription(LyXRC::RC_PRINTTOFILE);
	if (ob == dialog_->input_file_extension)
		return LyXRC::getDescription(LyXRC::RC_PRINTFILEEXTENSION);
	if (ob == dialog_->input_extra_options)
		return LyXRC::getDescription(LyXRC::RC_PRINTEXSTRAOPTIONS);
	if (ob == dialog_->input_spool_command)
		return LyXRC::getDescription(LyXRC::RC_PRINTSPOOL_COMMAND);
	if (ob == dialog_->input_spool_prefix)
		return LyXRC::getDescription(LyXRC::RC_PRINTSPOOL_PRINTERPREFIX);
	if (ob == dialog_->input_name)
		return LyXRC::getDescription(LyXRC::RC_PRINTER);
	if (ob == dialog_->input_even_pages)
		return LyXRC::getDescription(LyXRC::RC_PRINTEVENPAGEFLAG);
	if (ob == dialog_->input_odd_pages)
		return LyXRC::getDescription(LyXRC::RC_PRINTODDPAGEFLAG);
	if (ob == dialog_->input_page_range)
		return LyXRC::getDescription(LyXRC::RC_PRINTPAGERANGEFLAG);
	if (ob == dialog_->input_reverse)
		return LyXRC::getDescription(LyXRC::RC_PRINTREVERSEFLAG);
	if (ob == dialog_->input_landscape)
		return LyXRC::getDescription(LyXRC::RC_PRINTLANDSCAPEFLAG);
	if (ob == dialog_->input_copies)
		return LyXRC::getDescription(LyXRC::RC_PRINTCOPIESFLAG);
	if (ob == dialog_->input_collated)
		return LyXRC::getDescription(LyXRC::RC_PRINTCOLLCOPIESFLAG);
	if (ob == dialog_->input_paper_type)
		return LyXRC::getDescription(LyXRC::RC_PRINTPAPERFLAG);
	if (ob == dialog_->input_paper_size)
		return LyXRC::getDescription(LyXRC::RC_PRINTPAPERDIMENSIONFLAG);
	return string();
}


void FormPreferences::Printer::build()
{
	dialog_.reset(build_preferences_printer(&parent_));

	fl_set_input_return(dialog_->input_command, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_page_range, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_copies, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_reverse, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_to_printer, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_file_extension, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_spool_command, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_paper_type, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_even_pages, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_odd_pages, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_collated, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_landscape, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_to_file, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_extra_options, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_spool_prefix, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_paper_size, FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_name, FL_RETURN_CHANGED);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_command);
	setPrehandler(dialog_->input_page_range);
	setPrehandler(dialog_->input_copies);
	setPrehandler(dialog_->input_reverse);
	setPrehandler(dialog_->input_to_printer);
	setPrehandler(dialog_->input_file_extension);
	setPrehandler(dialog_->input_spool_command);
	setPrehandler(dialog_->input_paper_type);
	setPrehandler(dialog_->input_even_pages);
	setPrehandler(dialog_->input_odd_pages);
	setPrehandler(dialog_->input_collated);
	setPrehandler(dialog_->input_landscape);
	setPrehandler(dialog_->input_to_file);
	setPrehandler(dialog_->input_extra_options);
	setPrehandler(dialog_->input_spool_prefix);
	setPrehandler(dialog_->input_paper_size);
	setPrehandler(dialog_->input_name);
	setPrehandler(dialog_->check_adapt_output);
}


void FormPreferences::Printer::update(LyXRC const & rc)
{
	fl_set_button(dialog_->check_adapt_output,
		      rc.print_adapt_output);
	fl_set_input(dialog_->input_command,
		     rc.print_command.c_str());
	fl_set_input(dialog_->input_page_range,
		     rc.print_pagerange_flag.c_str());
	fl_set_input(dialog_->input_copies,
		     rc.print_copies_flag.c_str());
	fl_set_input(dialog_->input_reverse,
		     rc.print_reverse_flag.c_str());
	fl_set_input(dialog_->input_to_printer,
		     rc.print_to_printer.c_str());
	fl_set_input(dialog_->input_file_extension,
		     rc.print_file_extension.c_str());
	fl_set_input(dialog_->input_spool_command,
		     rc.print_spool_command.c_str());
	fl_set_input(dialog_->input_paper_type,
		     rc.print_paper_flag.c_str());
	fl_set_input(dialog_->input_even_pages,
		     rc.print_evenpage_flag.c_str());
	fl_set_input(dialog_->input_odd_pages,
		     rc.print_oddpage_flag.c_str());
	fl_set_input(dialog_->input_collated,
		     rc.print_collcopies_flag.c_str());
	fl_set_input(dialog_->input_landscape,
		     rc.print_landscape_flag.c_str());
	fl_set_input(dialog_->input_to_file,
		     rc.print_to_file.c_str());
	fl_set_input(dialog_->input_extra_options,
		     rc.print_extra_options.c_str());
	fl_set_input(dialog_->input_spool_prefix,
		     rc.print_spool_printerprefix.c_str());
	fl_set_input(dialog_->input_paper_size,
		     rc.print_paper_dimension_flag.c_str());
	fl_set_input(dialog_->input_name,
		     rc.printer.c_str());
}


FormPreferences::ScreenFonts::ScreenFonts(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_screen_fonts const * FormPreferences::ScreenFonts::dialog()
{
	return dialog_.get();
}


void FormPreferences::ScreenFonts::apply(LyXRC & rc) const
{
	bool changed = false;

	pair<string, string> tmp =
		parseFontName(getString(dialog_->input_roman));
	if (rc.roman_font_name != tmp.first ||
	    rc.roman_font_foundry != tmp.second) {
		changed = true;
		rc.roman_font_name = tmp.first;
		rc.roman_font_foundry = tmp.second;
	}

	tmp = parseFontName(getString(dialog_->input_sans));
	if (rc.sans_font_name != tmp.first ||
	    rc.sans_font_foundry != tmp.second) {
		changed = true;
		rc.sans_font_name = tmp.first;
		rc.sans_font_foundry = tmp.second;
	}

	tmp = parseFontName(getString(dialog_->input_typewriter));
	if (rc.typewriter_font_name != tmp.first ||
	    rc.typewriter_font_foundry != tmp.second) {
		changed = true;
		rc.typewriter_font_name = tmp.first;
		rc.typewriter_font_foundry = tmp.second;
	}

	string str = getString(dialog_->input_screen_encoding);
	if (rc.font_norm != str) {
		changed = true;
		rc.font_norm = str;
		rc.set_font_norm_type();
	}

	bool button = fl_get_button(dialog_->check_scalable);
	if (rc.use_scalable_fonts != button) {
		changed = true;
		rc.use_scalable_fonts = button;
	}

	unsigned int ivalue = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_zoom));
	if (rc.zoom != ivalue) {
		changed = true;
		rc.zoom = ivalue;
	}

	ivalue = static_cast<unsigned int>
		(fl_get_counter_value(dialog_->counter_dpi));
	if (rc.dpi != ivalue) {
		changed = true;
		rc.dpi = ivalue;
	}

	string dvalue = getString(dialog_->input_tiny);
	if (rc.font_sizes[LyXFont::SIZE_TINY] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_TINY] = dvalue;
	}

	dvalue = getString(dialog_->input_script);
	if (rc.font_sizes[LyXFont::SIZE_SCRIPT] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_SCRIPT] = dvalue;
	}

	dvalue = getString(dialog_->input_footnote);
	if (rc.font_sizes[LyXFont::SIZE_FOOTNOTE] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_FOOTNOTE] = dvalue;
	}

	dvalue = getString(dialog_->input_small);
	if (rc.font_sizes[LyXFont::SIZE_SMALL] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_SMALL] = dvalue;
	}

	dvalue = getString(dialog_->input_normal);
	if (rc.font_sizes[LyXFont::SIZE_NORMAL] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_NORMAL] = dvalue;
	}

	dvalue = getString(dialog_->input_large);
	if (rc.font_sizes[LyXFont::SIZE_LARGE] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_LARGE] = dvalue;
	}

	dvalue = getString(dialog_->input_larger);
	if (rc.font_sizes[LyXFont::SIZE_LARGER] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_LARGER] = dvalue;
	}

	dvalue = getString(dialog_->input_largest);
	if (rc.font_sizes[LyXFont::SIZE_LARGEST] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_LARGEST] = dvalue;
	}

	dvalue = getString(dialog_->input_huge);
	if (rc.font_sizes[LyXFont::SIZE_HUGE] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_HUGE] = dvalue;
	}

	dvalue = getString(dialog_->input_huger);
	if (rc.font_sizes[LyXFont::SIZE_HUGER] != dvalue) {
		changed = true;
		rc.font_sizes[LyXFont::SIZE_HUGER] = dvalue;
	}

	if (changed) {
		// Now update the buffers
		// Can anything below here affect the redraw process?
		parent_.controller().updateScreenFonts();
	}
}


void FormPreferences::ScreenFonts::build()
{
	dialog_.reset(build_preferences_screen_fonts(&parent_));

	fl_set_counter_step(dialog_->counter_zoom, 1, 10);
	fl_set_counter_step(dialog_->counter_dpi,  1, 10);

	fl_set_input_return(dialog_->input_roman,           FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_sans,            FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_typewriter,      FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_screen_encoding, FL_RETURN_CHANGED);
	fl_set_counter_return(dialog_->counter_zoom,        FL_RETURN_CHANGED);
	fl_set_counter_return(dialog_->counter_dpi,         FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_tiny,            FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_script,          FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_footnote,        FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_small,           FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_normal,          FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_large,           FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_larger,          FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_largest,         FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_huge,            FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_huger,           FL_RETURN_CHANGED);

	fl_set_input_filter(dialog_->input_tiny,     fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_script,   fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_footnote, fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_small,    fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_normal,   fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_large,    fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_larger,   fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_largest,  fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_huge,     fl_unsigned_float_filter);
	fl_set_input_filter(dialog_->input_huger,    fl_unsigned_float_filter);

	// set up the feedback mechanism
	setPrehandler(dialog_->input_roman);
	setPrehandler(dialog_->input_sans);
	setPrehandler(dialog_->input_typewriter);
	setPrehandler(dialog_->counter_zoom);
	setPrehandler(dialog_->counter_dpi);
	setPrehandler(dialog_->check_scalable);
	setPrehandler(dialog_->input_screen_encoding);
	setPrehandler(dialog_->input_tiny);
	setPrehandler(dialog_->input_script);
	setPrehandler(dialog_->input_footnote);
	setPrehandler(dialog_->input_small);
	setPrehandler(dialog_->input_large);
	setPrehandler(dialog_->input_larger);
	setPrehandler(dialog_->input_largest);
	setPrehandler(dialog_->input_normal);
	setPrehandler(dialog_->input_huge);
	setPrehandler(dialog_->input_huger);
}


string const
FormPreferences::ScreenFonts::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->input_roman)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_ROMAN);
	if (ob == dialog_->input_sans)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_SANS);
	if (ob == dialog_->input_typewriter)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_TYPEWRITER);
	if (ob == dialog_->check_scalable)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_SCALABLE);
	if (ob == dialog_->input_screen_encoding)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_ENCODING);
	if (ob == dialog_->counter_zoom)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_ZOOM);
	if (ob == dialog_->counter_dpi)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_DPI);
	if (ob == dialog_->input_tiny
	    || ob == dialog_->input_script
	    || ob == dialog_->input_footnote
	    || ob == dialog_->input_small
	    || ob == dialog_->input_large
	    || ob == dialog_->input_larger
	    || ob == dialog_->input_larger
	    || ob == dialog_->input_largest
	    || ob == dialog_->input_normal
	    || ob == dialog_->input_huge
	    || ob == dialog_->input_huger)
		return LyXRC::getDescription(LyXRC::RC_SCREEN_FONT_SIZES);
	return string();
}


bool FormPreferences::ScreenFonts::input()
{
	bool activate = true;
	string str;

	// Make sure that all fonts all have positive entries
	// Also note that an empty entry is returned as 0.0 by strToDbl
	if (0.0 >= convert<double>(fl_get_input(dialog_->input_tiny))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_script))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_footnote))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_small))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_normal))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_large))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_larger))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_largest))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_huge))
	    || 0.0 >= convert<double>(fl_get_input(dialog_->input_huger))) {
		activate = false;
		str = _("Fonts must be positive!");
	} else if (convert<double>(fl_get_input(dialog_->input_tiny)) >
		   // Fontsizes -- tiny < script < footnote etc.
		   convert<double>(fl_get_input(dialog_->input_script)) ||
		   convert<double>(fl_get_input(dialog_->input_script)) >
		   convert<double>(fl_get_input(dialog_->input_footnote)) ||
		   convert<double>(fl_get_input(dialog_->input_footnote)) >
		   convert<double>(fl_get_input(dialog_->input_small)) ||
		   convert<double>(fl_get_input(dialog_->input_small)) >
		   convert<double>(fl_get_input(dialog_->input_normal)) ||
		   convert<double>(fl_get_input(dialog_->input_normal)) >
		   convert<double>(fl_get_input(dialog_->input_large)) ||
		   convert<double>(fl_get_input(dialog_->input_large)) >
		   convert<double>(fl_get_input(dialog_->input_larger)) ||
		   convert<double>(fl_get_input(dialog_->input_larger)) >
		   convert<double>(fl_get_input(dialog_->input_largest)) ||
		   convert<double>(fl_get_input(dialog_->input_largest)) >
		   convert<double>(fl_get_input(dialog_->input_huge)) ||
		   convert<double>(fl_get_input(dialog_->input_huge)) >
		   convert<double>(fl_get_input(dialog_->input_huger))) {
		activate = false;

		str = _("Fonts must be input in the order Tiny > Smallest > Smaller > Small > Normal > Large > Larger > Largest > Huge > Huger.");
	}

	if (!activate)
		parent_.postWarning(str);

	return activate;
}


void FormPreferences::ScreenFonts::update(LyXRC const & rc)
{
	fl_set_input(dialog_->input_roman,
		     makeFontName(rc.roman_font_name,
				  rc.roman_font_foundry).c_str());
	fl_set_input(dialog_->input_sans,
		     makeFontName(rc.sans_font_name,
				  rc.sans_font_foundry).c_str());
	fl_set_input(dialog_->input_typewriter,
		     makeFontName(rc.typewriter_font_name,
				  rc.typewriter_font_foundry).c_str());
	fl_set_input(dialog_->input_screen_encoding,
		     rc.font_norm.c_str());
	fl_set_button(dialog_->check_scalable,
		      rc.use_scalable_fonts);
	fl_set_counter_value(dialog_->counter_zoom, rc.zoom);
	fl_set_counter_value(dialog_->counter_dpi,  rc.dpi);
	fl_set_input(dialog_->input_tiny,
		     rc.font_sizes[LyXFont::SIZE_TINY].c_str());
	fl_set_input(dialog_->input_script,
		     rc.font_sizes[LyXFont::SIZE_SCRIPT].c_str());
	fl_set_input(dialog_->input_footnote,
		     rc.font_sizes[LyXFont::SIZE_FOOTNOTE].c_str());
	fl_set_input(dialog_->input_small,
		     rc.font_sizes[LyXFont::SIZE_SMALL].c_str());
	fl_set_input(dialog_->input_normal,
		     rc.font_sizes[LyXFont::SIZE_NORMAL].c_str());
	fl_set_input(dialog_->input_large,
		     rc.font_sizes[LyXFont::SIZE_LARGE].c_str());
	fl_set_input(dialog_->input_larger,
		     rc.font_sizes[LyXFont::SIZE_LARGER].c_str());
	fl_set_input(dialog_->input_largest,
		     rc.font_sizes[LyXFont::SIZE_LARGEST].c_str());
	fl_set_input(dialog_->input_huge,
		     rc.font_sizes[LyXFont::SIZE_HUGE].c_str());
	fl_set_input(dialog_->input_huger,
		     rc.font_sizes[LyXFont::SIZE_HUGER].c_str());
}



FormPreferences::SpellOptions::SpellOptions(FormPreferences &  p)
	: parent_(p)
{}


FD_preferences_spelloptions const * FormPreferences::SpellOptions::dialog()
{
	return dialog_.get();
}


void FormPreferences::SpellOptions::apply(LyXRC & rc)
{
	string choice = fl_get_choice_text(dialog_->choice_spell_command);
	choice = trim(choice);

	rc.isp_command = choice;

#if 0
	// If spellchecker == "", all other input set to off.
	if (fl_get_choice(dialog_->choice_spell_command) == 1) {
		rc.isp_use_alt_lang = false;
		rc.isp_alt_lang.erase();

		rc.isp_use_esc_chars = false;
		rc.isp_esc_chars.erase();

		rc.isp_use_pers_dict = false;
		rc.isp_pers_dict.erase();

		rc.isp_accept_compound = false;
		rc.isp_use_input_encoding = false;
	} else {
#else
		int button = fl_get_button(dialog_->check_alt_lang);
		choice = getString(dialog_->input_alt_lang);
		if (button && choice.empty()) button = 0;
		if (!button) choice.erase();

		rc.isp_use_alt_lang = static_cast<bool>(button);
		rc.isp_alt_lang = choice;

		button = fl_get_button(dialog_->check_escape_chars);
		choice = getString(dialog_->input_escape_chars);
		if (button && choice.empty()) button = 0;
		if (!button) choice.erase();

		rc.isp_use_esc_chars = static_cast<bool>(button);
		rc.isp_esc_chars = choice;

		button = fl_get_button(dialog_->check_personal_dict);
		choice = getString(dialog_->input_personal_dict);
		if (button && choice.empty()) button = 0;
		if (!button) choice.erase();

		rc.isp_use_pers_dict = static_cast<bool>(button);
		rc.isp_pers_dict = choice;

		button = fl_get_button(dialog_->check_compound_words);
		rc.isp_accept_compound = static_cast<bool>(button);

		button = fl_get_button(dialog_->check_input_enc);
		rc.isp_use_input_encoding = static_cast<bool>(button);
#endif
#if 0
	}
#endif

	// Reset view
	update(rc);
}


void FormPreferences::SpellOptions::build()
{
	dialog_.reset(build_preferences_spelloptions(&parent_));

	fl_addto_choice(dialog_->choice_spell_command,
			_(" ispell | aspell ").c_str());
	fl_set_input_return(dialog_->input_alt_lang,      FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_escape_chars,  FL_RETURN_CHANGED);
	fl_set_input_return(dialog_->input_personal_dict, FL_RETURN_CHANGED);

#if !defined (USE_ISPELL)
	setEnabled(dialog_->choice_spell_command, false);
#endif

	// set up the feedback mechanism
	setPrehandler(dialog_->choice_spell_command);
	setPrehandler(dialog_->check_alt_lang);
	setPrehandler(dialog_->input_alt_lang);
	setPrehandler(dialog_->check_escape_chars);
	setPrehandler(dialog_->input_escape_chars);
	setPrehandler(dialog_->check_personal_dict);
	setPrehandler(dialog_->input_personal_dict);
	setPrehandler(dialog_->button_personal_dict);
	setPrehandler(dialog_->check_compound_words);
	setPrehandler(dialog_->check_input_enc);
}


string const
FormPreferences::SpellOptions::feedback(FL_OBJECT const * const ob) const
{
	if (ob == dialog_->choice_spell_command)
		return LyXRC::getDescription(LyXRC::RC_SPELL_COMMAND);
	if (ob == dialog_->check_alt_lang)
		return LyXRC::getDescription(LyXRC::RC_USE_ALT_LANG);
	if (ob == dialog_->input_alt_lang)
		return LyXRC::getDescription(LyXRC::RC_ALT_LANG);
	if (ob == dialog_->check_escape_chars)
		return LyXRC::getDescription(LyXRC::RC_USE_ESC_CHARS);
	if (ob == dialog_->input_escape_chars)
		return LyXRC::getDescription(LyXRC::RC_ESC_CHARS);
	if (ob == dialog_->check_personal_dict)
		return LyXRC::getDescription(LyXRC::RC_USE_PERS_DICT);
	if (ob == dialog_->input_personal_dict)
		return LyXRC::getDescription(LyXRC::RC_PERS_DICT);
	if (ob == dialog_->check_compound_words)
		return LyXRC::getDescription(LyXRC::RC_ACCEPT_COMPOUND);
	if (ob == dialog_->check_input_enc)
		return LyXRC::getDescription(LyXRC::RC_USE_INP_ENC);
	return string();
}


bool FormPreferences::SpellOptions::input(FL_OBJECT const * const ob)
{
	// !ob if function is called from updateSpellOptions() to de/activate
	// objects,
	// otherwise the function is called by an xforms CB via input().

#if 0
	// If spellchecker == "", disable all input.
	if (!ob || ob == dialog_->choice_spell_command) {
		if (fl_get_choice(dialog_->choice_spell_command) == 1) {
			fl_deactivate_object(dialog_->check_alt_lang);
			fl_deactivate_object(dialog_->input_alt_lang);
			fl_deactivate_object(dialog_->check_escape_chars);
			fl_deactivate_object(dialog_->input_escape_chars);
			fl_deactivate_object(dialog_->check_personal_dict);
			fl_deactivate_object(dialog_->input_personal_dict);
			fl_deactivate_object(dialog_->check_compound_words);
			fl_deactivate_object(dialog_->check_input_enc);
			return true;
		} else {
			fl_activate_object(dialog_->check_alt_lang);
			fl_activate_object(dialog_->check_escape_chars);
			fl_activate_object(dialog_->check_personal_dict);
			fl_activate_object(dialog_->check_compound_words);
			fl_activate_object(dialog_->check_input_enc);
		}
	}
#endif

	if (!ob || ob == dialog_->check_alt_lang) {
		bool const enable = fl_get_button(dialog_->check_alt_lang);
		setEnabled(dialog_->input_alt_lang, enable);
	}

	if (!ob || ob == dialog_->check_escape_chars) {
		bool const enable = fl_get_button(dialog_->check_escape_chars);
		setEnabled(dialog_->input_escape_chars, enable);
	}

	if (!ob || ob == dialog_->check_personal_dict) {
		bool const enable = fl_get_button(dialog_->check_personal_dict);
		setEnabled(dialog_->input_personal_dict, enable);
	}

	if (ob == dialog_->button_personal_dict) {
		string f = parent_.controller().browsedict(
			getString(dialog_->input_personal_dict));
		fl_set_input(dialog_->input_personal_dict, f.c_str());
	}

	return true; // All input is valid!
}


void FormPreferences::SpellOptions::update(LyXRC const & rc)
{
	int choice = 1;
#if 0
	if (rc.isp_command == "" || rc.isp_command == "none")
		choice = 1;
	else if (rc.isp_command == "ispell")
		choice = 2;
	else if (rc.isp_command == "aspell")
		choice = 3;
#else
	if (rc.isp_command == "ispell")
		choice = 1;
	else if (rc.isp_command == "aspell")
		choice = 2;
#endif
	fl_set_choice(dialog_->choice_spell_command, choice);

	string str;
	if (rc.isp_use_alt_lang)
		str = rc.isp_alt_lang;

	fl_set_button(dialog_->check_alt_lang,
		      rc.isp_use_alt_lang);
	fl_set_input(dialog_->input_alt_lang, str.c_str());

	str.erase();
	if (rc.isp_use_esc_chars)
		str = rc.isp_esc_chars;

	fl_set_button(dialog_->check_escape_chars,
		      rc.isp_use_esc_chars);
	fl_set_input(dialog_->input_escape_chars, str.c_str());

	str.erase();
	if (rc.isp_use_pers_dict)
		str = rc.isp_pers_dict;

	fl_set_button(dialog_->check_personal_dict,
		      rc.isp_use_pers_dict);
	fl_set_input(dialog_->input_personal_dict, str.c_str());

	fl_set_button(dialog_->check_compound_words,
		      rc.isp_accept_compound);
	fl_set_button(dialog_->check_input_enc,
		      rc.isp_use_input_encoding);

	// Activate/Deactivate the input fields dependent on the state of the
	// buttons.
	input(0);
}

} // namespace frontend
} // namespace lyx
