Esempio n. 1
0
t_rc SYSM_MetaManager::InsertRelationMetadata(char * relName, int recSize, int numOfAttributes, int numOfIndexes) {

	if (!this->sysm->isOpen) return (SYSM_NOTOPENEDDATABASE);

	t_rc rc;
	REM_RecordFileHandle rfh;
	RelMet relMeta;

	if (GetRelationMetadata(relName,relMeta) == OK) return (SYSM_RELATIONEXISTS);

	std::string relPath(this->sysm->path + this->sysm->openedDBName + "\\rel.met");

	rc = this->rfm->OpenRecordFile(relPath.c_str(), rfh);
	if (rc != OK) return rc;

	char * pData = new char[REL_SIZE];
	REM_RecordID rid;

	memcpy(&pData[REL_NAME_OFFSET],relName,REL_NAME_SIZE);
	memcpy(&pData[REL_REC_SIZE_OFFSET],&recSize,sizeof(int));
	memcpy(&pData[REL_ATTR_NUM_OFFSET],&numOfAttributes,sizeof(int));
	memcpy(&pData[REL_INX_NUM_OFFSET],&numOfIndexes,sizeof(int));
		
	rc = rfh.InsertRecord(pData,rid);
	if (rc != OK) return rc;
		
	rc = this->rfm->CloseRecordFile(rfh);
	if (rc != OK) return rc;

	return (OK);
}
Esempio n. 2
0
  void operator()(const char* name) const
  {
    EntityClassFilterMode filterMode;

    if(filterMode.filter_mp_sp)
    {
      if(string_empty(GlobalRadiant().getGameMode()) || string_equal(GlobalRadiant().getGameMode(), "sp"))
      {
        if(string_equal_n(name, filterMode.sp_ignore_prefix, strlen(filterMode.sp_ignore_prefix)))
        {
          globalOutputStream() << "Ignoring '" << name << "'\n";
          return;
        }
      }
      else
      {
        if(string_equal_n(name, filterMode.mp_ignore_prefix, strlen(filterMode.mp_ignore_prefix)))
        {
          globalOutputStream() << "Ignoring '" << name << "'\n";
          return;
        }
      }
    }
  
    // for a given name, we grab the first .def in the vfs
    // this allows to override baseq3/scripts/entities.def for instance
    StringOutputStream relPath(256);
    relPath << m_directory << name;

    scanner.scanFile(g_collector, relPath.c_str());
  }
void SemanticDatabase::loadSemanticInfo(string srcPath)
{
    path relPath(srcPath);
    relPath /= "relation.gz";
    relationMatrix = readMatrixFromYML(relPath);

    path feaPath(srcPath);
    feaPath /= "auxfeat.gz";
    featureMatrix = readMatrixFromYML(feaPath);
}
void SemanticDatabase::saveSemanticInfo(string destPath)
	{
        path relPath(destPath);
        relPath /= "relation.gz";
        saveMatrixToYML(relPath, relationMatrix);

        path feaPath(destPath);
        feaPath /= "auxfeat.gz";
        saveMatrixToYML(feaPath, featureMatrix);
	}
Esempio n. 5
0
bool MaItem::load(const QString& filename)
{
	bool res = false;

	if (!filename.isEmpty())
		mFilename = filename;

	mRelPath.clear();
	mRelPath = relPath();
#ifdef _DEBUG
//	qDebug() << absPath();
#endif  // _DEBUG

	QFile file(absPath());
	if (file.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		parseConfigLine(in.readLine());
		if (mIsEncrypted)
		{
			QByteArray s = in.readAll().toAscii();
			_engine->encrypt(s);
			QString s2(s);
			int i = s2.indexOf("\n");
			if (i > -1)
			{
				mCaption = s2.left(i);
				mNotes = s2.right(s2.length() - i - 1);
			}
		}
		else
		{
			mCaption = in.readLine();
			mNotes = in.readAll();
		}
		file.close();
		res = true;
	}

	// Loading the password from the password file:
	QFile file2(absPathToFilename(kPathwordFilename));
	if (file.exists() && file2.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file2);
		in.setCodec("UTF-8");
		QByteArray ba = in.readAll().toAscii();
		QByteArray salt(QString(_engine->passwordEncryptionSalt()).toAscii());
		_engine->encrypt(ba, _engine->passwordEncryptionKey().toAscii(), salt);
		mPassword = ba;
		mPasswordDirty = false;
	}

	return res;
}
Esempio n. 6
0
static BOOL RemoveInstalledFiles()
{
    BOOL success = TRUE;

    for (int i = 0; NULL != gPayloadData[i].filepath; i++) {
        ScopedMem<WCHAR> relPath(str::conv::FromUtf8(gPayloadData[i].filepath));
        ScopedMem<WCHAR> path(path::Join(gGlobalData.installDir, relPath));

        if (file::Exists(path))
            success &= DeleteFile(path);
    }

    RemoveEmptyDirectory(gGlobalData.installDir);
    return success;
}
Esempio n. 7
0
t_rc SYSM_MetaManager::GetRelationMetadata(char * relName, RelMet &relMeta) {

	if (!this->sysm->isOpen) return (SYSM_NOTOPENEDDATABASE);
	t_rc rc;
	REM_RecordFileHandle rfh;
	std::string relPath(this->sysm->path + this->sysm->openedDBName + "\\rel.met");

	rc = this->rfm->OpenRecordFile(relPath.c_str(), rfh);
	if (rc != OK) return rc;

	bool exists = true;
	REM_RecordFileScan rfs;
	rc = rfs.OpenRecordScan(rfh,TYPE_STRING,REL_NAME_SIZE,REL_NAME_OFFSET,EQ_OP,relName);
	if (rc == OK) {
	
		REM_RecordHandle rh;
		if (rfs.GetNextRecord(rh) != OK) {
			rc = this->rfm->CloseRecordFile(rfh);
			if (rc != OK) return rc;
			
			return (SYSM_RELATIONDOESNOTEXISTS);
		}

		char * pData;
		rc = rh.GetData(pData);
		if (rc != OK) return rc;
	
		relMeta.name = new char[255];

		memcpy(relMeta.name,&pData[REL_NAME_OFFSET],REL_NAME_SIZE);
		memcpy(&relMeta.rs,&pData[REL_REC_SIZE_OFFSET],sizeof(int));
		memcpy(&relMeta.numAttrs,&pData[REL_ATTR_NUM_OFFSET],sizeof(int));
		memcpy(&relMeta.numOfIndexes,&pData[REL_INX_NUM_OFFSET],sizeof(int));

		rc = rfs.CloseRecordScan();
		if (rc != OK) return rc;

		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
		
		return (OK);
	} else {
		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
		
		return (SYSM_RELATIONDOESNOTEXISTS);
	}
}
Esempio n. 8
0
void WorkspaceWork::DoImportTree(const String& dir, const String& mask, bool sep, Progress& pi, int from)
{
	String active = GetActivePackage();
	if(active.IsEmpty()) return;
	FindFile ff(AppendFileName(dir, "*.*"));
	Vector<String> dirs, files;
	while(ff) {
		String p = AppendFileName(dir, ff.GetName());
		if(ff.IsFile() && PatternMatchMulti(mask, ff.GetName()))
			files.Add(p);
		if(ff.IsFolder())
			dirs.Add(p);
		ff.Next();
	}
	String relPath(dir.Mid(from)),
		absPath = SourcePath(active, relPath);
	if(sep && files.GetCount()) {
		if(!DirectoryExists(absPath))
			if(!RealizeDirectory(absPath))
				throw Format("An error occurred while creating the directory:&\1%s", absPath);
		Package::File& f = actual.file.Add();
		f = relPath;
		f.separator = f.readonly = true;
	}
	Sort(files, &FileOrder_);
	Sort(dirs, &FileOrder_);
	for(int i = 0; i < files.GetCount(); i++) {
		if(pi.StepCanceled())
			throw String();
		String name = GetFileName(files[i]);
		if(FileCopy(files[i], AppendFileName(absPath, name))) {
			Package::File& f = actual.file.Add();
			f = AppendFileName(relPath, name);
			f.separator = f.readonly = false;
		}
		else
			throw Format("An error occurred while copying the file:&\1%s", files[i]);
	}
	for(int i = 0; i < dirs.GetCount(); i++)
		DoImportTree(dirs[i], mask, true, pi, from);
}
Esempio n. 9
0
void EbookController::OnClickedLink(int pageNo, DrawInstr *link)
{
    ScopedMem<WCHAR> url(str::conv::FromHtmlUtf8(link->str.s, link->str.len));
    if (url::IsAbsolute(url)) {
        EbookTocDest dest(nullptr, url);
        cb->GotoLink(&dest);
        return;
    }

    if (Doc_Epub == doc.Type() && pages && (size_t)pageNo <= pages->Count()) {
        // normalize the URL by combining it with the chapter's base path
        for (int j = pageNo; j > 0; j--) {
            HtmlPage *p = pages->At(j - 1);
            // <pagebreak src="..." page_marker /> is usually the second instruction on a page
            for (size_t k = 0; k < std::min((size_t)2, p->instructions.Count()); k++) {
                DrawInstr& di = p->instructions.At(k);
                if (InstrAnchor == di.type && str::StartsWith(di.str.s + di.str.len, "\" page_marker />")) {
                    ScopedMem<char> basePath(str::DupN(di.str.s, di.str.len));
                    ScopedMem<char> relPath(ResolveHtmlEntities(link->str.s, link->str.len));
                    ScopedMem<char> absPath(NormalizeURL(relPath, basePath));
                    url.Set(str::conv::FromUtf8(absPath));
                    j = 0; // done
                    break;
                }
            }
        }
    }

    int idx = ResolvePageAnchor(url);
    if (-1 == idx && str::FindChar(url, '%')) {
        url::DecodeInPlace(url);
        idx = ResolvePageAnchor(url);
    }
    if (idx != -1) {
        EbookTocDest dest(nullptr, idx);
        cb->GotoLink(&dest);
    }
}
Esempio n. 10
0
KServiceGroup::List
KServiceGroup::entries(bool sort, bool excludeNoDisplay, bool allowSeparators, bool sortByGenericName)
{
    KServiceGroup *group = this;

    // If the entries haven't been loaded yet, we have to reload ourselves
    // together with the entries. We can't only load the entries afterwards
    // since the offsets could have been changed if the database has changed.

    if (!m_bDeep) {

        group =
            KServiceGroupFactory::self()->findGroupByDesktopPath(relPath(), true);

        if (0 == group) // No guarantee that we still exist!
            return List();
    }

    if (!sort)
        return group->m_serviceList;

    // Sort the list alphabetically, according to locale.
    // Groups come first, then services.

    KSortableValueList<SPtr,QCString> slist;
    KSortableValueList<SPtr,QCString> glist;
    for (List::ConstIterator it(group->m_serviceList.begin()); it != group->m_serviceList.end(); ++it)
    {
        KSycocaEntry *p = (*it);
	bool noDisplay = p->isType(KST_KServiceGroup) ?
                                   static_cast<KServiceGroup *>(p)->noDisplay() :
                                   static_cast<KService *>(p)->noDisplay();
        if (excludeNoDisplay && noDisplay)
           continue;
        // Choose the right list
        KSortableValueList<SPtr,QCString> & list = p->isType(KST_KServiceGroup) ? glist : slist;
        QString name;
        if (p->isType(KST_KServiceGroup))
          name = static_cast<KServiceGroup *>(p)->caption();
        else if (sortByGenericName)
          name = static_cast<KService *>(p)->genericName() + " " + p->name();
        else
          name = p->name() + " " + static_cast<KService *>(p)->genericName();

        QCString key( name.length() * 4 + 1 );
        // strxfrm() crashes on Solaris
#ifndef USE_SOLARIS
        // maybe it'd be better to use wcsxfrm() where available
        size_t ln = strxfrm( key.data(), name.local8Bit().data(), key.size());
        if( ln != size_t( -1 ))
        {
            if( ln >= key.size())
            { // didn't fit?
                key.resize( ln + 1 );
                if( strxfrm( key.data(), name.local8Bit().data(), key.size()) == size_t( -1 ))
                    key = name.local8Bit();
            }
        }
        else
#endif
        {
            key = name.local8Bit();
        }
        list.insert(key,SPtr(*it));
    }
    // Now sort
    slist.sort();
    glist.sort();

    if (d->sortOrder.isEmpty())
    {
       d->sortOrder << ":M";
       d->sortOrder << ":F";
       d->sortOrder << ":OIH IL[4]"; //just inline header
    }

    QString rp = relPath();
    if(rp == "/") rp = QString::null;

    // Iterate through the sort spec list.
    // If an entry gets mentioned explicitly, we remove it from the sorted list
    for (QStringList::ConstIterator it(d->sortOrder.begin()); it != d->sortOrder.end(); ++it)
    {
        const QString &item = *it;
        if (item.isEmpty()) continue;
        if (item[0] == '/')
        {
          QString groupPath = rp + item.mid(1) + "/";
           // Remove entry from sorted list of services.
          for(KSortableValueList<SPtr,QCString>::Iterator it2 = glist.begin(); it2 != glist.end(); ++it2)
          {
             KServiceGroup *group = (KServiceGroup *)((KSycocaEntry *)((*it2).value()));
             if (group->relPath() == groupPath)
             {
                glist.remove(it2);
                break;
             }
          }
        }
        else if (item[0] != ':')
        {
           // Remove entry from sorted list of services.
           // TODO: Remove item from sortOrder-list if not found
           // TODO: This prevents duplicates
          for(KSortableValueList<SPtr,QCString>::Iterator it2 = slist.begin(); it2 != slist.end(); ++it2)
          {
             KService *service = (KService *)((KSycocaEntry *)((*it2).value()));
             if (service->menuId() == item)
             {
                slist.remove(it2);
                break;
             }
          }
        }
    }

    List sorted;

    bool needSeparator = false;
    // Iterate through the sort spec list.
    // Add the entries to the list according to the sort spec.
    for (QStringList::ConstIterator it(d->sortOrder.begin()); it != d->sortOrder.end(); ++it)
    {
        const QString &item = *it;
        if (item.isEmpty()) continue;
        if (item[0] == ':')
        {
          // Special condition...
          if (item == ":S")
          {
             if (allowSeparators)
                needSeparator = true;
          }
          else if ( item.contains( ":O" ) )
          {
              //todo parse attribute:
              QString tmp(  item );
              tmp = tmp.remove(":O");
              QStringList optionAttribute = QStringList::split(" ",tmp);
              if( optionAttribute.count()==0)
                  optionAttribute.append(tmp);
              bool showEmptyMenu = false;
              bool showInline = false;
              bool showInlineHeader = false;
              bool showInlineAlias = false;
              int inlineValue = -1;

              for ( QStringList::Iterator it3 = optionAttribute.begin(); it3 != optionAttribute.end(); ++it3 )
              {
                  parseAttribute( *it3,  showEmptyMenu, showInline, showInlineHeader, showInlineAlias, inlineValue );
              }
              for(KSortableValueList<SPtr,QCString>::Iterator it2 = glist.begin(); it2 != glist.end(); ++it2)
              {
                  KServiceGroup *group = (KServiceGroup *)((KSycocaEntry *)(*it2).value());
                  group->setShowEmptyMenu(  showEmptyMenu  );
                  group->setAllowInline( showInline );
                  group->setShowInlineHeader( showInlineHeader );
                  group->setInlineAlias( showInlineAlias );
                  group->setInlineValue( inlineValue );
              }

          }
          else if (item == ":M")
          {
            // Add sorted list of sub-menus
            for(KSortableValueList<SPtr,QCString>::Iterator it2 = glist.begin(); it2 != glist.end(); ++it2)
            {
              addItem(sorted, (*it2).value(), needSeparator);
            }
          }
          else if (item == ":F")
          {
            // Add sorted list of services
            for(KSortableValueList<SPtr,QCString>::Iterator it2 = slist.begin(); it2 != slist.end(); ++it2)
            {
              addItem(sorted, (*it2).value(), needSeparator);
            }
          }
          else if (item == ":A")
          {
            // Add sorted lists of services and submenus
            KSortableValueList<SPtr,QCString>::Iterator it_s = slist.begin();
            KSortableValueList<SPtr,QCString>::Iterator it_g = glist.begin();

            while(true)
            {
               if (it_s == slist.end())
               {
                  if (it_g == glist.end())
                     break; // Done

                  // Insert remaining sub-menu
                  addItem(sorted, (*it_g).value(), needSeparator);
                  it_g++;
               }
               else if (it_g == glist.end())
               {
                  // Insert remaining service
                  addItem(sorted, (*it_s).value(), needSeparator);
                  it_s++;
               }
               else if ((*it_g).index() < (*it_s).index())
               {
                  // Insert sub-menu first
                  addItem(sorted, (*it_g).value(), needSeparator);
                  it_g++;
               }
               else
               {
                  // Insert service first
                  addItem(sorted, (*it_s).value(), needSeparator);
                  it_s++;
               }
            }
          }
        }
        else if (item[0] == '/')
        {
            QString groupPath = rp + item.mid(1) + "/";

            for (List::ConstIterator it2(group->m_serviceList.begin()); it2 != group->m_serviceList.end(); ++it2)
            {
                if (!(*it2)->isType(KST_KServiceGroup))
                    continue;
                KServiceGroup *group = (KServiceGroup *)((KSycocaEntry *)(*it2));
                if (group->relPath() == groupPath)
                {
                    if (!excludeNoDisplay || !group->noDisplay())
                    {
                        const QString &nextItem = *( ++it );
                        if ( nextItem.startsWith( ":O" ) )
                        {
                            QString tmp(  nextItem );
                            tmp = tmp.remove(":O");
                            QStringList optionAttribute = QStringList::split(" ",tmp);
                            if( optionAttribute.count()==0)
                                optionAttribute.append(tmp);
                            bool bShowEmptyMenu = false;
                            bool bShowInline = false;
                            bool bShowInlineHeader = false;
                            bool bShowInlineAlias = false;
                            int inlineValue = -1;
                            for ( QStringList::Iterator it3 = optionAttribute.begin(); it3 != optionAttribute.end(); ++it3 )
                            {
                                parseAttribute( *it3 , bShowEmptyMenu, bShowInline, bShowInlineHeader, bShowInlineAlias , inlineValue );
                                group->setShowEmptyMenu( bShowEmptyMenu );
                                group->setAllowInline( bShowInline );
                                group->setShowInlineHeader( bShowInlineHeader );
                                group->setInlineAlias( bShowInlineAlias );
                                group->setInlineValue( inlineValue );
                            }
                        }
                        else
                            it--;

                        addItem(sorted, (group), needSeparator);
                    }
                    break;
                }
            }
        }
        else
        {
            for (List::ConstIterator it2(group->m_serviceList.begin()); it2 != group->m_serviceList.end(); ++it2)
            {
                if (!(*it2)->isType(KST_KService))
                    continue;
                KService *service = (KService *)((KSycocaEntry *)(*it2));
                if (service->menuId() == item)
                {
                    if (!excludeNoDisplay || !service->noDisplay())
                        addItem(sorted, (*it2), needSeparator);
                    break;
                }
            }
        }
    }

    return sorted;
}
Esempio n. 11
0
bool MaItem::operator!=( const MaItem& other ) const
{
	return relPath().compare(other.relPath());
}
Esempio n. 12
0
void
FindWindow::FindResults(void)
{
	// This function is called from the FinderThread function, so locking is
	// required when accessing any member variables.
	Lock();
	bool canReplace = fReplaceButton->IsEnabled();
	EnableReplace(false);
	for (int32 i = fResultList->CountItems() - 1; i >= 0; i--)
	{
		// We don't want to hog the window lock, but we also don't want
		// tons of context switches, either. Yielding the lock every 5 items
		// should give us sufficient responsiveness.
		if (i % 5 == 0)
		{
			Unlock();
			Lock();
		}
		
		BListItem *item = fResultList->RemoveItem(i);
		delete item;
	}
	Unlock();

	ShellHelper shell;
	
	shell << "cd ";
	shell.AddEscapedArg(fWorkingDir);
	shell << "; pwd; find . -type f ";
	shell << "|xargs grep -n -H -s --binary-files=without-match ";
	// TODO check for PCRE invocation and pass in pcre flag to grep if so
	// TODO Ensure RE escaping also happens (E.g. open/close paran etc.)
	shell.AddEscapedArg(fFindBox->Text());
	
	if (fThreadQuitFlag)
		return;
	
	BString out;
	shell.RunInPipe(out, false);
	
	if (fThreadQuitFlag)
		return;
	
	BObjectList<BString> resultList(20, true);
	TokenizeToList(out.String(), resultList);
	
	Lock();
	
	for (int32 i = 0; i < resultList.CountItems(); i++)
	{
		// We don't want to hog the window lock, but we also don't want
		// tons of context switches, either. Yielding the lock every 5 items
		// should give us sufficient responsiveness.
		if (i % 5 == 0)
		{
			Unlock();
			Lock();
		}
		
		BString entryString(resultList.ItemAt(i)->String());
		
		BString filename(entryString);
		int32 pos = filename.FindFirst(":");
		if (pos < 0)
			continue;
		filename.Truncate(pos);
		if (filename.StartsWith("./"))
			filename.Remove(0,2);
		STRACE(2,("Truncated file name from grep: %s\n",filename.String()));
		
		BString lineString;
		entryString.CopyInto(lineString, pos + 1, entryString.CountChars() - pos);
		int32 pos2 = lineString.FindFirst(":");
		
		BString locationString;
		lineString.CopyInto(locationString, pos2 + 1, lineString.CountChars() - pos2);
		lineString.Truncate(pos2);
		
		DPath entryPath(fWorkingDir);
		entryPath << filename;
		
		BString fullPath(fWorkingDir);
		fullPath << "/" << filename;
		
		STRACE(2,("Full path: %s\n",fullPath.String()));
		
		DPath relPath(filename);
		
		fResultList->AddItem(new GrepListItem(fullPath,filename,
			entryPath.GetRef(), atol(lineString.String()),
			locationString.String()));
	}
	EnableReplace(true);
	
	if (fResultList->CountItems() == 0)
		fResultList->AddItem(new BStringItem(B_TRANSLATE("No matches found")));
	
	Unlock();
	
}
Esempio n. 13
0
t_rc SYSM_MetaManager::DeleteRelationMetadata(char * rel_Name) {

	if (!this->sysm->isOpen) return (SYSM_NOTOPENEDDATABASE);

	t_rc rc;
	REM_RecordFileHandle rfh;
	std::string relPath(this->sysm->path + this->sysm->openedDBName + "\\rel.met");

	rc = this->rfm->OpenRecordFile(relPath.c_str(), rfh);
	if (rc != OK) return rc;

	REM_RecordFileScan rfs;
	rc = rfs.OpenRecordScan(rfh,TYPE_STRING,REL_NAME_SIZE,REL_NAME_OFFSET,EQ_OP,rel_Name);
	if (rc != OK) {
		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
		
		return (SYSM_RELATIONDOESNOTEXISTS);
	}

	REM_RecordHandle rh;
	if (rfs.GetNextRecord(rh) != OK) return (SYSM_RELATIONDOESNOTEXISTS);

	REM_RecordID rid;
	rc = rh.GetRecordID(rid);
	if (rc != OK) return rc;

	rc = rfh.DeleteRecord(rid);
	if (rc != OK) return rc;

	rc = rfs.CloseRecordScan();
	if (rc != OK) return rc;

	rc = this->rfm->CloseRecordFile(rfh);
	if (rc != OK) return rc;

	std::string attrPath(this->sysm->path + this->sysm->openedDBName + "\\attr.met");
	rc = this->rfm->OpenRecordFile(attrPath.c_str(),rfh);
	if (rc != OK) return rc;

	rc = rfs.OpenRecordScan(rfh,TYPE_STRING,REL_NAME_SIZE,ATTR_REL_NAME_OFFSET,EQ_OP,rel_Name);
	if (rc != OK) {
		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
		
		return (OK);
	}

	while (rfs.GetNextRecord(rh) == OK) {
		rc = rh.GetRecordID(rid);
		if (rc != OK) return rc;

		rc = rfh.DeleteRecord(rid);
		if (rc != OK) return rc;
	}

	rc = rfs.CloseRecordScan();
	if (rc != OK) return rc;

	rc = this->rfm->CloseRecordFile(rfh);
	if (rc != OK) return rc;

	return (OK);
}
Esempio n. 14
0
t_rc SYSM_MetaManager::UpdateRelationMetadata(char * p_Rel_Name, char * n_Rel_Name, int n_Rec_Size, int n_Num_Of_Attributes, int numOfIndexes) {

	if (!this->sysm->isOpen) return (SYSM_NOTOPENEDDATABASE);

	t_rc rc;
	REM_RecordFileHandle rfh;
	std::string relPath(this->sysm->path + this->sysm->openedDBName + "\\rel.met");

	rc = this->rfm->OpenRecordFile(relPath.c_str(), rfh);
	if (rc != OK) {
		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
		
		return (SYSM_RELATIONDOESNOTEXISTS);
	}

	REM_RecordFileScan rfs;
	rc = rfs.OpenRecordScan(rfh,TYPE_STRING,REL_NAME_SIZE,REL_NAME_OFFSET,EQ_OP,p_Rel_Name);
	if (rc != OK) return rc;

	REM_RecordHandle rh;
	if (rfs.GetNextRecord(rh) != OK) return (SYSM_RELATIONDOESNOTEXISTS);
	
	char * pData;
	REM_RecordID rid;

	rc = rh.GetData(pData);
	if (rc != OK) return rc;

	memcpy(&pData[REL_NAME_OFFSET],n_Rel_Name,REL_NAME_SIZE);
	memcpy(&pData[REL_REC_SIZE_OFFSET],&n_Rec_Size,sizeof(int));
	memcpy(&pData[REL_ATTR_NUM_OFFSET],&n_Num_Of_Attributes,sizeof(int));
	memcpy(&pData[REL_INX_NUM_OFFSET],&numOfIndexes,sizeof(int));

	rc = rfh.UpdateRecord(rh);
	if (rc != OK) return rc;

	rc = rfs.CloseRecordScan();
	if (rc != OK) return rc;

	rc = this->rfm->CloseRecordFile(rfh);
	if (rc != OK) return rc;

	if (strcmp(p_Rel_Name,n_Rel_Name) != 0) {
		std::string attrPath(this->sysm->path + this->sysm->openedDBName + "\\attr.met");
		rc = this->rfm->OpenRecordFile(attrPath.c_str(),rfh);
		if (rc != OK) return rc;

		rfs.OpenRecordScan(rfh,TYPE_STRING,REL_NAME_SIZE,ATTR_REL_NAME_OFFSET,EQ_OP,p_Rel_Name);
		if (rc != OK) {
			rc = this->rfm->CloseRecordFile(rfh);
			if (rc != OK) return rc;

			return (OK);
		}

		while (rfs.GetNextRecord(rh) == OK) {
			char * pData;
			rc = rh.GetData(pData);
			if (rc != OK) return rc;

			memcpy(&pData[ATTR_REL_NAME_OFFSET],n_Rel_Name,REL_NAME_SIZE);

			rc = rfh.UpdateRecord(rh);
			if (rc != OK) return rc;
		}

		rc = rfs.CloseRecordScan();
		if (rc != OK) return rc;

		rc = this->rfm->CloseRecordFile(rfh);
		if (rc != OK) return rc;
	}

	return (OK);
}
bool Filters::BT_ThMLHTML::handleToken(sword::SWBuf &buf, const char *token, sword::BasicFilterUserData *userData) {
    if (!substituteToken(buf, token) && !substituteEscapeString(buf, token)) {
        sword::XMLTag tag(token);
        BT_UserData* myUserData = dynamic_cast<BT_UserData*>(userData);
        sword::SWModule* myModule = const_cast<sword::SWModule*>(myUserData->module); //hack to be able to call stuff like Lang()

        if ( tag.getName() && !sword::stricmp(tag.getName(), "foreign") ) { // a text part in another language, we have to set the right font

            if (tag.getAttribute("lang")) {
                const char* abbrev = tag.getAttribute("lang");
                //const CLanguageMgr::Language* const language = CPointers::languageMgr()->languageForAbbrev( QString::fromLatin1(abbrev) );

                buf.append("<span class=\"foreign\" lang=\"");
                buf.append(abbrev);
                buf.append("\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "sync")) { //lemmas, morph codes or strongs

            if (tag.getAttribute("type") && (!sword::stricmp(tag.getAttribute("type"), "morph") || !sword::stricmp(tag.getAttribute("type"), "Strongs") || !sword::stricmp(tag.getAttribute("type"), "lemma"))) { // Morph or Strong
                buf.append('<');
                buf.append(token);
                buf.append('>');
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "note")) { // <note> tag

            if (!tag.isEndTag() && !tag.isEmpty()) {
                //appending is faster than appendFormatted
                buf.append(" <span class=\"footnote\" note=\"");
                buf.append(myModule->Name());
                buf.append('/');
                buf.append(myUserData->key->getShortText());
                buf.append('/');
                buf.append( QString::number(myUserData->swordFootnote++).toUtf8().constData() );
                buf.append("\">*</span> ");

                myUserData->suspendTextPassThru = true;
                myUserData->inFootnoteTag = true;
            }
            else if (tag.isEndTag() && !tag.isEmpty()) { //end tag
                //buf += ")</span>";
                myUserData->suspendTextPassThru = false;
                myUserData->inFootnoteTag = false;
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "scripRef")) { // a scripRef
            //scrip refs which are embeded in footnotes may not be displayed!

            if (!myUserData->inFootnoteTag) {
                if (tag.isEndTag()) {
                    if (myUserData->inscriptRef) { // like "<scripRef passage="John 3:16">See John 3:16</scripRef>"
                        buf.append("</a></span>");

                        myUserData->inscriptRef = false;
                        myUserData->suspendTextPassThru = false;
                    }
                    else { // like "<scripRef>John 3:16</scripRef>"

                        CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                        //Q_ASSERT(mod); tested later
                        if (mod) {
                            ReferenceManager::ParseOptions options;
                            options.refBase = QString::fromUtf8(myUserData->key->getText()); //current module key
                            options.refDestinationModule = QString(mod->name());
                            options.sourceLanguage = QString(myModule->Lang());
                            options.destinationLanguage = QString("en");

                            //it's ok to split the reference, because to descriptive text is given
                            bool insertSemicolon = false;
                            buf.append("<span class=\"crossreference\">");
                            QStringList refs = QString::fromUtf8(myUserData->lastTextNode.c_str()).split(";");
                            QString oldRef; //the previous reference to use as a base for the next refs
                            for (QStringList::iterator it(refs.begin()); it != refs.end(); ++it) {

                                if (! oldRef.isEmpty() ) {
                                    options.refBase = oldRef; //use the last ref as a base, e.g. Rom 1,2-3, when the next ref is only 3:3-10
                                }
                                const QString completeRef( ReferenceManager::parseVerseReference((*it), options) );

                                oldRef = completeRef; //use the parsed result as the base for the next ref.

                                if (insertSemicolon) { //prepend a ref divider if we're after the first one
                                    buf.append("; ");
                                }

                                buf.append("<a href=\"");
                                buf.append(
                                    ReferenceManager::encodeHyperlink(
                                        mod->name(),
                                        completeRef,
                                        ReferenceManager::typeFromModule(mod->type())
                                    ).toUtf8().constData()
                                );

                                buf.append("\" crossrefs=\"");
                                buf.append((const char*)completeRef.toUtf8());
                                buf.append("\">");

                                buf.append((const char*)(*it).toUtf8());

                                buf.append("</a>");

                                insertSemicolon = true;
                            }
                            buf.append("</span>"); //crossref end
                        }

                        myUserData->suspendTextPassThru = false;
                    }
                }
                else if (tag.getAttribute("passage") ) { //the passage was given as a parameter value
                    myUserData->inscriptRef = true;
                    myUserData->suspendTextPassThru = false;

                    const char* ref = tag.getAttribute("passage");
                    Q_ASSERT(ref);

                    CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                    //Q_ASSERT(mod); tested later

                    ReferenceManager::ParseOptions options;
                    options.refBase = QString::fromUtf8(myUserData->key->getText());

                    options.sourceLanguage = myModule->Lang();
                    options.destinationLanguage = QString("en");

                    const QString completeRef = ReferenceManager::parseVerseReference(QString::fromUtf8(ref), options);

                    if (mod) {
                        options.refDestinationModule = QString(mod->name());
                        buf.append("<span class=\"crossreference\">");
                        buf.append("<a href=\"");
                        buf.append(
                            ReferenceManager::encodeHyperlink(
                                mod->name(),
                                completeRef,
                                ReferenceManager::typeFromModule(mod->type())
                            ).toUtf8().constData()
                        );
                        buf.append("\" crossrefs=\"");
                        buf.append((const char*)completeRef.toUtf8());
                        buf.append("\">");
                    }
                    else {
                        buf.append("<span><a>");
                    }
                }
                else if ( !tag.getAttribute("passage") ) { // we're starting a scripRef like "<scripRef>John 3:16</scripRef>"
                    myUserData->inscriptRef = false;

                    // let's stop text from going to output, the text get's added in the -tag handler
                    myUserData->suspendTextPassThru = true;
                }
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "div")) {
            if (tag.isEndTag()) {
                buf.append("</div>");
            }
            else if ( tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "sechead") ) {
                buf.append("<div class=\"sectiontitle\">");
            }
            else if (tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "title")) {
                buf.append("<div class=\"booktitle\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "img") && tag.getAttribute("src")) {
            const char* value = tag.getAttribute("src");

            if (value[0] == '/') {
                value++; //strip the first /
            }

            buf.append("<img src=\"");
            QString absPath(QTextCodec::codecForLocale()->toUnicode(myUserData->module->getConfigEntry("AbsoluteDataPath")));
            QString relPath(QString::fromUtf8(value));
            QString url(QUrl::fromLocalFile(absPath.append('/').append(relPath)).toString());
            buf.append(url.toUtf8().data());
            buf.append("\" />");
        }
        else { // let unknown token pass thru
            return sword::ThMLHTML::handleToken(buf, token, userData);
        }
    }

    return true;
}
Esempio n. 16
0
EXPORT_C CUrl* CUrl::ResolveL(CUrl& aBaseUrl, CUrl& aRelativeUrl)
//
//	Based on the relative parsing algorithm in RFC2396
	{
	//	Return copy of aRelativeUrl if aBaseUrl is empty
	if (aBaseUrl.UrlDes().Compare(KNullDesC)==0)
		return aRelativeUrl.AllocL();

	TPtrC relativeUrl(aRelativeUrl.UrlDes());

	TPtrC relPath(aRelativeUrl.Component(EUrlPath));
	TPtrC relAuth(aRelativeUrl.Component(EUrlAuthority));
	TPtrC relScheme(aRelativeUrl.Component(EUrlScheme));
	TPtrC relQuery(aRelativeUrl.Component(EUrlQuery));
	TPtrC relFragment(aRelativeUrl.Component(EUrlFragment));

	if (relScheme.Length() > 0)
		{
		// LOOPHOLE in RFC 1630 if schemes match then remove the scheme from the relative url
		if (aBaseUrl.UrlDes().FindF(relScheme) == 0)
			relativeUrl.Set(relativeUrl.Mid(relScheme.Length() + 1)); // remove the ':' as well
		else // the relative url is absolute
			return NewL(relativeUrl);
		}

	TBool useBaseAuth = ETrue;
	TBool useRelQuery = ETrue;
	TPtrC basePath(aBaseUrl.Component(EUrlPath));
	HBufC* resolvedPath = NULL;
	if (relPath.Compare(KNullDesC)==0 && relAuth.Compare(KNullDesC)==0 
		&& relScheme.Compare(KNullDesC)==0 && relQuery.Compare(KNullDesC)==0) // relative URL could just be a fragment
		{
		// Use current document url (assume that it is aBaseUrl), including query, then add relative URL fragment
		useRelQuery = EFalse;
		resolvedPath = basePath.AllocLC();
		}
	else if (relativeUrl.Find(KUrlLoc) == 0) // relative url is a network path
		{
		// Set resolved path to be the relative path
		useBaseAuth = EFalse;
		resolvedPath = relPath.AllocLC();
		}	
	else if (relPath.Locate('/') == 0) // relative url is an absolute path
		{
		resolvedPath = relPath.AllocLC();
		}
	else 
		{
		//	Do path resolution, merge the base path and relative path
		if (relPath.Length() != 0)
			// if the relative path is a query or fragment then shouldn't strip the document from the basePath
			{
			TInt endBasePath = basePath.LocateReverse('/');
			if (endBasePath != KErrNotFound)
				basePath.Set(basePath.Left(endBasePath + 1)); // keep the '/' 
			else
				basePath.Set(_L("/"));	//	Create path of just '/'
			}
		//	Resolve relative path against base path
		resolvedPath = HBufC::NewLC(relPath.Length() + basePath.Length());
		TRelativePaths relativePaths(basePath, relPath, resolvedPath->Des());
		relativePaths.ResolveRelativePaths();
		}

	// put the url together
	TPtrC baseScheme(aBaseUrl.Component(EUrlScheme));
	TPtrC baseAuth(aBaseUrl.Component(EUrlAuthority));
	TPtrC baseQuery(aBaseUrl.Component(EUrlQuery));

	HBufC* resolvedUrl = HBufC::NewLC(aBaseUrl.UrlDes().Length()  
										 + relativeUrl.Length()
										 + KUrlColon().Length() 
										 + KUrlLoc().Length()
										 + KUrlQMark().Length()
										 + KUrlHash().Length()
										 + 1); // this will be long enough - extra 1 just in case basePath was empty
	TPtr resolvedBuf = resolvedUrl->Des();

	if (baseScheme.Length() > 0)
		{
		resolvedBuf.Append(baseScheme);
		resolvedBuf.Append(KUrlColon);
		}

	resolvedBuf.Append(KUrlLoc);	

	if (useBaseAuth && baseAuth.Length() >0)
		{
		resolvedBuf.Append(baseAuth);
		}
	else if (relAuth.Length() > 0)
		{
		resolvedBuf.Append(relAuth);
		}

	resolvedBuf.Append(*resolvedPath);

	if (useRelQuery && relQuery.Length() >0)
		{
		resolvedBuf.Append(KUrlQMark);
		resolvedBuf.Append(relQuery);
		}
	else if (!useRelQuery && baseQuery.Length() >0)
		{
		resolvedBuf.Append(KUrlQMark);
		resolvedBuf.Append(baseQuery);
		}

	if (relFragment.Length() >0)
		{
		resolvedBuf.Append(KUrlHash);
		resolvedBuf.Append(relFragment);
		}

	CUrl * url = CUrl::NewL(*resolvedUrl);
	CleanupStack::PopAndDestroy(2); // resolvedUrl, resolvedPath

	return url;
	}