/****************************************************************************
**
** Copyright (C) 1999-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>,
**                         Jose Hernandez <joseh@tesco.net>,
**                         Tom Mishima <tmishima@mail.at-m.or.jp>,
**                         Joerg Preiss <auba@auba.de>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** 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.
**
*****************************************************************************/

#ifndef GLOBALS_H_20010626
#define GLOBALS_H_20010626

//----------------------------------------------------------------------------

#include "config.h"

//----------------------------------------------------------------------------

#include <qlabel.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qdatetimeedit.h>
#include <qdir.h>
#include <qprocess.h>

//----------------------------------------------------------------------------

#include "profile.h"
#include "ProjectSettings.h"
#include "DirBase.h"
#include "DirConnector.h"

//----------------------------------------------------------------------------

#ifdef DEFINE_GLOBALS
  #define EXTERN
  //event monitoring
  DirConnector * fc;
  bool m_hasDirWatch;
#else
  #define EXTERN extern
#endif

//----------------------------------------------------------------------------

#define SIDEWIDTH (500) // 500 crashes on some systems

//----------------------------------------------------------------------------

//Add ProjectSettings keys here:
const char WORKDIR[]          = "Workdir";
const char DISABLED[]         = "Disabled";
const char SSHACCESS[]        = "SshAccess";
const char PAUTOUPDATE[]      = "AutoUpdate";
const char PROJECTTAGLIST[]   = "TagList";
const char CVSSERVER[]        = "CvsServerCmd";

//File properties
const int EXECUTABLE          =  1;
const int WRITEABLE           =  2;
const int READABLE            =  4;

//Access constants
const int RSH_EXT             = 16;
const int RSH_SERVER          = 32;

//Import and Checkout Dialog Vars:
//be carefull, these have to be equal to
//the presets defined in the enum used by ProfilesDialogImpl
const int PSERVER      =  0;
const int RSH          =  1;
const int LOCAL        =  2;
const int SSPI         =  3;

const int NOSSH            = 0;
const int USESSH           = 1;
const int USESSHAGENT      = 2;
const int USESSHAGENTVARS  = 3;

//Popupmenu defaults
const QString DEFDIRPOPUPMENU  = "29:17:27:11:26:35:0:31:37:26:13:14:26:8:33:10:26:9:6:25:23:26:19:21:20:26:16:26:2:";
const QString DEFFILEPOPUPMENU = "30:18:28:12:26:15:4:5:26:36:1:32:38:26:7:34:26:24:22:26:3:";

const char PLACEHOLDER_FOR_QUOTATION_MARKS[] = "^^^^^";

//----------------------------------------------------------------------------

class CvsConfig;
class CLinCVSLog;
class CMetaTextDecoder;
class CTextEncoder;

//----------------------------------------------------------------------------

//step by step reorganizing of global variables using namespaces
namespace CvsOptions {
   /**
      GZip compression level. 0 means no compression. 1 is the minimal
      compression level, 9 is the maximal level.
   */
   EXTERN unsigned int g_compression;

   /**
      Returns an empty string if compression is 0 or -z[1..9].
   */
   extern const QString cmprStr();
   
   /**
      Prune (remove) directories that are empty after being updated etc.
   */
   EXTERN bool g_bPruneDirs;
   
   /**
      Bring over new directories if run update and friends.
   */
   EXTERN bool g_bBringOverNewDirs;
   
   /**
      Show virtual dirs (query update all) only in filetab
   */
   EXTERN bool g_bShowVirtualInFiletab;
   
   /**
      Per-line diff precision
   */
   EXTERN int g_precision;
   
   /**
      Unified diff output
   */
   EXTERN bool g_bUnifiedDiffOutput;
   
   /**
      quiet CVS commands
   */
   EXTERN bool g_bQuietCvs;
   
   /**
      history period
   */
   EXTERN int g_historyPeriod;
}

namespace AutoUpdate {
   enum Level {
      OFF = 0,
      QUERY = 1,
      STATUS = 2,
      UPDATE = 3,
      QUERYALL = 4,
      UPDATEALL = 5
   };
}

namespace ExtApps {
   
   struct App {
      QString path;     //path (abs. or rel. + app file name
      QString options;
   };
   
   EXTERN App g_sshAgent;
   EXTERN App g_localShell;
   EXTERN App g_localBrowser;
   EXTERN App g_remoteBrowser;
   EXTERN App g_cvsRsh;
   EXTERN App g_diffProg;

   EXTERN QStringList g_sshKeyFiles;
}

namespace DirWatch {
   EXTERN bool b_useDirWatch;
   EXTERN bool b_isActive;
}

namespace Polling {
   enum Level {
      NONE = 0,
      CURRENT = 1,
      ALLDIRS = 2,
      ALLFILES = 3,
      ALLPROJECTS = 4
   };
   EXTERN int checkStatusLevel;
}

namespace LinCVSEvents {
   enum Type {
      T_WINNT_DIRWATCH = 65432
   };
}

namespace HighlightProperties {
   //we could give the user the possibility to change the font instead of 
   //switching only between normal/bold/italic. but is it useful?
   enum FontStyle {//Note: these styles are flags.
      FS_NORMAL = 0,
      FS_BOLD   = 1,
      FS_ITALIC = 2
   };
   
   struct Properties {
      FontStyle style;
      QColor    color;
   };
   
   //use syntax highlighting?
   EXTERN bool g_bUseSyntaxHighlighting;
   
   //used for (query) update and status
   EXTERN Properties g_updateQuestionMark;      //lines starting with ?
   EXTERN Properties g_updateModified;          //M
   EXTERN Properties g_updateNeedsUpdate;       //U and P
   EXTERN Properties g_updateMerging;           //affects onle the line "Merging differences"
   EXTERN Properties g_updateConflict;          //Conflict (all conflict lines)
   EXTERN Properties g_updateAdded;             //added file(s)
   EXTERN Properties g_updateRemoved;           //removed file(s)
   EXTERN Properties g_updateRemovedByOther;    //removed file(s) by another one
   
   //diff to console
   EXTERN Properties g_diffOld;     //lines starting with <
   EXTERN Properties g_diffNew;     //lines starting with >

   EXTERN Properties g_scmErr;      //cvs or svn error
}

namespace Font {
   //we use the string representations of fonts. if empty --> default font
   EXTERN QString g_general;
   EXTERN QString g_message;
   EXTERN QString g_diff; 
   
   //never we write this value to the config file, we must only save the 
   //default font set by qtconfig at runtime
   EXTERN QString g_default; 
}

namespace LookAndFeel {
   //use std-dialogs if true
   EXTERN bool g_stdDlg;
   EXTERN QDateEdit::Order g_dateTimeOrder;
   EXTERN QString g_dateTimeFormat;
   EXTERN bool g_b0AsParent;
   EXTERN bool g_bTopLevel;
   EXTERN Qt::WFlags g_nonModalF;
   EXTERN Qt::WFlags g_modalF;
}

namespace I18n {
   EXTERN CMetaTextDecoder* g_pTextDecoder;
   EXTERN QString g_nameOfDecoder;  //name of decoder used for all non file specific stuff
   
   EXTERN CTextEncoder* g_pTextEncoder;
   EXTERN QString g_nameOfEncoder;  //name of Encoder
   
   extern void init();
   extern void destroy();
}

namespace Debug {
   enum LogLevel {
      LL_LIKE_A_FISH = 0,              //little or nothing
      LL_THE_OLD_MAN_AND_THE_SEA = 1,  //almost nothing
      LL_INFO = 2,                     //log runtime infos
      LL_DEBUG = 3,                    //log infos and debug stuff
      LL_GOSSIP_MONGER = 4             //log all
   };
   
   EXTERN bool g_bDebug;
   EXTERN LogLevel g_logLevel;
   EXTERN CLinCVSLog* g_pLog;
}

namespace HistorySize {
   EXTERN unsigned int g_profiles;
   EXTERN unsigned int g_workdirs;
   EXTERN int g_commitinfo;
}

namespace SizeProperties {
   EXTERN QString g_fileHeader;
}

namespace Dialog {
   EXTERN bool g_showWarning;
}

namespace Misc {
#ifdef Q_WS_X11
   EXTERN QString g_rcPath;  // additional rcpath
#endif
   EXTERN bool    g_bVeryFirstStart;
}

namespace Mapping {
   struct FileAppItem {
      QString wildcard;
      QString app;
      QString params;
      bool isRegExp;
   };
   typedef QValueList<FileAppItem> FileAppList;
   EXTERN FileAppList openFileAppList;
   EXTERN FileAppList viewFileAppList;
}

//--- cfg values -------------------------------------------------------------

EXTERN int          WINVERSION;

EXTERN ProjectSettings *projectSettings;

EXTERN int          CHECKSTATUSINTERVALL; // [msec]
EXTERN int          AUTOUPDATEINTERVALL;  // [minutes]
EXTERN bool         AUTOUPDATE;

EXTERN int          PROGRESSINTERVALL;
EXTERN QString      CVSSTYLE;

EXTERN QString CVSIGNOREFILES;

EXTERN QString DIRPOPUPMENU;
EXTERN QString FILEPOPUPMENU;
EXTERN QString KEYBOARDSHORTCUTS;

EXTERN QStringList MODULEHISTORYLIST;
EXTERN QStringList WORKDIRHISTORYLIST;
EXTERN QStringList CHECKOUTASLIST;

//--- settings / dialog ------------------------------------------------------

// geometry
EXTERN int          GEOM_X;
EXTERN int          GEOM_Y;
EXTERN int          GEOM_WIDTH;
EXTERN int          GEOM_HEIGHT;
EXTERN int          SPLITTER_POS_H;
EXTERN int          SPLITTER_POS_V;
EXTERN int          WORKBENCH_COLUMN_WIDTH;
EXTERN QString      TOOLBARPOS;

//--- var --------------------------------------------------------------------

EXTERN QString  APPDIR;

EXTERN bool     KILLED;

EXTERN QString  CVSVERSION;
EXTERN QString  CVSPATH;
EXTERN QString  CVSPASSPATH;

EXTERN bool     globalListViewsEnabled;
EXTERN bool     ONTHEFLYSCANNING;
EXTERN bool     bOVERRIDEONTHEFLYSCANNING;
EXTERN bool     bSCANNONCVS;

EXTERN bool     globalStopAction;
EXTERN int      timeZoneDiffInSecs;
EXTERN bool     winOnly_isDayLight;
EXTERN QDateTime TIMEZERO;

EXTERN bool     bUseSsh;
EXTERN bool     bUseSshAgent;
EXTERN bool     bUseSshAgentVars;
EXTERN QProcess *sshProc;
EXTERN bool     sshAgentIsRunning;
EXTERN bool     sshAgentStarted;
EXTERN QString  sshAuthSock;
EXTERN QString  envSSH_AGENT_PID;
EXTERN QString  envSSH_AUTH_SOCK;

EXTERN QColor   SELECTION_COLOR_OF_LOGDLG[2];

EXTERN bool     bUSEEXTERNALDIFFFORSIDEBYSIDE;
EXTERN bool     bUseSmallIcons;
EXTERN bool     bStartedInDir;
EXTERN bool     bRWPermission;
EXTERN bool     bKeywordSuppression;
EXTERN bool     bDiffIgnoreWhiteSpace;

EXTERN QString  tmpDir;
EXTERN QString  iconDir;

EXTERN CvsConfig* conf;

EXTERN QStringList           proxyList;
EXTERN int                   outputLineOffset;

EXTERN QStringList           BINARYFILESPECLIST;

//lists for profiles, repositories etc.
EXTERN QStringList                cvsUsers;
EXTERN QStringList                cvsServers;
EXTERN QStringList                cvsRepositories;
EXTERN QStringList                cvsProfileNameList;
EXTERN QValueList<CLincvsProfile> cvsProfileContentList;

//--- functions --------------------------------------------------------------

extern void    initGlobals();
extern void    determineTimeZoneDiff();
extern bool    isInCvsPass(QString cvsRoot);
extern bool    writeToCvsPassFile(const QString& cvsRoot, const QString& pwd);
extern bool    removeFromCvsPassFile( QString cvsRoot);

/* extern int     analyzeCVSROOT(QString& connectMethod, QString& userName,  */
/*                              QString& host, QString& rootDir); */

extern int     analyzeCVSROOT( QString& method,
      QString& user,
      QString& passwd,
      QString& host,
      int& port,
      QString& path);

extern bool     extractCVSROOT( QString rootline,
      QString& method,
      QString& user,
      QString& passwd,
      QString& host,
      int& port,
      QString& path);

extern int     validateCVSROOT( QString rootline);

extern void    removeDoubleSlashes(QString& s);

extern void    startSshAgent();
extern void    checkSshAgent();
extern void    killSshAgent();

extern void    runExternal( QString arg, QDir *dir=0);
extern void    runExternal( QStringList args, QDir *dir=0);

//returns the filename of temp file or "" if the file could not created
extern QString writeTmpFile(QString text);
extern void writeUserHstFile(QString text);

//read the textfile with name fn
extern QString readTextFile(QString fn);

//returns the text of tmpDir/Template/rcsinfo or "" if file does not exist
extern QString readDefaultTemplateFile();

//write text to tmpDir/Template/rcsinfo
extern void writeDefaultTemplateFile(QString text);

//creates the temporarly directory
extern void createTmpDir();

//creates the Template dir in tmpDir
extern void createTemplateDir();

//returns the filename of created temp file or "" if the file could not be created
extern QString createTempFile(QString appendix = QString::null);
extern QString createHistoryFile();

//rearange order, so latest entry (&s) comes first, adapt size and prevent double entries
extern void adaptQStringList(const QString &s, QStringList *list, int size);

//removes all multiple entries in pList. it works on the passed list itself!!!
extern void simplifyStringList(QStringList* pList);
extern void cutList(QStringList* pList, int allowedSize);

//masque filenames containing whitespaces for use with InteractiveCmdThread
extern QString masqWs(const QString &str);
extern QString umasqWs(QString str);
extern void masqQuoteMarks(QStringList *pList);

//validation of passed command line options
extern QString validateOptions(const QString options);

//open URL[s] with the remote browser
extern void openUrlWithRemoteBrowser(const QString url);
extern void openUrlsWithRemoteBrowser(const QStringList urlList);

//mapping
extern Mapping::FileAppItem getMatchForWildcard(const QStringList& nameList, const Mapping::FileAppList& appList);
extern bool masqedFilenamesForPlaceholders(QString& params, const QStringList& nameList);

//wrappers for platform specific funktions
extern bool setPermission(const QFile& file, int perm);
extern bool rename(const QString& src, const QString& dst);

//proxy
extern QString getProxy(const QString& userAtHost);

//wait for usecs micro seconds
extern void wait(int usecs);

//system linefeed
extern QString getSystemLF();

//eventmonitoring
extern bool initMonitoring();
extern DirConnector* getDirConnector();
extern bool hasDirWatch();
extern void releaseMonitoring();
extern bool addMonitoredDir(DirBase*);
extern void releaseMonitoredDir(DirBase*);
extern DirBase* checkMonitoredEvent(QString&,bool&);
extern void suspendDirWatch();
extern void resumeDirWatch();
extern void lockDirWatch();
extern void unlockDirWatch();

//--- end of file ------------------------------------------------------------

#endif   //GLOBALS_H_20010626

