示例#1
0
int main()
{
    bool done = false;

    string ext;
    string docname;

    while ( !done )
    {
        cout << endl << endl << "Enter the document name:   ";
        cin >> docname;
        cout << "Enter the file extention:  " << docname << ".";
        cin >> ext;

        string filename = docname + "." + ext;

        IDocument* doc = NULL;

        if ( ext == "txt" )         { doc = new TextDocument; }
        else if ( ext == "csv" )    { doc = new CsvDocument; }
        else if ( ext == "html" )   { doc = new WebDocument; }
        else
        {
            cout << "Unknown file type" << endl;
            continue;
        }

        doc->GetInput();
        doc->Save( filename );
        delete doc;
    }

    return 0;
}
示例#2
0
//Returns only the name, no template-parameters or scope
QString cursorItemText() {
  KDevelop::DUChainReadLocker lock( DUChain::lock() );

  Declaration* decl = cursorDeclaration();
  if(!decl)
    return QString();

  IDocument* doc = ICore::self()->documentController()->activeDocument();
  if(!doc)
    return QString();

  TopDUContext* context = DUChainUtils::standardContextForUrl( doc->url() );

  if( !context ) {
    qCDebug(PLUGIN_QUICKOPEN) << "Got no standard context";
    return QString();
  }

  AbstractType::Ptr t = decl->abstractType();
  IdentifiedType* idType = dynamic_cast<IdentifiedType*>(t.data());
  if( idType && idType->declaration(context) )
    decl = idType->declaration(context);

  if(!decl->qualifiedIdentifier().isEmpty())
    return decl->qualifiedIdentifier().last().identifier().str();

  return QString();
}
示例#3
0
/*!
 * \brief DocumentManager::createDocument
 */
void DocumentManager::createDocument()
{
	IDocument *d = new IDocument();
	d->setObjectName(QString("%1").arg(i++));
	addDocument(d);
	;
}
static inline QString displayNameOfEditor(const QString &fileName)
{
    IDocument *document = DocumentModel::documentForFilePath(fileName);
    if (document)
        return document->displayName();
    return QString();
}
void KDevelop::DocumentationController::doShowDocumentation()
{
    IDocument* doc = ICore::self()->documentController()->activeDocument();
    if(!doc)
      return;
    
    KTextEditor::Document* textDoc = doc->textDocument();
    if(!textDoc)
      return;
    
    KTextEditor::View* view = textDoc->activeView();
    if(!view)
      return;
    
    KDevelop::DUChainReadLocker lock( DUChain::lock() );
    
    Declaration *dec = DUChainUtils::declarationForDefinition( DUChainUtils::itemUnderCursor( doc->url(), SimpleCursor(view->cursorPosition()) ) );
    
    if(dec) {
        KSharedPtr< IDocumentation > documentation = documentationForDeclaration(dec);
        if(documentation) {
            showDocumentation(documentation);
        }
    }
}
void QmlProjectRunConfiguration::updateEnabled()
{
    bool qmlFileFound = false;
    if (mainScriptSource() == FileInEditor) {
        IDocument *document = EditorManager::currentDocument();
        if (document) {
            m_currentFileFilename = document->filePath();
            if (MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
                qmlFileFound = true;
        }
        if (!document
                || MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) {
            // find a qml file with lowercase filename. This is slow, but only done
            // in initialization/other border cases.
            foreach (const QString &filename, target()->project()->files(ProjectExplorer::Project::AllFiles)) {
                const QFileInfo fi(filename);

                if (!filename.isEmpty() && fi.baseName()[0].isLower()
                        && MimeDatabase::findByFile(fi).type() == QLatin1String("application/x-qml"))
                {
                    m_currentFileFilename = filename;
                    qmlFileFound = true;
                    break;
                }

            }
        }
示例#7
0
bool IncludeFileData::execute( QString& filterText ) {
  QString path = QString(filterText);   // default to filterText in case extracting number fails
  uint lineNumber;
  bool hasLineNumber = extractLineNumber(filterText, path, lineNumber);
  if( m_item.isDirectory ) {
    //Change the filter-text to match the sub-directory
    // Line number not expected for directory
    KUrl u( filterText );
//     kDebug() << "filter-text:" << u;
    QString addName = m_item.name;
    if(addName.contains('/'))
      addName = addName.split('/').last();
    u.setFileName( addName );                                   
//     kDebug() << "with added:" << u;
    filterText = u.toLocalFile( KUrl::AddTrailingSlash );
//     kDebug() << "new:" << filterText;
    return false;
  } else {
    KUrl u = m_item.url();
    
    IDocument* doc = ICore::self()->documentController()->openDocument( u );
    if (hasLineNumber) {
      doc->setCursorPosition(KTextEditor::Cursor(lineNumber - 1, 0));
    }

    return true;
  }
}
示例#8
0
void GrepOutputModel::activate( const QModelIndex &idx )
{
    QStandardItem *stditem = itemFromIndex(idx);
    GrepOutputItem *grepitem = dynamic_cast<GrepOutputItem*>(stditem);
    if( !grepitem || !grepitem->isText() )
        return;

    QUrl url = QUrl::fromLocalFile(grepitem->filename());

    int line = grepitem->lineNumber() - 1;
    KTextEditor::Range range( line, 0, line+1, 0);

    // Try to find the actual text range we found during the grep
    IDocument* doc = ICore::self()->documentController()->documentForUrl( url );
    if(!doc)
        doc = ICore::self()->documentController()->openDocument( url, range );
    if(!doc)
        return;
    if (KTextEditor::Document* tdoc = doc->textDocument()) {
        KTextEditor::Range matchRange = grepitem->change()->m_range;
        QString actualText = tdoc->text(matchRange);
        QString expectedText = grepitem->change()->m_oldText;
        if (actualText == expectedText) {
            range = matchRange;
        }
    }

    ICore::self()->documentController()->activateDocument( doc, range );
}
void QmlProjectRunConfiguration::updateEnabled()
{
    bool qmlFileFound = false;
    if (mainScriptSource() == FileInEditor) {
        Utils::MimeDatabase mimeDataBase;
        IDocument *document = EditorManager::currentDocument();
        Utils::MimeType mainScriptMimeType = mimeDataBase.mimeTypeForFile(mainScript());
        if (document) {
            m_currentFileFilename = document->filePath().toString();
            if (mainScriptMimeType.matchesName(QLatin1String(ProjectExplorer::Constants::QML_MIMETYPE)))
                qmlFileFound = true;
        }
        if (!document
                || mainScriptMimeType.matchesName(QLatin1String(QmlJSTools::Constants::QMLPROJECT_MIMETYPE))) {
            // find a qml file with lowercase filename. This is slow, but only done
            // in initialization/other border cases.
            foreach (const QString &filename, target()->project()->files(Project::AllFiles)) {
                const QFileInfo fi(filename);

                if (!filename.isEmpty() && fi.baseName()[0].isLower()
                        && mimeDataBase.mimeTypeForFile(fi).matchesName(QLatin1String(ProjectExplorer::Constants::QML_MIMETYPE)))
                {
                    m_currentFileFilename = filename;
                    qmlFileFound = true;
                    break;
                }

            }
        }
示例#10
0
CodeRepresentation::Ptr createCodeRepresentation(const IndexedString& path) {
    if(artificialCodeRepresentationExists(path))
        return CodeRepresentation::Ptr(new StringCodeRepresentation(representationForPath(path)));

    IDocument* document = ICore::self()->documentController()->documentForUrl(path.toUrl());
    if(document && document->textDocument())
        return CodeRepresentation::Ptr(new EditorCodeRepresentation(document->textDocument()));
    else
        return CodeRepresentation::Ptr(new FileCodeRepresentation(path));
}
示例#11
0
bool BazaarPlugin::submitEditorAboutToClose()
{
    CommitEditor *commitEditor = qobject_cast<CommitEditor *>(submitEditor());
    QTC_ASSERT(commitEditor, return true);
    IDocument *editorDocument = commitEditor->document();
    QTC_ASSERT(editorDocument, return true);

    bool dummyPrompt = false;
    const VcsBaseSubmitEditor::PromptSubmitResult response =
            commitEditor->promptSubmit(tr("Close Commit Editor"), tr("Do you want to commit the changes?"),
                                       tr("Message check failed. Do you want to proceed?"),
                                       &dummyPrompt, !m_submitActionTriggered);
    m_submitActionTriggered = false;

    switch (response) {
    case VcsBaseSubmitEditor::SubmitCanceled:
        return false;
    case VcsBaseSubmitEditor::SubmitDiscarded:
        return true;
    default:
        break;
    }

    QStringList files = commitEditor->checkedFiles();
    if (!files.empty()) {
        //save the commit message
        if (!DocumentManager::saveDocument(editorDocument))
            return false;

        //rewrite entries of the form 'file => newfile' to 'newfile' because
        //this would mess the commit command
        for (QStringList::iterator iFile = files.begin(); iFile != files.end(); ++iFile) {
            const QStringList parts = iFile->split(QLatin1String(" => "), QString::SkipEmptyParts);
            if (!parts.isEmpty())
                *iFile = parts.last();
        }

        BazaarCommitWidget *commitWidget = commitEditor->commitWidget();
        QStringList extraOptions;
        // Author
        if (!commitWidget->committer().isEmpty())
            extraOptions.append(QLatin1String("--author=") + commitWidget->committer());
        // Fixed bugs
        foreach (const QString &fix, commitWidget->fixedBugs()) {
            if (!fix.isEmpty())
                extraOptions << QLatin1String("--fixes") << fix;
        }
        // Whether local commit or not
        if (commitWidget->isLocalOptionEnabled())
            extraOptions += QLatin1String("--local");
        m_client->commit(m_submitRepository, files, editorDocument->filePath(), extraOptions);
    }
    return true;
}
示例#12
0
bool SubversionPlugin::submitEditorAboutToClose()
{
    if (!isCommitEditorOpen())
        return true;

    SubversionSubmitEditor *editor = qobject_cast<SubversionSubmitEditor *>(submitEditor());
    QTC_ASSERT(editor, return true);
    IDocument *editorDocument = editor->document();
    QTC_ASSERT(editorDocument, return true);

    // Submit editor closing. Make it write out the commit message
    // and retrieve files
    const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
    const QFileInfo changeFile(m_commitMessageFileName);
    if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
        return true; // Oops?!

    // Prompt user. Force a prompt unless submit was actually invoked (that
    // is, the editor was closed or shutdown).
    SubversionSettings newSettings = m_settings;
    const VcsBaseSubmitEditor::PromptSubmitResult answer =
            editor->promptSubmit(tr("Closing Subversion Editor"),
                                 tr("Do you want to commit the change?"),
                                 tr("The commit message check failed. Do you want to commit the change?"),
                                 newSettings.boolPointer(SubversionSettings::promptOnSubmitKey),
                                 !m_submitActionTriggered);
    m_submitActionTriggered = false;
    switch (answer) {
    case VcsBaseSubmitEditor::SubmitCanceled:
        return false; // Keep editing and change file
    case VcsBaseSubmitEditor::SubmitDiscarded:
        cleanCommitMessageFile();
        return true; // Cancel all
    default:
        break;
    }
    setSettings(newSettings); // in case someone turned prompting off
    const QStringList fileList = editor->checkedFiles();
    bool closeEditor = true;
    if (!fileList.empty()) {
        // get message & commit
        closeEditor = DocumentManager::saveDocument(editorDocument);
        if (closeEditor) {
            VcsCommand *commitCmd = m_client->createCommitCmd(m_commitRepository,
                                                              fileList,
                                                              m_commitMessageFileName);
            QObject::connect(commitCmd, &VcsCommand::finished,
                             this, [this]() { cleanCommitMessageFile(); });
            commitCmd->execute();
        }
    }
    return closeEditor;
}
示例#13
0
bool ApplyChangesWidget::applyAllChanges()
{
    /// @todo implement safeguard in case a file saving fails

    bool ret = true;
    for(int i = 0; i < d->m_files.size(); ++i )
        if(d->m_editParts[i]->saveAs(d->m_files[i].toUrl())) {
            IDocument* doc = ICore::self()->documentController()->documentForUrl(d->m_files[i].toUrl());
            if(doc && doc->state()==IDocument::Dirty)
                doc->reload();
        } else
            ret = false;

    return ret;
}
//-----------------------------------------------------------------------------
void ActionFontHandlers::fontMinimizeHeight_triggered()
{
    if (this->editor() != NULL)
    {
        IDocument *doc = this->editor()->document();

        int left = std::numeric_limits<int>::max();
        int top = std::numeric_limits<int>::max();
        int right = 0;
        int bottom = 0;
        int l, t, r, b;

        // find limits
        QStringList keys = doc->dataContainer()->keys();
        QListIterator<QString> it(keys);
        it.toFront();
        while (it.hasNext())
        {
            QString key = it.next();
            const QImage *original = doc->dataContainer()->image(key);

            BitmapHelper::findEmptyArea(original, &l, &t, &r, &b);

            left = qMin(left, l);
            top = qMin(top, t);
            right = qMin(right, r);
            bottom = qMin(bottom, b);
        }

        DialogCanvasResize dialog(doc->dataContainer(), this->mMainWindow->parentWidget());
        dialog.selectKeys(keys);
        dialog.setResizeInfo(-left, -top, -right, -bottom);
        if (dialog.exec() == QDialog::Accepted)
        {
            dialog.resizeInfo(&left, &top, &right, &bottom);

            if (left != 0 || top != 0 || right != 0 || bottom != 0)
            {
                doc->beginChanges();

                QStringListIterator iterator(keys);
                while (iterator.hasNext())
                {
                    QString key = iterator.next();

                    const QImage *original = doc->dataContainer()->image(key);
                    QImage result = BitmapHelper::crop(original, left, top, right, bottom, BitmapEditorOptions::color2());
                    doc->dataContainer()->setImage(key, &result);
                }

                doc->endChanges();
            }
        }
    }
}
示例#15
0
TopDUContextPointer getCurrentTopDUContext() {
  IDocument* doc = ICore::self()->documentController()->activeDocument();

  if( doc )
  {
    return TopDUContextPointer( ICore::self()->languageController()->language("C++")->languageSupport()->standardContext( doc->url() ) );
  }
  return TopDUContextPointer();
}
示例#16
0
void IncludeFileDataProvider::reset()
{
  m_lastSearchedPrefix = QString();
  m_duContext = TopDUContextPointer();
  m_baseUrl = KUrl();
  m_importers.clear();
  
  IDocument* doc = ICore::self()->documentController()->activeDocument();

  if( doc )
  {
    m_baseUrl = doc->url();

    {
      DUChainReadLocker lock( DUChain::lock() );
      m_duContext = TopDUContextPointer( ICore::self()->languageController()->language("C++")->languageSupport()->standardContext( doc->url() )  );

      if( m_allowImporters && m_duContext ) {
        QSet<IndexedString> importers;

        collectImporters( importers, m_duContext.data() );

        m_importers = importers.values();
      }
    }
  }
  
  QList<IncludeItem> allIncludeItems;

  if( m_allowPossibleImports )
    allIncludeItems += CppUtils::allFilesInIncludePath( m_baseUrl, true, QString(), KUrl::List(), false, true, true );

  if( m_allowImports )
    allIncludeItems += getAllIncludedItems( m_duContext );
  
  foreach( const IndexedString &u, m_importers ) {
    IncludeItem i;
    i.isDirectory = false;
    i.name = u.str();
    i.pathNumber = -1; //We mark this as an importer by putting pathNumber to -1
    allIncludeItems << i;
  }
示例#17
0
void BaseEditor::actionOpen()
{
	auto uiFramework = pImpl_->get<IUIFramework>();
	TF_ASSERT(uiFramework != nullptr);
	if (!uiFramework)
	{
		return;
	}
	IDocument* doc = nullptr;
	auto path = uiFramework->showOpenFileDialog("Open", lastSaveFolder(), fileOpenFilter(), IUIFramework::None);
	if (!path.empty())
	{
		auto editor = pImpl_->get<IEditor>();
		TF_ASSERT(editor != nullptr);
		if (editor)
		{
			doc = editor->open(path.front().c_str());

			if (doc == nullptr)
			{
				return;
			}

			bindDocument(doc);

			if (path.front() == doc->getFilePath())
			{
				clearCheckoutState();
			}
		}

		onOpen(path.front().c_str(), doc);
		auto editorCommon = pImpl_->get<IEditorCommon>();
		TF_ASSERT(editorCommon != nullptr);
		if (editorCommon)
		{
			editorCommon->addToRecentFiles(path.front().c_str());
		}
	}
}
示例#18
0
bool KDevelop::renameUrl(const KDevelop::IProject* project, const KUrl& oldname, const KUrl& newname)
{
    bool wasVcsMoved = false;
    IPlugin* vcsplugin = project->versionControlPlugin();
    if (vcsplugin) {
        IBasicVersionControl* vcs = vcsplugin->extension<IBasicVersionControl>();

        // We have a vcs and the file/folder is controller, need to make the rename through vcs
        if (vcs->isVersionControlled(oldname)) {
            VcsJob* job = vcs->move(oldname, newname);
            if (job && !job->exec()) {
                return false;
            }
            wasVcsMoved = true;
        }
    }
    // Fallback for the case of no vcs, or not-vcs-managed file/folder

    // try to save-as the text document, so users can directly continue to work
    // on the renamed url as well as keeping the undo-stack intact
    IDocument* document = ICore::self()->documentController()->documentForUrl(oldname);
    if (document && document->textDocument()) {
        if (!document->textDocument()->saveAs(newname)) {
            return false;
        }
        if (!wasVcsMoved) {
            // unlink the old file
            removeUrl(project, oldname, false);
        }
        return true;
    } else if (!wasVcsMoved) {
        // fallback for non-textdocuments (also folders e.g.)
        KIO::CopyJob* job = KIO::move(oldname, newname);
        return KIO::NetAccess::synchronousRun(job, 0);
    } else {
        return true;
    }
}
示例#19
0
void TestProject::checkCurrent()
{
  Project* project = SessionManager::startupProject ();
  CustomRunConfiguration* configuration = parse (project);
  if (configuration == NULL)
  {
    return;
  }

  IDocument* document = EditorManager::currentDocument ();
  if (document == NULL)
  {
    return;
  }
  FileName file = document->filePath();
  QStringList files = project->files (Project::ExcludeGeneratedFiles);
  if (!files.contains (file.toString ()))
  {
    return;
  }

  runTestsForFiles (FileNameList () << file, configuration);
}
示例#20
0
void ocr(LPCTSTR pszName)
{
	USES_CONVERSION;

  HRESULT hr = NULL;
	IDocument  *pDoc = NULL;
	IImages *pImages = NULL;
	IImage *pImage = NULL;
	ILayout *pLayout = NULL;
	IWords *pWords = NULL;
	IWord *pWord = NULL;
	IMiRects *pRects = NULL;
	IMiRect *pRect = NULL;
  long iCount = 0, wCount = 0, rCount = 0, count = 0;
	long left, top, right, bottom, minTop = 0, maxBottom = 0, savedMaxBottom = 0;
	short conf = 0;
	double tConf = 0.0;

	CComBSTR bstrName;
	BSTR bstrText;
	CString strText;

#if _OCR_DEBUG > 0
	CString strDebug;
	strDebug.Format("OCR %s!", pszName);
	MessageBox(NULL, strDebug, "OCR.DLL", MB_ICONINFORMATION);
#endif

	hr = CoInitialize(0);
	// hr = CoInitializeEx(pReserved, COINIT_MULTITHREADED);
	// hr = CoInitializeEx(pReserved, COINIT_APARTMENTTHREADED);
#if _OCR_DEBUG > 0
	strDebug.Format("CoInitialize result = 0x%08X!", hr);
	MessageBox(NULL, strDebug, "OCR.DLL", MB_ICONINFORMATION);
#endif
	if (!SUCCEEDED(hr)) return;

	hr = CoCreateInstance(CLSID_Document, NULL, CLSCTX_INPROC_SERVER, IID_IDocument, (void**) &pDoc);
	// hr = CoCreateInstance(CLSID_Document, NULL, CLSCTX_INPROC_SERVER, IID_IDocument, (void**) &pDisp);
	// hr = pDisp->QueryInterface(IID_IDocument, (void**) &pDoc);
	// hr = pDoc.CoCreateInstance(CLSID_Document);
	// hr = CoGetClassObject(CLSID_Document, CLSCTX_INPROC_SERVER, NULL, IID_IDocument, (void**) &pDoc);
#if _OCR_DEBUG > 0
	strDebug.Format("CoCreateInstance result = 0x%08X!", hr);
	MessageBox(NULL, strDebug, "OCR.DLL", MB_ICONINFORMATION);
#endif
	if (!SUCCEEDED(hr)) return;

	bstrName = pszName;
	hr = pDoc->Create(bstrName);
#if _OCR_DEBUG > 0
	strDebug.Format("IDocument created, result = 0x%08X!", hr);
	MessageBox(NULL, strDebug, "OCR.DLL", MB_ICONINFORMATION);
#endif
	if (!SUCCEEDED(hr)) return;

	hr = pDoc->OCR(miLANG_CHINESE_SIMPLIFIED, FALSE, FALSE);
#if _OCR_DEBUG > 0
	strDebug.Format("IDocument OCR result = 0x%08X!", hr);
	MessageBox(NULL, strDebug, "OCR.DLL", MB_ICONINFORMATION);
#endif
	if (!SUCCEEDED(hr)) return;

	pDoc->get_Images(&pImages);
	pImages->get_Count(&iCount);
  for (long i = 0; i < iCount; i++ )
  {
		pImages->get_Item(i, (IDispatch**)&pImage);
    pImage->get_Layout(&pLayout);
		pLayout->get_Words(&pWords);
		pWords->get_Count(&wCount);

		for (long j = 0; j < wCount; j++)
		{
			pWords->get_Item(j, (IDispatch**)&pWord);
			pWord->get_Rects(&pRects);
			pRects->get_Count(&rCount);
			minTop = maxBottom = 0;
			for (long k = 0; k < rCount; k++)
			{
				pRects->get_Item(k, (IDispatch**)&pRect);
				pRect->get_Left(&left);
				pRect->get_Top(&top);
				pRect->get_Right(&right);
				pRect->get_Bottom(&bottom);
				if (minTop == 0) minTop = top;
				if (minTop > top) minTop = top;
				if (maxBottom < bottom) maxBottom = bottom;
				if (pRect) pRect->Release();
			}
			if (pRects) pRects->Release();
			if (savedMaxBottom == 0) savedMaxBottom = maxBottom;
			if (minTop >= savedMaxBottom)
			{
				tConf /= count;
				savedMaxBottom = maxBottom;
				strText = "";
				tConf = 0.0;
				count = 0;
			}
			pWord->get_Text(&bstrText);
			pWord->get_RecognitionConfidence(&conf);
			tConf += conf;
			count++;
			strText += bstrText ? OLE2CT(bstrText) : _T("");
			if (pWord) pWord->Release();
		}
		if (strText.GetLength() > 0)
		{
				tConf /= count;
				strText = "";
				tConf = 0.0;
				count = 0;
		}
		if (pWords) pWords->Release();
		if (pLayout) pLayout->Release();
		if (pImage) pImage->Release();
  }
	if (pImages) pImages->Release();
  pDoc->Close(0);
  pDoc->Release();
	CoUninitialize();
	return pItems;
}
示例#21
0
void StateListener::slotStateChanged()
{
    // Get the current file. Are we on a temporary submit editor indicated by
    // temporary path prefix or does the file contains a hash, indicating a project
    // folder?
    State state;
    IDocument *currentDocument = EditorManager::currentDocument();
    if (!currentDocument) {
        state.currentFile.clear();
    } else {
        state.currentFile = currentDocument->filePath().toString();
        if (state.currentFile.isEmpty() || currentDocument->isTemporary())
            state.currentFile = VcsBasePlugin::source(currentDocument);
    }
    QScopedPointer<QFileInfo> currentFileInfo; // Instantiate QFileInfo only once if required.
    if (!state.currentFile.isEmpty()) {
        const bool isTempFile = state.currentFile.startsWith(QDir::tempPath());
        // Quick check: Does it look like a patch?
        const bool isPatch = state.currentFile.endsWith(QLatin1String(".patch"))
                             || state.currentFile.endsWith(QLatin1String(".diff"));
        if (isPatch) {
            // Patch: Figure out a name to display. If it is a temp file, it could be
            // Codepaster. Use the display name of the editor.
            state.currentPatchFile = state.currentFile;
            if (isTempFile)
                state.currentPatchFileDisplayName = displayNameOfEditor(state.currentPatchFile);
            if (state.currentPatchFileDisplayName.isEmpty()) {
                currentFileInfo.reset(new QFileInfo(state.currentFile));
                state.currentPatchFileDisplayName = currentFileInfo->fileName();
            }
        }
        // For actual version control operations on it:
        // Do not show temporary files and project folders ('#')
        if (isTempFile || state.currentFile.contains(QLatin1Char('#')))
            state.currentFile.clear();
    }

    // Get the file and its control. Do not use the file unless we find one
    IVersionControl *fileControl = 0;
    if (!state.currentFile.isEmpty()) {
        if (currentFileInfo.isNull())
            currentFileInfo.reset(new QFileInfo(state.currentFile));
        if (currentFileInfo->isDir()) {
            state.currentFile.clear();
            state.currentFileDirectory = currentFileInfo->absoluteFilePath();
        } else {
            state.currentFileDirectory = currentFileInfo->absolutePath();
            state.currentFileName = currentFileInfo->fileName();
        }
        fileControl = VcsManager::findVersionControlForDirectory(
                    state.currentFileDirectory,
                    &state.currentFileTopLevel);
        if (!fileControl)
            state.clearFile();
    }
    // Check for project, find the control
    IVersionControl *projectControl = 0;
    Project *currentProject = ProjectTree::currentProject();
    if (!currentProject)
        currentProject = SessionManager::startupProject();
    if (currentProject) {
        state.currentProjectPath = currentProject->projectDirectory().toString();
        state.currentProjectName = currentProject->displayName();
        projectControl = VcsManager::findVersionControlForDirectory(state.currentProjectPath,
                                                                    &state.currentProjectTopLevel);
        if (projectControl) {
            // If we have both, let the file's one take preference
            if (fileControl && projectControl != fileControl)
                state.clearProject();
        } else {
            state.clearProject(); // No control found
        }
    }
    // Assemble state and emit signal.
    IVersionControl *vc = fileControl;
    if (!vc)
        vc = projectControl;
    if (!vc)
        state.clearPatchFile(); // Need a repository to patch
    if (debug)
        qDebug() << state << (vc ? vc->displayName() : QLatin1String("No version control"));
    EditorManager::updateWindowTitles();
    emit stateChanged(state, vc);
}