/****************************************************************************
**
** Copyright (C) 2003-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** CrossVC is available under two different licenses:
**
** If CrossVC is linked against the GPLed version of Qt 
** CrossVC is released under the terms of GPL also.
**
** If CrossVC is linked against a nonGPLed version of Qt 
** CrossVC is released under the terms of the 
** CrossVC License for non-Unix platforms (CLNU)
**
**
** CrossVC License for non-Unix platforms (CLNU):
**
** Redistribution and use in binary form, without modification, 
** are permitted provided that the following conditions are met:
**
** 1. Redistributions in binary form must reproduce the above copyright
**    notice, this list of conditions and the following disclaimer in the
**    documentation and/or other materials provided with the distribution.
** 2. It is not permitted to distribute the binary package under a name
**    different than CrossVC.
** 3. The name of the authors may not be used to endorse or promote
**    products derived from this software without specific prior written
**    permission.
** 4. The source code is the creative property of the authors.
**    Extensions and development under the terms of the Gnu Public License
**    are limited to the Unix platform. Any distribution or compilation of 
**    the source code against libraries licensed other than gpl requires 
**    the written permission of the authors.
**
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
**
** CrossVC License for Unix platforms:
**
** 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, version 2 of the License.
** 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 version 2 for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
*****************************************************************************/

#include "config.h"

#include <qtable.h>
#include <qfiledialog.h>
#include <qwhatsthis.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qcommonstyle.h>
#include <qapplication.h>
#include <qtimer.h>

#include "FileMapperDialogImpl.h"


class LinCVSTableStyle : public QCommonStyle {//private style to better find selected cells in FollowStyle mode

 public:
   LinCVSTableStyle() {}
   ~LinCVSTableStyle() {}

   void drawPrimitive( PrimitiveElement pe,
	 QPainter *p,
	 const QRect & r,
	 const QColorGroup & cg,
	 SFlags flags,
	 const QStyleOption & opt) const
   {
      if (pe == QStyle::PE_FocusRect) {

	 int x = r.x();
	 int y = r.y();
	 int w = r.width();
	 int h = r.height();
	 QColor c = p->pen().color();
	 p->setPen(QColor("black"));
	 for (int i=0; i<2; i++) {
	    p->drawRect(x,y,w,h);
	    x++;
	    y++;
	    w -= 2;
	    h -= 2;
	 }
	 p->setPen(c);
      } else {
	 QApplication::style().drawPrimitive( pe, p, r, cg, flags, opt );
      }
   }
   void polishPopupMenu(QPopupMenu * p) {QApplication::style().polishPopupMenu(p);}

 private:
   // Disabled copy constructor and operator=
   LinCVSTableStyle( const LinCVSTableStyle & );
   LinCVSTableStyle& operator=( const LinCVSTableStyle & );
};

FileMapperDialogImpl::FileMapperDialogImpl(Mapping::FileAppList & fileAppList, 
      QString caption,
      const QIconSet &whatsThisIconSet, 
      QWidget * parent,
      const char * name,
      bool modal, WFlags f)
   : MappingDialog(parent,	name, modal, f),
     m_pFileAppList(&fileAppList), m_tmpCol(0), m_tmpRow(0)
{

   m_pWhatsThis->setIconSet(whatsThisIconSet);
#ifdef Q_WS_MAC
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height() * 2);
#else
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height());
#endif

   setCaption( caption);

   QWhatsThis::add(this, tr("To insert, delete or browse dirs, use the contextual menu.")
	 +"\n\n"
	 +tr("* The 'Match' specifies the affected files.")
	 +" "+tr("CrossVC will match selected files against these matches from top down. The first exact match will be used.")
	 +"\n\n"
	 +tr("* The 'Application' specifies the application which will open the files filtered by 'Match'.")
	 +"\n\n"
	 +tr("* The 'Options' column specifies how the files will be opened.")
	 +" "+tr("The number that follows each percent ('%') sign will be replaced")
	 +" "+tr("with the (number)th file of the current selection.")
	 +" "+tr("'%2' would be replaced with the second selected file name.")
	 +" "+tr("If you want to invoke your application with special options, this is the place to specify them.")
	 +" "+tr("Type the options in the way you would use them from the command line, this should;-) do.")
	 +"\n"
	 +tr("To open all selected files, specify '%n' here.")
	 +"\n\n"
	 +tr("* In case 'use as regexp' is checked, the 'Match' will be interpreted as a regular expression.")
	 +" "+tr("The default is wildcard mode.")
	 +"\n\n\n"
	 +tr("Example entries:")
	 +"\n"
	 +"*.html\t\tmozilla\t%1\t'unchecked'\n*.txt\t\tvi\t%n\t'unchecked'\n.+\\.(c|cpp|h)\txemacs\t%n\t'checked'");

   List->setStyle(new LinCVSTableStyle());

   List->setSelectionMode(QTable::SingleRow);
   List->setRowMovingEnabled(TRUE);
   List->setDragEnabled(TRUE);
   List->setFocusStyle(QTable::FollowStyle);

   List->verticalHeader()->hide();
   List->setLeftMargin(0);
   List->insertColumns( 0, 4);
   List->horizontalHeader()->setLabel( 0, tr("Match"));
   List->horizontalHeader()->setLabel( 1, tr("Application"));
   List->horizontalHeader()->setLabel( 2, tr("Options"));
   List->horizontalHeader()->setLabel( 3, tr("Wildcard / RegExp"));

   resetClicked();//prepare and fill the List
}

FileMapperDialogImpl::~FileMapperDialogImpl() {

}

void FileMapperDialogImpl::listContextMenuRequested(int row, int col, const QPoint &p) {

   m_tmpCol = col;
   m_tmpRow = row;
   
   QPoint cp = List->mapFromGlobal(p);
   cp += QPoint(0,List->contentsY()-List->horizontalHeader()->height());
   if (List->cellGeometry(row,col).contains(cp)) m_isClickedFromSelectedCell = TRUE;
   else m_isClickedFromSelectedCell = FALSE;
   m_pPopupMenu.clear();
   if ( (col == 1)  && m_isClickedFromSelectedCell) {
      m_pPopupMenu.insertItem( tr("Browse dir ..."),this,SLOT(browseDir()));
      m_pPopupMenu.insertSeparator();
   }
   m_pPopupMenu.insertItem( tr("New entry"),this,SLOT(addEntry()));
   m_pPopupMenu.insertItem( tr("Delete entry"),this,SLOT(deleteEntry()));
   m_pPopupMenu.popup(p);
}

void FileMapperDialogImpl::browseDir() {

   QString fn = QFileDialog::getOpenFileName(List->text(List->currentRow(), List->currentColumn()),
                                             QString::null, this,
                                             0, tr("Choose application"), 0, true);
					     
   if ( !fn.isEmpty() ) {
      List->setText(m_tmpRow, m_tmpCol, fn);
   }
}

void FileMapperDialogImpl::deleteEntry() {
   int row = List->currentRow();
   List->removeRow(row);
   List->clearSelection();
   if (List->numRows() <= row) row = List->numRows()-1;
   List->selectRow(row);
   List->setCurrentCell(row,0);
}

void FileMapperDialogImpl::addEntry() {
   int row = List->currentRow();
   if (row != -1) {// list contains entries
      List->setCurrentCell(row,1);//don't select col 0, return would cause a cursor jump to next col on top position
      if (!m_isClickedFromSelectedCell) {
	 row = List->numRows();
      }
   } else row = 0;
   List->insertRows(row);
   List->setItem( row, 3, new QCheckTableItem(List,tr("use as regexp")));
   List->setCurrentCell(row,0);
}

void FileMapperDialogImpl::moveCellUp() {
   int row;
   if ( (row=List->currentRow()) > 0) {
      List->swapRows(row-1,row);
      List->clearSelection();
      List->selectRow(row-1);
      int i;
      for (i = 0; i < List->numCols(); i++) {
	 List->updateCell(row, i);
	 List->updateCell(row-1, i);
      }
   }
}

void FileMapperDialogImpl::moveCellDown() {
   int row;
   if ( (row=List->currentRow()) < List->numRows()-1) {
      List->swapRows(row,row+1);
      List->clearSelection();
      List->selectRow(row+1);
      int i;
      for (i = 0; i < List->numCols(); i++) {
	 List->updateCell(row, i);
	 List->updateCell(row+1, i);
      }
   }
}

void FileMapperDialogImpl::okClicked() {
   m_pFileAppList->clear();
   int row;
   if (List->numRows() > 0) {//workaround to actually insert currently edited tableItem values
      List->editCell(0,1);
      List->editCell(0,0);
   }
   for (row = 0; row < List->numRows(); row++) {
      Mapping::FileAppItem item;
      item.wildcard = List->text(row,0).stripWhiteSpace();
      item.app = List->text(row,1).stripWhiteSpace();
      item.params = List->text(row,2).stripWhiteSpace();
      item.isRegExp = ((QCheckTableItem*)List->item(row,3))->isChecked();
      m_pFileAppList->append( item);
   }
   accept();
}

void FileMapperDialogImpl::resetClicked() {
   int rows = List->numRows();
   int newRows = m_pFileAppList->size();
   while ( rows > newRows) {
      List->removeRow(--rows);
   }
   if (rows < newRows) {
      newRows = newRows - rows;
      List->insertRows( rows, newRows);
      int i;
      for (i=rows; i<rows+newRows; i++) {
         List->setItem( i, 3, new QCheckTableItem(List,tr("use as regexp")));
      }
   }
   fillList();
}

void FileMapperDialogImpl::cancelClicked() {
   reject();
}

void FileMapperDialogImpl::fillList() {
   int row = 0;
   Mapping::FileAppList::Iterator it;
   for ( it = m_pFileAppList->begin(); it != m_pFileAppList->end(); ++it ) {
      List->setText(row,0,(*it).wildcard);
      List->setText(row,1,(*it).app);
      List->setText(row,2,(*it).params);
      ((QCheckTableItem*)List->item(row,3))->setChecked((*it).isRegExp);
      ++row;
   }
   List->setCurrentCell(0,0);
}

void FileMapperDialogImpl::enterWhatsThisMode()
{
   QWhatsThis::enterWhatsThisMode();
}



syntax highlighted by Code2HTML, v. 0.9.1