void logAdapter::setLogFileNumAndSize(int logNum, int sizeOfPerFile) {
  string homeDir(UtilAll::getHomeDirectory());
  homeDir.append("/logs/rocketmq-cpp/");
  m_logSink->locked_backend()->set_file_collector(sinks::file::make_collector(
      keywords::target = homeDir,
      keywords::max_size = logNum * sizeOfPerFile * 1024 * 1024));
}
logAdapter::logAdapter() : m_logLevel(eLOG_LEVEL_INFO) {
  string homeDir(UtilAll::getHomeDirectory());
  homeDir.append("/logs/rocketmq-cpp/");
  m_logFile += homeDir;
  std::string fileName =
      UtilAll::to_string(getpid()) + "_" + "rocketmq-cpp.log.%N";
  m_logFile += fileName;

  // boost::log::expressions::attr<
  // boost::log::attributes::current_thread_id::value_type>("ThreadID");
  boost::log::register_simple_formatter_factory<
      boost::log::trivial::severity_level, char>("Severity");
  m_logSink = logging::add_file_log(
      keywords::file_name = m_logFile,
      keywords::rotation_size = 100 * 1024 * 1024,
      keywords::time_based_rotation =
          sinks::file::rotation_at_time_point(0, 0, 0),
      keywords::format = "[%TimeStamp%](%Severity%):%Message%",
      keywords::min_free_space = 300 * 1024 * 1024, keywords::target = homeDir,
      keywords::max_size = 200 * 1024 * 1024,  // max keep 3 log file defaultly
      keywords::auto_flush = true);
  logging::core::get()->set_filter(logging::trivial::severity >=
                                   logging::trivial::info);

  logging::add_common_attributes();
}
QString KShell::tildeExpand(const QString &fname)
{
    if (!fname.isEmpty() && fname[0] == QLatin1Char('~')) {
        int pos = fname.indexOf(QLatin1Char('/'));
        if (pos < 0) {
            return homeDir(fname.mid(1));
        }
        QString ret = homeDir(fname.mid(1, pos - 1));
        if (!ret.isNull()) {
            ret += fname.midRef(pos);
        }
        return ret;
    } else if (fname.length() > 1 && fname[0] == QLatin1Char(ESCAPE) && fname[1] == QLatin1Char('~')) {
        return fname.mid(1);
    }
    return fname;
}
Beispiel #4
0
int main( int argc, char* argv[] , char *envp[])
{
  QApplication myapp( argc, argv );
  
  QString rcfil;
  QString bibl;
  QStringList lines;
  QString homeDir( QDir::homeDirPath() );
  
  rcfil.append(homeDir);
  rcfil.append("/.olfixrc");	/* resursfil, configfil		*/
  QFile file(rcfil);
  /***************************************************/
  /*  Testa om $HOME/.olfixrc existerar, om inte skapa den.    */
  /***************************************************/
  if ( !file.open( IO_ReadOnly )){
      file.close();
      find_homedir(envp);		/* Hämta $HOME		    			*/
      copy_rcfile();			/* Kopiera från /opt/olfix/script/.olficrc till  $HOME/.olfixrc	*/
  }
/*  fprintf(stderr,"Start 2 OLFIXW\n");	*/
/****************************************/
/*  Vilken databas ska användas?		*/
/****************************************/      
   which_database(envp);
/*fprintf(stderr,"Start 3 OLFIXW\n");	*/
  /****************************************/
  /*  Läs in data från $HOME/.olfixrc här	 */
  /****************************************/
   file.close();
   if ( file.open( IO_ReadOnly ) ) {
	QTextStream stream( &file );
	QString line;
        while ( !stream.eof() ) {
            line = stream.readLine(); // line of text excluding '\n'
            int i = line.find( QRegExp("PATH="), 0 );    // i == 1
	    if ( i == 0){
	    	int l =line.length();
	    	bibl = line.mid(5,l);
	    }
            lines += line;
        }
	file.close();
//	fprintf(stdout,"Bibliotek=%s\n",bibl.latin1() );
  }else{
      	qWarning( "Cannot find the $HOME/.olfixrc file" );
 	fprintf(stderr,"%s\n", rcfil.latin1() );
  }
  QDir::setCurrent ( bibl );
 
  frmOlfix* mywidget = new frmOlfix();
  mywidget->lineEditDatabase->setText(database);
  
  myapp.setMainWidget( mywidget);
  mywidget->show();
  return myapp.exec();
}
void ZeroTierOneService::threadMain()
throw()
{
    ZT_SVCDBG("ZeroTierOneService::threadMain()\r\n");

restart_node:
    try {
        {
            ZeroTier::Mutex::Lock _l(_lock);
            delete _service;
            _service = (ZeroTier::OneService *)0; // in case newInstance() fails
            _service = ZeroTier::OneService::newInstance(
                           ZeroTier::OneService::platformDefaultHomePath().c_str(),
                           ZT_DEFAULT_PORT);
        }
        switch(_service->run()) {
        case ZeroTier::OneService::ONE_UNRECOVERABLE_ERROR: {
            std::string err("ZeroTier One encountered an unrecoverable error: ");
            err.append(_service->fatalErrorMessage());
            err.append(" (restarting in 5 seconds)");
            WriteEventLogEntry(const_cast <PSTR>(err.c_str()),EVENTLOG_ERROR_TYPE);
            Sleep(5000);
        }
        goto restart_node;

        case ZeroTier::OneService::ONE_IDENTITY_COLLISION: {
            std::string homeDir(ZeroTier::OneService::platformDefaultHomePath());
            delete _service;
            _service = (ZeroTier::OneService *)0;
            std::string oldid;
            ZeroTier::OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
            if (oldid.length()) {
                ZeroTier::OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
                ZeroTier::OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
                ZeroTier::OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
            }
        }
        goto restart_node;

        default: // normal termination
            break;
        }
    } catch ( ... ) {
        // sanity check, shouldn't happen since Node::run() should catch all its own errors
        // could also happen if we're out of memory though!
        WriteEventLogEntry("unexpected exception (out of memory?) (trying again in 5 seconds)",EVENTLOG_ERROR_TYPE);
        Sleep(5000);
        goto restart_node;
    }

    {
        ZeroTier::Mutex::Lock _l(_lock);
        delete _service;
        _service = (ZeroTier::OneService *)0;
    }
}
Beispiel #6
0
QString KUser::faceIconPath() const
{
    QString pathToFaceIcon(homeDir() + QDir::separator() + QLatin1String(".face.icon"));

    if (QFile::exists(pathToFaceIcon)) {
        return pathToFaceIcon;
    }

    return QString();
}
QString ApplicationInfo::makeSubhomePath(const QString &path, ApplicationInfo::HomedirType type)
{
	if (path.indexOf("..") == -1) { // ensure its in home dir
		QDir dir(homeDir(type) + "/" + path);
		if (!dir.exists()) {
			dir.mkpath(".");
		}
		return dir.path();
	}
	return QString();
}
TEST_FIXTURE(EnchantTestFixture, 
             GetUserConfigDir_BlankFromRegistryConfigHomeDir_RegistryEntryIgnored)
{
  std::string homeDir("");
  SetRegistryHomeDir(homeDir);

  GSList * enchantUserConfigDirs = enchant_get_user_config_dirs();

  CHECK(enchantUserConfigDirs);
  GSList* iter = enchantUserConfigDirs->next;
  CHECK(iter);
  
  CHECK_EQUAL(GetEnchantHomeDirFromBase(g_get_home_dir()), (gchar*) iter->data);

  g_slist_free(enchantUserConfigDirs);
}
Beispiel #9
0
std::string Environment::absolutePath(const std::string& name) const {
	std::string tmpName = Util::replace(name, PathResolver());

	if ( tmpName.find("~/") == 0 )
		tmpName = homeDir() + tmpName.substr(1);

	bool trailingSlash = !tmpName.empty() && tmpName[tmpName.size()-1] == '/';

	char absolutePath[PATH_MAX];
	if ( realpath(tmpName.c_str(), absolutePath) )
		tmpName = absolutePath;

	if ( trailingSlash && !tmpName.empty() && tmpName[tmpName.size()-1] != '/' )
		tmpName += '/';

	return tmpName;
}
Beispiel #10
0
FilePrivateKeyStorage::FilePrivateKeyStorage()
{
  // Note: We don't use <filesystem> support because it is not "header-only" and
  // require linking to libraries.
  // TODO: Handle non-unix file system paths which don't use '/'.
  const char* home = getenv("HOME");
  if (!home || *home == '\0')
    // Don't expect this to happen;
    home = ".";
  string homeDir(home);
  if (homeDir[homeDir.size() - 1] == '/' || homeDir[homeDir.size() - 1] == '\\')
    // Strip the ending path separator.
    homeDir.erase(homeDir.size() - 1);

  keyStorePath_ = homeDir + '/' + ".ndn/ndnsec-tpm-file";
  // TODO: Handle non-unix file systems which don't have "mkdir -p".
  ::system(("mkdir -p " + keyStorePath_).c_str());
}
Beispiel #11
0
OfxHttpRequest::OfxHttpRequest(const QString& type, const QUrl &url, const QByteArray &postData, const QMap<QString, QString>& metaData, const QUrl& dst, bool showProgressInfo) :
    d(new Private),
    m_dst(dst),
    m_postJob(0),
    m_getJob(0)
{
  m_eventLoop = new QEventLoop(qApp->activeWindow());

  QDir homeDir(QDir::home());
  if (homeDir.exists("ofxlog.txt")) {
    d->m_fpTrace.setFileName(QString("%1/ofxlog.txt").arg(QDir::homePath()));
    d->m_fpTrace.open(QIODevice::WriteOnly | QIODevice::Append);
  }

  KIO::JobFlag jobFlags = KIO::DefaultFlags;
  if (!showProgressInfo)
    jobFlags = KIO::HideProgressInfo;

  KIO::Job* job;
  if(type.toLower() == QStringLiteral("get")) {
    job = m_getJob = KIO::copy(url, dst, jobFlags);
  } else {
    job = m_postJob = KIO::http_post(url, postData, jobFlags);
    m_postJob->addMetaData("content-type", "Content-type: application/x-ofx");
    m_postJob->addMetaData(metaData);
    connect(job, SIGNAL(data(KIO::Job*,QByteArray)), this, SLOT(slotOfxData(KIO::Job*,QByteArray)));
    connect(job, SIGNAL(connected(KIO::Job*)), this, SLOT(slotOfxConnected(KIO::Job*)));
  }

  if (d->m_fpTrace.isOpen()) {
    QTextStream ts(&d->m_fpTrace);
    ts << "url: " << url.toDisplayString() << "\n";
    ts << "request:\n" << QString(postData) << "\n" << "response:\n";
  }

  connect(job, SIGNAL(result(KJob*)), this, SLOT(slotOfxFinished(KJob*)));

  job->start();

  qDebug("Starting eventloop");
  if (m_eventLoop)
    m_eventLoop->exec();
  qDebug("Ending eventloop");
}
Beispiel #12
0
const ModuleFileInfomations& GetModuleFileInformations()
{
	static ModuleFileInfomations __s_mi;
	static BOOL bLoad = FALSE;
	
	if(!bLoad)
	{
		// Get application's full path.
		
		::GetModuleFileName(NULL, __s_mi.strFullPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
		__s_mi.strFullPath.ReleaseBuffer();
		
		// Break full path into seperate components.
		_splitpath(
			__s_mi.strFullPath, 
			__s_mi.strDrive.GetBufferSetLength(_MAX_DRIVE + 1),
			__s_mi.strDir.GetBufferSetLength(_MAX_DIR + 1),
			__s_mi.strName.GetBufferSetLength(_MAX_FNAME + 1),
			__s_mi.strExt.GetBufferSetLength(_MAX_EXT + 1));
		__s_mi.strDrive.ReleaseBuffer();
		__s_mi.strDir.ReleaseBuffer();
		__s_mi.strName.ReleaseBuffer();
		__s_mi.strExt.ReleaseBuffer();
		
		
		TCHAR   sDrive[_MAX_DRIVE];   
		TCHAR   sDir[_MAX_DIR];   
		TCHAR   sFilename[_MAX_FNAME],Filename[_MAX_FNAME];   
		TCHAR   sExt[_MAX_EXT];   
		GetModuleFileName(AfxGetInstanceHandle(),   Filename,   _MAX_PATH);   
		_tsplitpath(Filename,   sDrive,   sDir,   sFilename,   sExt);   
		CString   homeDir(CString(sDrive)   +   CString(sDir));   
		int   nLen   =   homeDir.GetLength();   
		if(homeDir.GetAt(nLen-1)   !=   _T('\\'))   
			homeDir   +=   _T('\\');   
		
		__s_mi.strPath = homeDir;
		
		bLoad = TRUE;
	}
	
	return __s_mi;
}
void WizUpdaterDialog::doOldDatabaseUpgrade()
{
    QDir homeDir(QDir::homePath());
    QString oldDataStorePath = QDir::homePath() + "/WizNote/";
    QString newDataStorePath = QDir::homePath() + "/.wiznote/";

    bool ret = homeDir.rmdir(newDataStorePath);

    if (ret) {
        homeDir.rename(oldDataStorePath, newDataStorePath);
    } else {
        QMessageBox::critical(this, tr("Error"), tr("the .wiznote directory should be empty, please contect R&D team!"));
        return;
    }

    QDir rootDir(newDataStorePath);

    rootDir.remove("wiznote.ini");
    setGuiNotify("Remove wiznote.ini");
    rootDir.remove("wiznote.log");
    setGuiNotify("Remove wiznote.log");

    // enum each user
    CWizStdStringArray folders;
    WizEnumFolders(newDataStorePath, folders, 0);
    foreach (const QString& folder, folders) {
        QDir userDir(folder);

        QString strOldNotes = folder + "Notes/";
        QString strOldAttaches = folder + "Attachments/";

        // rename notes data
        CWizStdStringArray notes;
        WizEnumFiles(strOldNotes, "*.ziw", notes, 0);
        foreach (const QString& note, notes) {
            QDir dirNote(strOldNotes);
            // 36 chars for GUID and 4 chars for extention
            QString strNewName = strOldNotes + "{" + note.right(40).left(36) + "}";
            dirNote.rename(note, strNewName);
            setGuiNotify(QString("Rename %1").arg(note));
        }
Beispiel #14
0
QT_BEGIN_NAMESPACE

/*! \internal
Gets the current KDE home path
like "/home/troll/.kde"
*/
QString QKde::kdeHome()
{
    static QString kdeHomePath;
    if (kdeHomePath.isEmpty()) {
        kdeHomePath = QString::fromLocal8Bit(qgetenv("KDEHOME"));
        if (kdeHomePath.isEmpty()) {
            QDir homeDir(QDir::homePath());
            QString kdeConfDir(QLatin1String("/.kde"));
            if (4 == X11->desktopVersion && homeDir.exists(QLatin1String(".kde4")))
            kdeConfDir = QLatin1String("/.kde4");
            kdeHomePath = QDir::homePath() + kdeConfDir;
        }
    }
    return kdeHomePath;
}
Beispiel #15
0
int main( int argc, char* argv[] )
{
  QApplication myapp( argc, argv );

  frmPrtFoljesedel* mywidget = new frmPrtFoljesedel();

  // mywidget->lineEditBestNr->setText(QString(argv[1]));

  QString rcfil;
  QString bibl;
  QStringList lines;
  QString homeDir( QDir::homeDirPath() );
   rcfil.append(homeDir);
   rcfil.append("/.olfixrc");	// configfil
// Läs in config filen här
   QFile file(rcfil);
   if ( file.open( IO_ReadOnly ) ) {
	QTextStream stream( &file );
	QString line;
        while ( !stream.eof() ) {
            line = stream.readLine(); // line of text excluding '\n'
            int i = line.find( QRegExp("PATH="), 0 );    // i == 1
	    if ( i == 0){
	    	int l =line.length();
	    	bibl = line.mid(5,l);
	    }
            lines += line;
        }
	file.close();
    }else{
	QMessageBox::warning( mywidget, "OLFIX - FSORDW",
 	"Kan inte hitta filen $HOME/.olfixrc.\n FSORDW kommer inte att fungera!\n");
	qWarning( "Cannot find the $HOME/.olfixrc file" );
    }
   QDir::setCurrent ( bibl );

  myapp.setMainWidget( mywidget );
  mywidget->show();
  return myapp.exec();
}
Beispiel #16
0
void Screenshot::saveScreenshot()
{
    QString format = "png";
    QString initialPath = QDir::currentPath() + tr("/untitled.") + format;
#ifdef Q_WS_QWS

    QString  fileName = "sc_" + QDateTime::currentDateTime().toString();
    fileName.replace(QRegExp("'"), "");
    fileName.replace(QRegExp(" "), "_");
    fileName.replace(QRegExp(":"), ".");
    fileName.replace(QRegExp(","), "");
    QString dirName = QDir::homePath() + "/Documents/image/png/";

    if ( !QDir( dirName).exists() ) {
        QDir homeDir(QDir::homePath());
        homeDir.mkpath("Documents/image/png");
    }
#else
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                       initialPath,
                       tr("%1 Files (*.%2);;All Files (*)")
                       .arg(format.toUpper())
                       .arg(format));
    if (!fileName.isEmpty())
#endif
#ifdef Q_WS_QWS
    QString new_file = dirName+"/"+fileName+".png";
    originalPixmap.save(new_file, format.toAscii());
    QContent content;
    content.setName( fileName);
    content.setFile( new_file );
    content.commit();

#else
    originalPixmap.save(fileName, format.toAscii());
#endif


}
Beispiel #17
0
int UserManagerBackend::validateHome(QString home) {
    int result = 0;
    QFileInfo homeDir(home);
    QUrl *homePath = new QUrl(home);
    if (home == "") {
	result = 1;
    }
    if ((! homeDir.isDir()) && (home != "")) {
	result = 3;
    }
    if ((homeLocRegExp.indexIn(home) == -1) && (home != "")) {
	result = 4;
    }    
    if ((homeDir.isFile()) && (home != "")) {
	result = 5;
    }
    if ((! homePath->isValid()) && (home != "")) {
	result = 2;
    }
    
    return result;
}
QStringList QGuiPlatformPlugin::iconThemeSearchPaths()
{
    QStringList paths;
#if defined(Q_WS_X11)
    QString xdgDirString = QFile::decodeName(getenv("XDG_DATA_DIRS"));
    if (xdgDirString.isEmpty())
        xdgDirString = QLatin1String("/usr/local/share/:/usr/share/");

    QStringList xdgDirs = xdgDirString.split(QLatin1Char(':'));

    for (int i = 0 ; i < xdgDirs.size() ; ++i) {
        QDir dir(xdgDirs[i]);
        if (dir.exists())
            paths.append(dir.path() + QLatin1String("/icons"));
    }
    if (X11->desktopEnvironment == DE_KDE) {
        paths << QLatin1Char(':') + QKde::kdeHome() + QLatin1String("/share/icons");
        QStringList kdeDirs = QFile::decodeName(getenv("KDEDIRS")).split(QLatin1Char(':'));
        for (int i = 0 ; i< kdeDirs.count() ; ++i) {
            QDir dir(QLatin1Char(':') + kdeDirs.at(i) + QLatin1String("/share/icons"));
            if (dir.exists())
                paths.append(dir.path());
        }
    }

    // Add home directory first in search path
    QDir homeDir(QDir::homePath() + QLatin1String("/.icons"));
    if (homeDir.exists())
        paths.prepend(homeDir.path());
#endif

#if defined(Q_WS_WIN)
    paths.append(qApp->applicationDirPath() + QLatin1String("/icons"));
#elif defined(Q_WS_MAC)
    paths.append(qApp->applicationDirPath() + QLatin1String("/../Resources/icons"));
#endif
    return paths;
}
Beispiel #19
0
int main( int argc, char* argv[] )
{
  QApplication myapp( argc, argv );

  QString rcfil;
  QString bibl;
  QStringList lines;
  QString homeDir( QDir::homeDirPath() );
   rcfil.append(homeDir);
   rcfil.append("/.olfixrc");	// configfil
// Läs in config filen här
   QFile file(rcfil);
   if ( file.open( IO_ReadOnly ) ) {
	QTextStream stream( &file );
	QString line;
        while ( !stream.eof() ) {
            line = stream.readLine(); // line of text excluding '\n'
            int i = line.find( QRegExp("PATH="), 0 );    // i == 1
	    if ( i == 0){
	    	int l =line.length();
	    	bibl = line.mid(5,l);
	    }
            lines += line;
        }
	file.close();
    }else{
	qWarning( "Cannot find the $HOME/.olfixrc file" );
 	fprintf(stdout,"%s\n", rcfil.latin1() );
    }
   QDir::setCurrent ( bibl );

  frmListValuta ListaValuta;

  myapp.setMainWidget( &ListaValuta );
  ListaValuta.show();
  myapp.exec();
}
Beispiel #20
0
std::wstring Gosu::userSettingsPrefix()
{
    return homeDir() + L"/.";
}
Beispiel #21
0
static void mapBlockChainFiles()
{
    std::string coinName(
        #if defined REDDCOIN
            "/.reddcoin/"
        #else
            "/.bitcoin/"
        #endif
    );

    const char *home = getenv("HOME");
    if(0==home) {
        warning("could not getenv(\"HOME\"), using \".\" instead.");
        home = ".";
    }

    std::string homeDir(home);
    std::string blockDir = homeDir + coinName + std::string("blocks");

    struct stat statBuf;
    int r = stat(blockDir.c_str(), &statBuf);
    bool oldStyle = (r<0 || !S_ISDIR(statBuf.st_mode));

    int blkDatId = oldStyle ? 1 : 0;
    const char *fmt = oldStyle ? "blk%04d.dat" : "blocks/blk%05d.dat";
    while(1) {

        char buf[64];
        sprintf(buf, fmt, blkDatId++);

        std::string blockMapFileName =
            homeDir                             +
            coinName                            +
            std::string(buf)
        ;

        int blockMapFD = open(blockMapFileName.c_str(), O_DIRECT | O_RDONLY);
        if(blockMapFD<0) {
            if(1<blkDatId) break;
            sysErrFatal(
                "failed to open block chain file %s",
                blockMapFileName.c_str()
            );
        }

        struct stat statBuf;
        int r = fstat(blockMapFD, &statBuf);
        if(r<0) sysErrFatal( "failed to fstat block chain file %s", blockMapFileName.c_str());

        size_t mapSize = statBuf.st_size;
        void *pMap = mmap(0, mapSize, PROT_READ, MAP_PRIVATE, blockMapFD, 0);
        if(((void*)-1)==pMap) {
            sysErrFatal(
                "failed to mmap block chain file %s",
                blockMapFileName.c_str()
            );
        }

        Map map;
        map.size = mapSize;
        map.fd = blockMapFD;
        map.name = blockMapFileName;
        map.p = (const uint8_t*)pMap;
        mapVec.push_back(map);
    }
}
Beispiel #22
0
void EnvDialog::accept() {
  int id;
  
  if (ed_id->text().isEmpty() ||
      (sscanf((const char *) ed_id->text(), "%d", &id) != 1) ||
      (id < 2) ||
      (id > 127)) {
    QMessageBox::critical(this, "Bouml", TR("Invalid identifier, must be an integer between 2 and 127"));
    return;
  }
  
  int l, t, r, b;
  BooL ok_l, ok_t, ok_r, ok_b;
  
  setCoord(l, ok_l, ed_xmin);
  setCoord(t, ok_t, ed_ymin);
  setCoord(r, ok_r, ed_xmax);
  setCoord(b, ok_b, ed_ymax);
  
  if (ok_l && ok_t && ok_r && ok_b) {
    if ((l < 0) || (t < 0) || (r < 0) || (b < 0)) {
      QMessageBox::critical(this, "Bouml",
			    TR("Invalid DEFAULT SCREEN : coordinates can't be negative"));
      return;
    }
    else if ((l != 0) || (t != 0) || (r != 0) || (b != 0)) {
      if (r <= l) {
	QMessageBox::critical(this, "Bouml",
			      TR("Invalid DEFAULT SCREEN : the right must be greater than the left"));
	return;
      }
      
      if (b <= t) {
	QMessageBox::critical(this, "Bouml",
			      TR("Invalid DEFAULT SCREEN : the bottom must be greater than the top"));
	return;
      }
      
      if ((r - l) < 500)
	QMessageBox::warning(this, "Bouml",
			     TR("small DEFAULT SCREEN, width less than 500 points !"));
      
      if ((b - t) < 500)
	QMessageBox::warning(this, "Bouml",
			     TR("small DEFAULT SCREEN, height less than 500 points !"));
    }
  }
  else {
    QMessageBox::critical(this, "Bouml",
			  TR("Invalid DEFAULT SCREEN"
			     "To not specify the desktop all values must be empty or null."
			     "Else the values must be non negative, the right must be greater\n"
			     "than the left, and the bottom must be greater than the top"));
    return;
  }
  
  // note : QFile fp(QDir::home().absFilePath(".boumlrc")) doesn't work
  // if the path contains non latin1 characters, for instance cyrillic !
  QString s = homeDir().absFilePath(".boumlrc");
  FILE * fp = fopen((const char *) s, "w");
  
















  
  if (fp == 0) {
    QMessageBox::critical(this, "Bouml", "cannot write in '" + s + "'");
    if (conversion)
      exit(-1);
    else
      return;
  }
  
  fprintf(fp, "ID %d\n", id);
  
  if (! ed_doc->text().isEmpty())
    fprintf(fp, "MANUAL %s\n", (const char *) ed_doc->text());
  
  if (! ed_navigator->text().isEmpty())
    fprintf(fp, "NAVIGATOR %s\n", (const char *) ed_navigator->text());
  
  if (! ed_template->text().isEmpty())
    fprintf(fp, "TEMPLATE %s\n", (const char *) ed_template->text());
  
  if (! ed_editor->text().isEmpty())
    fprintf(fp, "EDITOR %s\n", (const char *) ed_editor->text());
  
  if (! ed_lang->text().isEmpty())
    fprintf(fp, "LANG %s\n", (const char *) ed_lang->text());
  else
    fputs("NOLANG\n", fp);
  
  if (! cb_charset->currentText().isEmpty())
    fprintf(fp, "CHARSET %s\n", (const char *) cb_charset->currentText());
  
  if (!ed_xmin->text().isEmpty() && 
      !ed_xmax->text().isEmpty() &&
      !ed_ymin->text().isEmpty() &&
      !ed_ymax->text().isEmpty()) {
    fprintf(fp, "DESKTOP %d %d %d %d\n", l, t, r, b);
  }
  
  fclose(fp);
  
  QDialog::accept();
}
Beispiel #23
0
QStringList KShell::splitArgs( const QString &args, Options flags, Errors *err)
{
    QStringList ret;
    bool firstword = flags & AbortOnMeta;

    for (int pos = 0; ; ) {
        QChar c;
        do {
            if (pos >= args.length())
                goto okret;
            c = args.unicode()[pos++];
        } while (c.isSpace());
        QString cret;
        if ((flags & TildeExpand) && c == QLatin1Char('~')) {
            int opos = pos;
            for (; ; pos++) {
                if (pos >= args.length())
                    break;
                c = args.unicode()[pos];
                if (c == QLatin1Char('/') || c.isSpace())
                    break;
                if (isQuoteMeta( c )) {
                    pos = opos;
                    c = QLatin1Char('~');
                    goto notilde;
                }
                if ((flags & AbortOnMeta) && isMeta( c ))
                    goto metaerr;
            }
            QString ccret = homeDir( args.mid(opos, pos-opos) );
            if (ccret.isEmpty()) {
                pos = opos;
                c = QLatin1Char('~');
                goto notilde;
            }
            if (pos >= args.length()) {
                ret += ccret;
                goto okret;
            }
            pos++;
            if (c.isSpace()) {
                ret += ccret;
                firstword = false;
                continue;
            }
            cret = ccret;
        }
        // before the notilde label, as a tilde does not match anyway
        if (firstword) {
            if (c == QLatin1Char('_') ||
                (c >= QLatin1Char('A') && c <= QLatin1Char('Z')) ||
                (c >= QLatin1Char('a') && c <= QLatin1Char('z')))
            {
                int pos2 = pos;
                QChar cc;
                do {
                    if (pos2 >= args.length()) {
                        // Exactly one word
                        ret += args.mid(pos - 1);
                        goto okret;
                    }
                    cc = args.unicode()[pos2++];
                } while (cc == QLatin1Char('_') ||
                       (cc >= QLatin1Char('A') && cc <= QLatin1Char('Z')) ||
                       (cc >= QLatin1Char('a') && cc <= QLatin1Char('z')) ||
                       (cc >= QLatin1Char('0') && cc <= QLatin1Char('9')));
                if (cc == QLatin1Char('='))
                    goto metaerr;
            }
        }
      notilde:
        do {
            if (c == QLatin1Char('\'')) {
                int spos = pos;
                do {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                } while (c != QLatin1Char('\''));
                cret += args.mid(spos, pos-spos-1);
            } else if (c == QLatin1Char('"')) {
                for (;;) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                    if (c == QLatin1Char('"'))
                        break;
                    if (c == QLatin1Char('\\')) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        if (c != QLatin1Char('"') &&
                            c != QLatin1Char('\\') &&
                            !((flags & AbortOnMeta) &&
                              (c == QLatin1Char('$') ||
                               c == QLatin1Char('`'))))
                            cret += QLatin1Char('\\');
                    } else if ((flags & AbortOnMeta) &&
                                (c == QLatin1Char('$') ||
                                 c == QLatin1Char('`')))
                        goto metaerr;
                    cret += c;
                }
            } else if (c == QLatin1Char('$') && pos < args.length() &&
                       args.unicode()[pos] == QLatin1Char('\'')) {
                pos++;
                for (;;) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                    if (c == QLatin1Char('\''))
                        break;
                    if (c == QLatin1Char('\\')) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        switch (c.toAscii()) {
                        case 'a': cret += QLatin1Char('\a'); break;
                        case 'b': cret += QLatin1Char('\b'); break;
                        case 'e': cret += QLatin1Char('\033'); break;
                        case 'f': cret += QLatin1Char('\f'); break;
                        case 'n': cret += QLatin1Char('\n'); break;
                        case 'r': cret += QLatin1Char('\r'); break;
                        case 't': cret += QLatin1Char('\t'); break;
                        case '\\': cret += QLatin1Char('\\'); break;
                        case '\'': cret += QLatin1Char('\''); break;
                        case 'c':
                            if (pos >= args.length())
                                goto quoteerr;
                            cret += args.unicode()[pos++].toAscii() & 31;
                            break;
                        case 'x':
                          {
                            if (pos >= args.length())
                                goto quoteerr;
                            int hv = fromHex( args.unicode()[pos++] );
                            if (hv < 0)
                                goto quoteerr;
                            if (pos < args.length()) {
                                int hhv = fromHex( args.unicode()[pos] );
                                if (hhv > 0) {
                                    hv = hv * 16 + hhv;
                                    pos++;
                                }
                                cret += QChar( hv );
                            }
                            break;
                          }
                        default:
                            if (c.toAscii() >= '0' && c.toAscii() <= '7') {
                                char cAscii = c.toAscii();
                                int hv = cAscii - '0';
                                for (int i = 0; i < 2; i++) {
                                    if (pos >= args.length())
                                        break;
                                    c = args.unicode()[pos];
                                    if (c.toAscii() < '0' || c.toAscii() > '7')
                                        break;
                                    hv = hv * 8 + (c.toAscii() - '0');
                                    pos++;
                                }
                                cret += QChar( hv );
                            } else {
                                cret += QLatin1Char('\\');
                                cret += c;
                            }
                            break;
                        }
                    } else
                        cret += c;
                }
            } else {
                if (c == QLatin1Char('\\')) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                } else if ((flags & AbortOnMeta) && isMeta( c ))
                    goto metaerr;
                cret += c;
            }
            if (pos >= args.length())
                break;
            c = args.unicode()[pos++];
        } while (!c.isSpace());
        ret += cret;
        firstword = false;
    }

  okret:
    if (err)
        *err = NoError;
    return ret;

  quoteerr:
    if (err)
        *err = BadQuoting;
    return QStringList();

  metaerr:
    if (err)
        *err = FoundMeta;
    return QStringList();
}
Beispiel #24
0
bool CodeLiteApp::OnInit()
{
    // Set the log file verbosity
    FileLogger::OpenLog("codelite.log", clConfig::Get().Read("LogVerbosity", FileLogger::Error));
    CL_DEBUG(wxT("Starting codelite..."));


#if defined(__WXGTK__) || defined(__WXMAC__)

    // block signal pipe
    sigset_t mask_set;
    sigemptyset(&mask_set);
    sigaddset(&mask_set, SIGPIPE);
    sigprocmask(SIG_SETMASK, &mask_set, NULL);

    // Handle sigchld
    CodeLiteBlockSigChild();

#ifdef __WXGTK__
    // Insall signal handlers
    signal(SIGSEGV, WaitForDebugger);
    signal(SIGABRT, WaitForDebugger);
#endif

#endif
    wxSocketBase::Initialize();

// #if wxUSE_ON_FATAL_EXCEPTION
//     //trun on fatal exceptions handler
//     wxHandleFatalExceptions(true);
// #endif

#ifdef __WXMSW__
    // as described in http://jrfonseca.dyndns.org/projects/gnu-win32/software/drmingw/
    // load the exception handler dll so we will get Dr MinGW at runtime
    m_handler = LoadLibrary(wxT("exchndl.dll"));

// Enable this process debugging priviliges
// EnableDebugPriv();
#endif

#ifdef USE_POSIX_LAYOUT
    wxStandardPaths::Get().IgnoreAppSubDir("bin");
#endif

    // Init resources and add the PNG handler
    wxSystemOptions::SetOption(_T("msw.remap"), 0);
    wxSystemOptions::SetOption("msw.notebook.themed-background", 0);
    wxXmlResource::Get()->InitAllHandlers();
    wxImage::AddHandler(new wxPNGHandler);
    wxImage::AddHandler(new wxCURHandler);
    wxImage::AddHandler(new wxICOHandler);
    wxImage::AddHandler(new wxXPMHandler);
    wxImage::AddHandler(new wxGIFHandler);
    InitXmlResource();

    wxLog::EnableLogging(false);
    wxString homeDir(wxEmptyString);

    // parse command line
    wxCmdLineParser parser;
    parser.SetDesc(cmdLineDesc);
    parser.SetCmdLine(wxAppBase::argc, wxAppBase::argv);
    if(parser.Parse() != 0) {
        return false;
    }

    if(parser.Found(wxT("h"))) {
        // print usage
        parser.Usage();
        return false;
    }
    
    if(parser.Found(wxT("v"))) {
        // print version
#ifdef __WXMSW__
        ::wxMessageBox(wxString() << "CodeLite IDE v" << clGitRevision, "CodeLite");
#else
        wxPrintf("CodeLite IDE v%s\n", clGitRevision);
#endif
        return false;
    }

    if(parser.Found(wxT("n"))) {
        // Load codelite without plugins
        SetPluginLoadPolicy(PP_None);
    }

    wxString plugins;
    if(parser.Found(wxT("p"), &plugins)) {
        wxArrayString pluginsArr = ::wxStringTokenize(plugins, wxT(","));
        // Trim and make lower case
        for(size_t i = 0; i < pluginsArr.GetCount(); i++) {
            pluginsArr.Item(i).Trim().Trim(false).MakeLower();
        }

        // Load codelite without plugins
        SetAllowedPlugins(pluginsArr);
        SetPluginLoadPolicy(PP_FromList);
    }

    wxString newBaseDir(wxEmptyString);
    if(parser.Found(wxT("b"), &newBaseDir)) {
#if defined(__WXMSW__)
        homeDir = newBaseDir;
#else
        wxLogDebug("Ignoring the Windows-only --basedir option as not running Windows");
#endif
    }

    wxString newDataDir(wxEmptyString);
    if(parser.Found(wxT("d"), &newDataDir)) {
        clStandardPaths::Get().SetUserDataDir(newDataDir);
    }

    // Copy gdb pretty printers from the installation folder to a writeable location
    // this is  needed because python complies the files and in most cases the user
    // running codelite has no write permissions to /usr/share/codelite/...
    DoCopyGdbPrinters();

    // Since GCC 4.8.2 gcc has a default colored output
    // which breaks codelite output parsing
    // to disable this, we need to set GCC_COLORS to an empty
    // string.
    // https://sourceforge.net/p/codelite/bugs/946/
    // http://gcc.gnu.org/onlinedocs/gcc/Language-Independent-Options.html
    ::wxSetEnv("GCC_COLORS", "");

#if defined(__WXGTK__)
    if(homeDir.IsEmpty()) {
        SetAppName(wxT("codelite"));
        homeDir = clStandardPaths::Get()
                      .GetUserDataDir(); // By default, ~/Library/Application Support/codelite or ~/.codelite
        if(!wxFileName::Exists(homeDir)) {
            wxLogNull noLog;
            wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
            wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
        }

        // Create the directory structure
        wxLogNull noLog;
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));

        // copy the settings from the global location if needed
        wxString installPath(INSTALL_DIR, wxConvUTF8);
        if(!CopySettings(homeDir, installPath)) return false;
        ManagerST::Get()->SetInstallDir(installPath);

    } else {
        wxFileName fn(homeDir);
        fn.MakeAbsolute();
        ManagerST::Get()->SetInstallDir(fn.GetFullPath());
    }

#elif defined(__WXMAC__)
    SetAppName(wxT("codelite"));
    homeDir = clStandardPaths::Get().GetUserDataDir();
    if(!wxFileName::Exists(homeDir)) {
        wxLogNull noLog;
        wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
        wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
    }

    {
        wxLogNull noLog;

        // Create the directory structure
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));
    }

    wxString installPath(MacGetBasePath());
    ManagerST::Get()->SetInstallDir(installPath);
    // copy the settings from the global location if needed
    CopySettings(homeDir, installPath);

#else //__WXMSW__
    if(homeDir.IsEmpty()) { // did we got a basedir from user?
#  ifdef USE_POSIX_LAYOUT
        homeDir = wxStandardPaths::Get().GetDataDir() + wxT(INSTALL_DIR);
#  else
        homeDir = ::wxGetCwd();
#  endif
    }
    wxFileName fnHomdDir(homeDir + wxT("/"));

    // try to locate the menu/rc.xrc file
    wxFileName fn(homeDir + wxT("/rc"), wxT("menu.xrc"));
    if(!fn.FileExists()) {
        // we got wrong home directory
        wxFileName appFn(wxAppBase::argv[0]);
        homeDir = appFn.GetPath();
    }

    if(fnHomdDir.IsRelative()) {
        fnHomdDir.MakeAbsolute();
        homeDir = fnHomdDir.GetPath();
    }

    ManagerST::Get()->SetInstallDir(homeDir);
#endif

    // Update codelite revision and Version
    EditorConfigST::Get()->Init(clGitRevision, wxT("2.0.2"));
    
    // Make sure we have an instance if the keyboard manager allocated before we create the main frame class
    // (the keyboard manager needs to connect to the main frame events)
    clKeyboardManager::Get();
    
    ManagerST::Get()->SetOriginalCwd(wxGetCwd());
    ::wxSetWorkingDirectory(homeDir);
    // Load all of the XRC files that will be used. You can put everything
    // into one giant XRC file if you wanted, but then they become more
    // diffcult to manage, and harder to reuse in later projects.
    // The menubar
    if(!wxXmlResource::Get()->Load(DoFindMenuFile(ManagerST::Get()->GetInstallDir(), wxT("2.0")))) return false;

    // keep the startup directory
    ManagerST::Get()->SetStartupDirectory(::wxGetCwd());

    // set the performance output file name
    PERF_OUTPUT(wxString::Format(wxT("%s/codelite.perf"), wxGetCwd().c_str()).mb_str(wxConvUTF8));

    // Initialize the configuration file locater
    ConfFileLocator::Instance()->Initialize(ManagerST::Get()->GetInstallDir(), ManagerST::Get()->GetStartupDirectory());

    Manager* mgr = ManagerST::Get();

    // set the CTAGS_REPLACEMENT environment variable
    wxSetEnv(wxT("CTAGS_REPLACEMENTS"), ManagerST::Get()->GetStartupDirectory() + wxT("/ctags.replacements"));

    long style = wxSIMPLE_BORDER;
#if defined(__WXMSW__) || defined(__WXGTK__)
    style |= wxFRAME_NO_TASKBAR;

#else // Mac
    wxUnusedVar(style);

#endif

// read the last frame size from the configuration file
// Initialise editor configuration files
#ifdef __WXMSW__
    {
        wxLogNull noLog;
        wxFileName::Mkdir(clStandardPaths::Get().GetUserDataDir(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
    }
#endif

    EditorConfigST::Get()->SetInstallDir(mgr->GetInstallDir());
    EditorConfig* cfg = EditorConfigST::Get();
    if(!cfg->Load()) {
        CL_ERROR(wxT("Failed to load configuration file: %s/config/codelite.xml"), wxGetCwd().c_str());
        return false;
    }

    ColoursAndFontsManager::Get().Load();

#ifdef __WXGTK__
    bool redirect = clConfig::Get().Read("RedirectLogOutput", true);
    if(redirect) {
        // Redirect stdout/error to a file
        wxFileName stdout_err(clStandardPaths::Get().GetUserDataDir(), "codelite-stdout-stderr.log");
        FILE* new_stdout = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stdout);
        FILE* new_stderr = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stderr);
        wxUnusedVar(new_stderr);
        wxUnusedVar(new_stdout);
    }
#endif
    // check for single instance
    if(!IsSingleInstance(parser, ManagerST::Get()->GetOriginalCwd())) {
        return false;
    }

    //---------------------------------------------------------
    // Set environment variable for CodeLiteDir (make it first
    // on the list so it can be used by other variables)
    //---------------------------------------------------------
    EvnVarList vars;
    EnvironmentConfig::Instance()->Load();
    EnvironmentConfig::Instance()->ReadObject(wxT("Variables"), &vars);

    vars.InsertVariable(wxT("Default"), wxT("CodeLiteDir"), ManagerST::Get()->GetInstallDir());
    EnvironmentConfig::Instance()->WriteObject(wxT("Variables"), &vars);

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

#ifdef __WXMSW__

    // Read registry values
    MSWReadRegistry();

#endif

    GeneralInfo inf;
    cfg->ReadObject(wxT("GeneralInfo"), &inf);

    // Set up the locale if appropriate
    if(EditorConfigST::Get()->GetOptions()->GetUseLocale()) {
        int preferredLocale = wxLANGUAGE_ENGLISH;
        // The locale had to be saved as the canonical locale name, as the wxLanguage enum wasn't consistent between wx
        // versions
        wxString preferredLocalename = EditorConfigST::Get()->GetOptions()->GetPreferredLocale();
        if(!preferredLocalename.IsEmpty()) {
            const wxLanguageInfo* info = wxLocale::FindLanguageInfo(preferredLocalename);
            if(info) {
                preferredLocale = info->Language;
                if(preferredLocale == wxLANGUAGE_UNKNOWN) {
                    preferredLocale = wxLANGUAGE_ENGLISH;
                }
            }
        }

#if defined(__WXGTK__)
        // Cater for a --prefix= build. This gets added automatically to the search path for catalogues.
        // So hack in the standard ones too, otherwise wxstd.mo will be missed
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/share/locale"));
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/local/share/locale"));

#elif defined(__WXMSW__)
#   ifdef USE_POSIX_LAYOUT
        wxLocale::AddCatalogLookupPathPrefix(wxStandardPaths::Get().GetDataDir() + wxT("/share/locale"));
#   else
        wxLocale::AddCatalogLookupPathPrefix(ManagerST::Get()->GetInstallDir() + wxT("\\locale"));
#   endif
#endif

        // This has to be done before the catalogues are added, as otherwise the wrong one (or none) will be found
        m_locale.Init(preferredLocale);

        bool codelitemo_found = m_locale.AddCatalog(wxT("codelite"));
        if(!codelitemo_found) {
            m_locale.AddCatalog(wxT("CodeLite")); // Hedge bets re our spelling
        }

        if(!codelitemo_found) {
            // I wanted to 'un-init' the locale if no translations were found
            // as otherwise, in a RTL locale, menus, dialogs etc will be displayed RTL, in English...
            // However I couldn't find a way to do this
        }
    }

// Append the binary's dir to $PATH. This makes codelite-cc available even for a --prefix= installation
#if defined(__WXMSW__)
    wxChar pathsep(wxT(';'));
#else
    wxChar pathsep(wxT(':'));
#endif
    wxString oldpath;
    wxGetEnv(wxT("PATH"), &oldpath);
    wxFileName execfpath(wxStandardPaths::Get().GetExecutablePath());
    wxSetEnv(wxT("PATH"), oldpath + pathsep + execfpath.GetPath());
    wxString newpath;
    wxGetEnv(wxT("PATH"), &newpath);

    // If running under Cygwin terminal, adjust the environment variables
    AdjustPathForCygwinIfNeeded();

    // If running under Cygwin terminal, adjust the environment variables
    AdjustPathForMSYSIfNeeded();

    // Create the main application window
    clMainFrame::Initialize(parser.GetParamCount() == 0);
    m_pMainFrame = clMainFrame::Get();
    m_pMainFrame->Show(TRUE);
    SetTopWindow(m_pMainFrame);

    long lineNumber(0);
    parser.Found(wxT("l"), &lineNumber);
    if(lineNumber > 0) {
        lineNumber--;
    } else {
        lineNumber = 0;
    }

    for(size_t i = 0; i < parser.GetParamCount(); i++) {
        wxString argument = parser.GetParam(i);

        // convert to full path and open it
        wxFileName fn(argument);
        fn.MakeAbsolute(ManagerST::Get()->GetOriginalCwd());

        if(fn.GetExt() == wxT("workspace")) {
            ManagerST::Get()->OpenWorkspace(fn.GetFullPath());
        } else {
            clMainFrame::Get()->GetMainBook()->OpenFile(fn.GetFullPath(), wxEmptyString, lineNumber);
        }
    }

    wxLogMessage(wxString::Format(wxT("Install path: %s"), ManagerST::Get()->GetInstallDir().c_str()));
    wxLogMessage(wxString::Format(wxT("Startup Path: %s"), ManagerST::Get()->GetStartupDirectory().c_str()));

#ifdef __WXGTK__
    // Needed on GTK
    if(clMainFrame::Get()->GetMainBook()->GetActiveEditor() == NULL) {
        clMainFrame::Get()->GetOutputPane()->GetBuildTab()->SetFocus();
    }
#endif

    // Especially with the OutputView open, CodeLite was consuming 50% of a cpu, mostly in updateui
    // The next line limits the frequency of UpdateUI events to every 100ms
    wxUpdateUIEvent::SetUpdateInterval(100);

    return TRUE;
}
Beispiel #25
0
bool KOfxDirectConnectDlg::init()
{
  show();

  QByteArray request = m_connector.statementRequest();
  if (request.isEmpty()) {
    hide();
    return false;
  }

  // For debugging, dump out the request
#if 0
  QFile g("request.ofx");
  g.open(QIODevice::WriteOnly);
  QTextStream(&g) << m_connector.url() << "\n" << QString(request);
  g.close();
#endif

  QDir homeDir(QDir::home());
  if (homeDir.exists("ofxlog.txt")) {
    d->m_fpTrace.setFileName(QString("%1/ofxlog.txt").arg(QDir::homePath()));
    d->m_fpTrace.open(QIODevice::WriteOnly | QIODevice::Append);
  }

  if (d->m_fpTrace.isOpen()) {
    QByteArray data = m_connector.url().toUtf8();
    d->m_fpTrace.write("url: ", 5);
    d->m_fpTrace.write(data, strlen(data));
    d->m_fpTrace.write("\n", 1);
    d->m_fpTrace.write("request:\n", 9);
    QByteArray trcData(request);  // make local copy
    trcData.replace('\r', "");
    d->m_fpTrace.write(trcData, trcData.size());
    d->m_fpTrace.write("\n", 1);
    d->m_fpTrace.write("response:\n", 10);
  }

  qDebug("creating job");
  m_job = KIO::http_post(QUrl(m_connector.url()), request, KIO::HideProgressInfo);

  // open the temp file. We come around here twice if init() is called twice
  if (m_tmpfile) {
    qDebug() << "Already connected, using " << m_tmpfile->fileName();
    delete m_tmpfile; //delete otherwise we mem leak
  }
  m_tmpfile = new QTemporaryFile();
  // for debugging purposes one might want to leave the temp file around
  // in order to achieve this, please uncomment the next line
  // m_tmpfile->setAutoRemove(false);
  if (!m_tmpfile->open()) {
    qWarning("Unable to open tempfile '%s' for download.", qPrintable(m_tmpfile->fileName()));
    return false;
  }

  m_job->addMetaData("content-type", "Content-type: application/x-ofx");

  connect(m_job, SIGNAL(result(KJob*)), this, SLOT(slotOfxFinished(KJob*)));
  connect(m_job, SIGNAL(data(KIO::Job*,QByteArray)), this, SLOT(slotOfxData(KIO::Job*,QByteArray)));

  setStatus(QString("Contacting %1...").arg(m_connector.url()));
  kProgress1->setMaximum(3);
  kProgress1->setValue(1);
  return true;
}
Beispiel #26
0
                        jid = nn.firstChild().toText().data();
                    if (nn.toElement().tagName() == "host")
                        host = nn.firstChild().toText().data();
                    nn = nn.nextSibling();
                }
                createXML(jid, decodePassword(hash, jid), host);
                yyy = yyy.nextSibling();
            }
        }
        node = node.nextSibling();
    }
}


void psi::findConfig() {
    foreach(QString profile, dirList(homeDir() + ".psi/profiles")) {
        QFile file(homeDir() + ".psi/profiles/" + profile + "/config.xml");
        if (file.open(QIODevice::ReadOnly)){
            decoding(file);
            file.close();
        }
        file.setFileName(homeDir() + ".psi/profiles/" + profile + "/accounts.xml");
        if (file.open(QIODevice::ReadOnly))
            decoding(file);
    }
}

psi* psi::instance() {
    if (!instance_)
        instance_ = new psi();
    return instance_;
QStringList ApplicationInfo::dataDirs()
{
	const static QStringList dirs = QStringList() << ":" << "." << homeDir(DataLocation)
												  << resourcesDir();
	return  dirs;
}
Beispiel #28
0
std::wstring Gosu::userDocsPrefix()
{
    return homeDir() + L"/";
}
int main(int argc, char* argv[]) {
    namespace DU = util::directory;

    BibleTimeApp app(argc, argv); //for QApplication
    app.setApplicationName("bibletime");
    app.setApplicationVersion(BT_VERSION);

    showDebugMessages = QCoreApplication::arguments().contains("--debug");

#ifdef Q_WS_WIN
    // Use the default Qt message handler if --debug is not specified
    // This works with Visual Studio debugger Output Window
    if (showDebugMessages)
        qInstallMsgHandler( myMessageOutput );
#else
    qInstallMsgHandler( myMessageOutput );
#endif

#ifdef BT_ENABLE_TESTING
    if (QString(argv[1]) == QString("--run-tests")) {
        BibleTimeTest testClass;
        return QTest::qExec(&testClass);
    }
#endif

    /**
      \todo Reimplement "--ignore-session" and "--open-default-bible <key>"
            command line argument handling.
    */

#ifdef Q_WS_WIN

    // On Windows, add a path for Qt plugins to be loaded from
    app.addLibraryPath(app.applicationDirPath() + "/plugins");

    // Must set HOME var on Windows
    QString homeDir(getenv("APPDATA"));
    _putenv_s("HOME", qPrintable(homeDir));

#endif

    registerMetaTypes();

    if (!DU::initDirectoryCache()) {
        qFatal("Error initializing directory cache!");
        return EXIT_FAILURE;
    }

#ifdef Q_WS_WIN
    // change directory to the Sword or .sword directory in the $HOME dir so that
    // the sword.conf is found. It points to the sword/locales.d directory
    QString homeSwordDir = util::directory::getUserHomeDir().absolutePath();
    QDir dir;
    dir.setCurrent(homeSwordDir);
#endif

    // This is needed for languagemgr language names to work, they use \uxxxx escape sequences in string literals
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    //first install QT's own translations
    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name());
    app.installTranslator(&qtTranslator);
    //then our own
    QTranslator BibleTimeTranslator;
    BibleTimeTranslator.load( QString("bibletime_ui_").append(QLocale::system().name()), DU::getLocaleDir().canonicalPath());
    app.installTranslator(&BibleTimeTranslator);

    app.setProperty("--debug", QVariant(showDebugMessages));

    //Migrate configuration data, if neccessary
    util::migration::checkMigration();

//	setSignalHandler(signalHandler);

    BibleTime *mainWindow = new BibleTime();
    mainWindow->setAttribute(Qt::WA_DeleteOnClose);

    // a new BibleTime version was installed (maybe a completely new installation)
    if (CBTConfig::get(CBTConfig::bibletimeVersion) != BT_VERSION) {
        CBTConfig::set(CBTConfig::bibletimeVersion, BT_VERSION);
        mainWindow->saveConfigSettings();
    }

    // restore the workspace and process command line options
    //app.setMainWidget(bibletime_ptr); //no longer used in qt4 (QApplication)
    mainWindow->show();
    mainWindow->processCommandline(); //must be done after the bibletime window is visible

#ifndef NO_DBUS
    new BibleTimeDBusAdaptor(mainWindow);
    // connect to D-Bus and register as an object:
    QDBusConnection::sessionBus().registerService("info.bibletime.BibleTime");
    QDBusConnection::sessionBus().registerObject("/BibleTime", mainWindow);
#endif

    int r = app.exec();
    CLOSE_DEBUG_STREAM;
    return r;
}
Beispiel #30
0
void Shortcut::load(bool conv)
{
    // default shortcuts
    add("Delete", FALSE, FALSE, FALSE, "Remove from diagram");
    add("Left",	FALSE, FALSE, FALSE, "Move left");
    add("Right",	FALSE, FALSE, FALSE, "Move right");
    add("Down",	FALSE, FALSE, FALSE, "Move down");
    add("Up",	FALSE, FALSE, FALSE, "Move up");
    add("Return",	FALSE, FALSE, FALSE, "Menu");
    add("D",	FALSE, TRUE, FALSE, "Delete");
    add("A",	FALSE, TRUE, FALSE, "Select all");
    add("C",	FALSE, TRUE, FALSE, "Copy");
    add("V",	FALSE, TRUE, FALSE, "Paste");
    add("X",	FALSE, TRUE, FALSE, "Cut");
    add("U",	FALSE, TRUE, FALSE, "Undo");
    add("Z",	FALSE, TRUE, FALSE, "Undo");
    add("R",	FALSE, TRUE, FALSE, "Redo");
    add("Y",	FALSE, TRUE, FALSE, "Redo");
    add("S",	FALSE, TRUE, FALSE, "Save");
    add("W",	FALSE, TRUE, FALSE, "Close");
    add("Q",	FALSE, TRUE, FALSE, "Quit");
    add("L",	FALSE, TRUE, FALSE, "Arrow geometry");
    add("F",	FALSE, TRUE, FALSE, "Browser search");
    add("O",	FALSE, TRUE, FALSE, "Open project");
    add("P",	FALSE, TRUE, FALSE, "Print");
    add("S",	TRUE, TRUE, FALSE, "Save as");

    QString f = shortcut_file_path(conv);

    if (!f.isEmpty())  {
        // note : QFile fp(QDir::home().absFilePath(f)) doesn't work
        // if the path contains non latin1 characters, for instance cyrillic !
        QString s = homeDir().absFilePath(f);
        FILE * fp = fopen((const char *) s, "r");

        if (fp != 0) {
            char line[512];

            while (fgets(line, sizeof(line) - 1, fp) != 0) {
                remove_crlf(line);

                bool shift = FALSE;
                bool control = FALSE;
                bool alt = FALSE;
                int index = 0;
                QString ln = line;

                if (!strncmp(line, "shift ", 6)) {
                    shift = TRUE;
                    index = 6;
                }

                if (!strncmp(line+index, "control ", 8)) {
                    control = TRUE;
                    index += 8;
                }

                if (!strncmp(line+index, "alt ", 4)) {
                    alt = TRUE;
                    index += 4;
                }

                int index2 = ln.find(' ', index);

                if (index2 != -1) {
                    QString s = ln.mid(index2 + 1);
                    QString k = ln.mid(index, index2 - index);

                    if (s == "New collaboration diagram")
                        // old
                        s = "New communication diagram";
                    else if (s == "Remove from view")
                        // old
                        s = "Remove from diagram";

                    if (k == "Suppr")
                        // old
                        k = "Delete";

                    add(k, shift, control, alt, s);
                }
            }

            fclose(fp);

            if (conv)
                save();

            return;
        }
    }
}