/*
 * Cueplot: a GUI front-end to gnuplot
 * Copyright (C) 2008 Muneyuki Noguchi
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, 
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "PlotListView.h"

#include <QtCore/QCoreApplication>
#if QT_VERSION >= 0x040200
# include <QtCore/QFileInfo>
# include <QtCore/QUrl>
# include <QtGui/QDesktopServices>
#endif
#include <QtGui/QAction>
#include <QtGui/QInputDialog>
#include <QtGui/QMenu>
#if QT_VERSION >= 0x040200
# include <QtGui/QMessageBox>
#endif

PlotListView::PlotListView(QWidget *parent)
: QListView(parent)
{
	setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
			this, SLOT(showContextMenu(const QPoint &)));
}

void PlotListView::showContextMenu(const QPoint &/*pos*/)
{
	QModelIndexList list = selectionModel()->selectedIndexes();
	if (!list.size()) {
		return;
	}
	QModelIndex index = list[0];
	QMenu *menu = new QMenu;
#if QT_VERSION >= 0x040200
	QAction *openAction = new QAction(tr("&Open"), this);
	openAction->setEnabled(!model()->data(index, Qt::UserRole + 1).toBool());
	menu->addAction(openAction);
#endif
	QAction *editAction = new QAction(tr("&Edit..."), this);
	menu->addAction(editAction);
	QAction *action = menu->exec(QCursor::pos());


#if QT_VERSION >= 0x040200
	if (action == openAction) {
		QString file = model()->data(index).toString(); 
		// 実行可能ファイルの実行を防ぐ
		if (QFileInfo(file).isExecutable()) {
			QMessageBox::warning(this, tr("Executable File") + " - "
					+ QCoreApplication::applicationName(), 
					tr("This is an executable file."));
			return;
		}
		QDesktopServices::openUrl(QUrl::fromLocalFile(file));
	} else
#endif
	if (action == editAction) {
		bool ok;
		QString text 
			= QInputDialog::getText(this, tr("Edit") + " - " 
					+ QCoreApplication::applicationName(),
					tr("An Item Name:"), QLineEdit::Normal,
					model()->data(index).toString(), &ok);
		// 文字列が空のときは変更しない
		if (ok && !text.isEmpty()) {
			model()->setData(index, QVariant(text));
		}
	}
}
