perforceplugin.cpp 46.5 KB
Newer Older
con's avatar
con committed
1
2
3
4
5
6
7
8
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
32
**
***************************************************************************/
hjk's avatar
hjk committed
33

con's avatar
con committed
34
#include "perforceplugin.h"
hjk's avatar
hjk committed
35

con's avatar
con committed
36
#include "changenumberdialog.h"
hjk's avatar
hjk committed
37
38
#include "p4.h"
#include "pendingchangesdialog.h"
con's avatar
con committed
39
40
#include "perforceconstants.h"
#include "perforceeditor.h"
hjk's avatar
hjk committed
41
42
43
44
#include "perforceoutputwindow.h"
#include "perforcesubmiteditor.h"
#include "perforceversioncontrol.h"
#include "settingspage.h"
con's avatar
con committed
45

hjk's avatar
hjk committed
46
#include <coreplugin/actionmanager/actionmanagerinterface.h>
con's avatar
con committed
47
#include <coreplugin/coreconstants.h>
hjk's avatar
hjk committed
48
#include <coreplugin/editormanager/editormanager.h>
con's avatar
con committed
49
#include <coreplugin/filemanager.h>
hjk's avatar
hjk committed
50
#include <coreplugin/icore.h>
con's avatar
con committed
51
#include <coreplugin/messagemanager.h>
hjk's avatar
hjk committed
52
#include <coreplugin/mimedatabase.h>
con's avatar
con committed
53
#include <coreplugin/uniqueidmanager.h>
hjk's avatar
hjk committed
54
#include <utils/qtcassert.h>
con's avatar
con committed
55
56
57
58
59
60
61
62
#include <utils/synchronousprocess.h>
#include <vcsbase/basevcseditorfactory.h>
#include <vcsbase/basevcssubmiteditorfactory.h>
#include <vcsbase/vcsbaseeditor.h>

#include <QtCore/qplugin.h>
#include <QtCore/QDebug>
#include <QtCore/QDir>
hjk's avatar
hjk committed
63
#include <QtCore/QFileInfo>
con's avatar
con committed
64
#include <QtCore/QSettings>
hjk's avatar
hjk committed
65
#include <QtCore/QTemporaryFile>
con's avatar
con committed
66
#include <QtCore/QTextCodec>
hjk's avatar
hjk committed
67

con's avatar
con committed
68
#include <QtGui/QAction>
hjk's avatar
hjk committed
69
70
#include <QtGui/QFileDialog>
#include <QtGui/QMainWindow>
con's avatar
con committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>

using namespace Perforce::Internal;

enum { p4Timeout = 20000 };

static const VCSBase::VCSBaseEditorParameters editorParameters[] = {
{
    VCSBase::RegularCommandOutput,
    "Perforce Command Log Editor",
    Perforce::Constants::C_PERFORCEEDITOR,
    "application/vnd.nokia.text.scs_commandlog",
    "scslog"},
{   VCSBase::LogOutput,
    "Perforce File Log Editor",
    Perforce::Constants::C_PERFORCEEDITOR,
    "application/vnd.nokia.text.scs_filelog",
    "scsfilelog"},
{    VCSBase::AnnotateOutput,
    "Perforce Annotation Editor",
    Perforce::Constants::C_PERFORCEEDITOR,
    "application/vnd.nokia.text.scs_annotation",
    "scsannotate"},
{   VCSBase::DiffOutput,
    "Perforce Diff Editor",
    Perforce::Constants::C_PERFORCEEDITOR,
    "text/x-patch","diff"}
};

// Utility to find a parameter set by type
static inline const VCSBase::VCSBaseEditorParameters *findType(int ie)
{
    const VCSBase::EditorContentType et = static_cast<VCSBase::EditorContentType>(ie);
    return  VCSBase::VCSBaseEditor::findType(editorParameters, sizeof(editorParameters)/sizeof(VCSBase::VCSBaseEditorParameters), et);
}

static inline QString debugCodec(const QTextCodec *c)
{
    return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
}

const char * const PerforcePlugin::PERFORCE_MENU = "Perforce.Menu";
const char * const PerforcePlugin::EDIT = "Perforce.Edit";
const char * const PerforcePlugin::ADD = "Perforce.Add";
const char * const PerforcePlugin::DELETE_FILE = "Perforce.Delete";
const char * const PerforcePlugin::OPENED = "Perforce.Opened";
const char * const PerforcePlugin::REVERT = "Perforce.Revert";
const char * const PerforcePlugin::DIFF_CURRENT = "Perforce.DiffCurrent";
const char * const PerforcePlugin::DIFF_PROJECT = "Perforce.DiffProject";
const char * const PerforcePlugin::DIFF_ALL = "Perforce.DiffAll";
const char * const PerforcePlugin::RESOLVE = "Perforce.Resolve";
const char * const PerforcePlugin::SUBMIT = "Perforce.Submit";
const char * const PerforcePlugin::PENDING_CHANGES = "Perforce.PendingChanges";
const char * const PerforcePlugin::DESCRIBE = "Perforce.Describe";
const char * const PerforcePlugin::ANNOTATE_CURRENT = "Perforce.AnnotateCurrent";
const char * const PerforcePlugin::ANNOTATE = "Perforce.Annotate";
const char * const PerforcePlugin::FILELOG_CURRENT = "Perforce.FilelogCurrent";
const char * const PerforcePlugin::FILELOG = "Perforce.Filelog";
const char * const PerforcePlugin::SEPARATOR1 = "Perforce.Separator1";
const char * const PerforcePlugin::SEPARATOR2 = "Perforce.Separator2";
const char * const PerforcePlugin::SEPARATOR3 = "Perforce.Separator3";

////
// CoreListener
////

bool CoreListener::editorAboutToClose(Core::IEditor *editor)
{
    return m_plugin->editorAboutToClose(editor);
}

////
// PerforcePlugin
////

Core::ICore *PerforcePlugin::m_coreInstance = NULL;
PerforcePlugin *PerforcePlugin::m_perforcePluginInstance = NULL;

PerforcePlugin::PerforcePlugin() :
    m_perforceOutputWindow(0),
    m_settingsPage(0),
    m_editAction(0),
    m_addAction(0),
    m_deleteAction(0),
    m_openedAction(0),
    m_revertAction(0),
    m_diffCurrentAction(0),
    m_diffProjectAction(0),
    m_diffAllAction(0),
    m_resolveAction(0),
    m_submitAction(0),
    m_pendingAction(0),
    m_describeAction(0),
    m_annotateCurrentAction(0),
    m_annotateAction(0),
    m_filelogCurrentAction(0),
    m_filelogAction(0),
    m_changeTmpFile(0),
#ifdef USE_P4_API
    m_workbenchClientUser(0),
#endif
    m_coreListener(0),
    m_submitEditorFactory(0),
    m_versionControl(0)
{
}

static const VCSBase::VCSBaseSubmitEditorParameters submitParameters = {
    Perforce::Constants::SUBMIT_MIMETYPE,
    Perforce::Constants::PERFORCESUBMITEDITOR_KIND,
    Perforce::Constants::C_PERFORCESUBMITEDITOR,
    Core::Constants::UNDO,
    Core::Constants::REDO,
    Perforce::Constants::SUBMIT_CURRENT,
    Perforce::Constants::DIFF_SELECTED
};

bool PerforcePlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
    typedef VCSBase::VCSEditorFactory<PerforceEditor> PerforceEditorFactory;
    typedef VCSBase::VCSSubmitEditorFactory<PerforceSubmitEditor> PerforceSubmitEditorFactory;

    m_coreInstance = ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>();
    if (!m_coreInstance->mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.perforce/Perforce.mimetypes.xml"), errorMessage))
        return false;
    m_perforcePluginInstance = this;

    if (QSettings *settings = m_coreInstance->settings())
        m_settings.fromSettings(settings);

    m_perforceOutputWindow = new PerforceOutputWindow(this);
    addObject(m_perforceOutputWindow);

    m_settingsPage = new SettingsPage;
    addObject(m_settingsPage);

    // Editor factories
    m_submitEditorFactory = new PerforceSubmitEditorFactory(&submitParameters);
    addObject(m_submitEditorFactory);

    static const char *describeSlot = SLOT(describe(QString,QString));
    const int editorCount = sizeof(editorParameters)/sizeof(VCSBase::VCSBaseEditorParameters);
    for (int i = 0; i < editorCount; i++) {
        m_editorFactories.push_back(new PerforceEditorFactory(editorParameters + i, m_coreInstance, this, describeSlot));
        addObject(m_editorFactories.back());
    }

    m_versionControl = new PerforceVersionControl(this);
    addObject(m_versionControl);

#ifdef USE_P4_API
    m_workbenchClientUser = new WorkbenchClientUser(m_perforceOutputWindow, this);
    m_enableP4APIActions = true;
#endif

    m_coreListener = new CoreListener(this);
    addObject(m_coreListener);


    //register actions
    Core::ActionManagerInterface *am = m_coreInstance->actionManager();

    Core::IActionContainer *mtools =
        am->actionContainer(Core::Constants::M_TOOLS);

    Core::IActionContainer *mperforce =
        am->createMenu(QLatin1String(PERFORCE_MENU));
    mperforce->menu()->setTitle(tr("&Perforce"));
    mtools->addMenu(mperforce);
241
242
243
244
    if (QAction *ma = mperforce->menu()->menuAction()) {
        ma->setEnabled(m_versionControl->isEnabled());
        connect(m_versionControl, SIGNAL(enabledChanged(bool)), ma, SLOT(setVisible(bool)));
    }
con's avatar
con committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375

    QList<int> globalcontext;
    globalcontext << Core::Constants::C_GLOBAL_ID;

    QList<int> perforcesubmitcontext;
    perforcesubmitcontext <<
            m_coreInstance->uniqueIDManager()->uniqueIdentifier(Constants::C_PERFORCESUBMITEDITOR);

    Core::ICommand *command;
    QAction *tmpaction;

    m_editAction = new QAction(tr("Edit"), this);
    command = am->registerAction(m_editAction, PerforcePlugin::EDIT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+E")));
    command->setDefaultText(tr("Edit File"));
    connect(m_editAction, SIGNAL(triggered()), this, SLOT(openCurrentFile()));
    mperforce->addAction(command);

    m_addAction = new QAction(tr("Add"), this);
    command = am->registerAction(m_addAction, PerforcePlugin::ADD, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+A")));
    command->setDefaultText(tr("Add File"));
    connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
    mperforce->addAction(command);

    m_deleteAction = new QAction(tr("Delete"), this);
    command = am->registerAction(m_deleteAction, PerforcePlugin::DELETE_FILE, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultText(tr("Delete File"));
    connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteCurrentFile()));
    mperforce->addAction(command);

    m_revertAction = new QAction(tr("Revert"), this);
    command = am->registerAction(m_revertAction, PerforcePlugin::REVERT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+R")));
    command->setDefaultText(tr("Revert File"));
    connect(m_revertAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
    mperforce->addAction(command);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    command = am->registerAction(tmpaction, QLatin1String("Perforce.Sep.Edit"), globalcontext);
    mperforce->addAction(command);

    m_diffCurrentAction = new QAction(tr("Diff Current File"), this);
    command = am->registerAction(m_diffCurrentAction, PerforcePlugin::DIFF_CURRENT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultText(tr("Diff Current File"));
    connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
    mperforce->addAction(command);

    m_diffProjectAction = new QAction(tr("Diff Current Project/Session"), this);
    command = am->registerAction(m_diffProjectAction, PerforcePlugin::DIFF_PROJECT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+D")));
    command->setDefaultText(tr("Diff Current Project/Session"));
    connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffCurrentProject()));
    mperforce->addAction(command);

    m_diffAllAction = new QAction(tr("Diff Opened Files"), this);
    command = am->registerAction(m_diffAllAction, PerforcePlugin::DIFF_ALL, globalcontext);
    connect(m_diffAllAction, SIGNAL(triggered()), this, SLOT(diffAllOpened()));
    mperforce->addAction(command);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    command = am->registerAction(tmpaction, QLatin1String("Perforce.Sep.Diff"), globalcontext);
    mperforce->addAction(command);

    m_openedAction = new QAction(tr("Opened"), this);
    command = am->registerAction(m_openedAction, PerforcePlugin::OPENED, globalcontext);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+O")));
    connect(m_openedAction, SIGNAL(triggered()), this, SLOT(printOpenedFileList()));
    mperforce->addAction(command);

#ifdef USE_P4_API
    m_resolveAction = new QAction(tr("Resolve"), this);
    command = am->registerAction(m_resolveAction, PerforcePlugin::RESOLVE, globalcontext);
    connect(m_resolveAction, SIGNAL(triggered()), this, SLOT(resolve()));
    mperforce->addAction(command);
#endif

    m_submitAction = new QAction(tr("Submit Project"), this);
    command = am->registerAction(m_submitAction, PerforcePlugin::SUBMIT, globalcontext);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+S")));
    connect(m_submitAction, SIGNAL(triggered()), this, SLOT(submit()));
    mperforce->addAction(command);

    m_pendingAction = new QAction(tr("Pending Changes..."), this);
    command = am->registerAction(m_pendingAction, PerforcePlugin::PENDING_CHANGES, globalcontext);
    connect(m_pendingAction, SIGNAL(triggered()), this, SLOT(printPendingChanges()));
    mperforce->addAction(command);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    command = am->registerAction(tmpaction, QLatin1String("Perforce.Sep.Changes"), globalcontext);
    mperforce->addAction(command);

    m_describeAction = new QAction(tr("Describe..."), this);
    command = am->registerAction(m_describeAction, PerforcePlugin::DESCRIBE, globalcontext);
    connect(m_describeAction, SIGNAL(triggered()), this, SLOT(describeChange()));
    mperforce->addAction(command);

    m_annotateCurrentAction = new QAction(tr("Annotate Current File"), this);
    command = am->registerAction(m_annotateCurrentAction, PerforcePlugin::ANNOTATE_CURRENT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultText(tr("Annotate Current File"));
    connect(m_annotateCurrentAction, SIGNAL(triggered()), this, SLOT(annotateCurrentFile()));
    mperforce->addAction(command);

    m_annotateAction = new QAction(tr("Annotate..."), this);
    command = am->registerAction(m_annotateAction, PerforcePlugin::ANNOTATE, globalcontext);
    connect(m_annotateAction, SIGNAL(triggered()), this, SLOT(annotate()));
    mperforce->addAction(command);

    m_filelogCurrentAction = new QAction(tr("Filelog Current File"), this);
    command = am->registerAction(m_filelogCurrentAction, PerforcePlugin::FILELOG_CURRENT, globalcontext);
    command->setAttribute(Core::ICommand::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(tr("Alt+P,Alt+F")));
    command->setDefaultText(tr("Filelog Current File"));
    connect(m_filelogCurrentAction, SIGNAL(triggered()), this, SLOT(filelogCurrentFile()));
    mperforce->addAction(command);

    m_filelogAction = new QAction(tr("Filelog..."), this);
    command = am->registerAction(m_filelogAction, PerforcePlugin::FILELOG, globalcontext);
    connect(m_filelogAction, SIGNAL(triggered()), this, SLOT(filelog()));
    mperforce->addAction(command);

376
    m_submitCurrentLogAction = new QAction(VCSBase::VCSBaseSubmitEditor::submitIcon(), tr("Submit"), this);
con's avatar
con committed
377
378
379
    command = am->registerAction(m_submitCurrentLogAction, Constants::SUBMIT_CURRENT, perforcesubmitcontext);
    connect(m_submitCurrentLogAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));

380
    m_diffSelectedFiles = new QAction(VCSBase::VCSBaseSubmitEditor::diffIcon(), tr("Diff Selected Files"), this);
con's avatar
con committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
    command = am->registerAction(m_diffSelectedFiles, Constants::DIFF_SELECTED, perforcesubmitcontext);

    m_undoAction = new QAction(tr("&Undo"), this);
    command = am->registerAction(m_undoAction, Core::Constants::UNDO, perforcesubmitcontext);

    m_redoAction = new QAction(tr("&Redo"), this);
    command = am->registerAction(m_redoAction, Core::Constants::REDO, perforcesubmitcontext);

    connect(m_coreInstance, SIGNAL(contextChanged(Core::IContext *)),
        this, SLOT(updateActions()));

    connect(m_coreInstance->fileManager(), SIGNAL(currentFileChanged(const QString &)),
        this, SLOT(updateActions()));

    return true;
}

void PerforcePlugin::extensionsInitialized()
{
    m_projectExplorer = ExtensionSystem::PluginManager::instance()->getObject<ProjectExplorer::ProjectExplorerPlugin>();
    if (m_projectExplorer) {
        connect(m_projectExplorer,
            SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
            this, SLOT(updateActions()));
    }
    updateActions();
}

void PerforcePlugin::openCurrentFile()
{
411
    vcsOpen(currentFileName());
con's avatar
con committed
412
413
414
415
}

void PerforcePlugin::addCurrentFile()
{
416
    vcsAdd(currentFileName());
con's avatar
con committed
417
418
419
420
}

void PerforcePlugin::deleteCurrentFile()
{
421
    vcsDelete(currentFileName());
con's avatar
con committed
422
423
424
425
}

void PerforcePlugin::revertCurrentFile()
{
hjk's avatar
hjk committed
426
    QTC_ASSERT(m_coreInstance, return);
con's avatar
con committed
427
428
429
430
431

    const QString fileName = currentFileName();
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(m_coreInstance, fileName);
    QStringList args;
    args << QLatin1String("diff") << QLatin1String("-sa");
432
    PerforceResponse result = runP4Cmd(args, QStringList(), CommandToWindow|StdErrToWindow|ErrorToWindow, codec);
con's avatar
con committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    if (result.error)
        return;

    if (!result.stdOut.isEmpty()) {
        bool doNotRevert = QMessageBox::warning(0, tr("p4 revert"),
                                                tr("The file has been changed. Do you want to revert it?"),
                                                QMessageBox::Yes, QMessageBox::No)
                            == QMessageBox::No;
        if (doNotRevert)
            return;
    }

    Core::FileManager *fm = m_coreInstance->fileManager();
    QList<Core::IFile *> files = fm->managedFiles(fileName);
    foreach (Core::IFile *file, files) {
        fm->blockFileChange(file);
    }
450
    PerforceResponse result2 = runP4Cmd(QStringList() << QLatin1String("revert") << fileName, QStringList(), CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    Core::IFile::ReloadBehavior tempBehavior =
            Core::IFile::ReloadAll;
    foreach (Core::IFile *file, files) {
        file->modified(&tempBehavior);
        fm->unblockFileChange(file);
    }
}

void PerforcePlugin::diffCurrentFile()
{
    p4Diff(QStringList(currentFileName()));
}

void PerforcePlugin::diffCurrentProject()
{
    QString name;
467
    const QStringList nativeFiles = VCSBase::VCSBaseSubmitEditor::currentProjectFiles(true, &name);
con's avatar
con committed
468
469
470
471
472
473
474
475
476
477
478
479
480
    p4Diff(nativeFiles, name);
}

void PerforcePlugin::diffAllOpened()
{
    p4Diff(QStringList());
}

void PerforcePlugin::printOpenedFileList()
{
    Core::IEditor *e = m_coreInstance->editorManager()->currentEditor();
    if (e)
        e->widget()->setFocus();
481
    PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("opened"), QStringList(), CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
482
483
484
485
486
487
488
489
490
491
492
493
}

#ifdef USE_P4_API
void PerforcePlugin::resolve()
{
    m_workbenchClientUser->setMode(WorkbenchClientUser::Resolve);
    runP4APICmd(QLatin1String("resolve"));
}
#endif

void PerforcePlugin::submit()
{
hjk's avatar
hjk committed
494
495
    QTC_ASSERT(m_coreInstance, return);

con's avatar
con committed
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
    if (!checkP4Command()) {
        showOutput(tr("No p4 executable specified!"));
        return;
    }

    if (m_changeTmpFile) {
        showOutput(tr("Another submit is currently executed."));
        m_perforceOutputWindow->popup(false);
        return;
    }

    m_changeTmpFile = new QTemporaryFile(this);
    if (!m_changeTmpFile->open()) {
        showOutput(tr("Cannot create temporary file."));
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
        return;
    }

515
516
    PerforceResponse result = runP4Cmd(QStringList()<< QLatin1String("change") << QLatin1String("-o"), QStringList(),
                                       CommandToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
517
518
519
520
521
522
523
524
525
526
527
    if (result.error) {
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
        return;
    }

    m_changeTmpFile->write(result.stdOut.toAscii());
    m_changeTmpFile->seek(0);

    // Assemble file list of project
    QString name;
528
    const QStringList nativeFiles = VCSBase::VCSBaseSubmitEditor::currentProjectFiles(true, &name);
529
530
    PerforceResponse result2 = runP4Cmd(QStringList(QLatin1String("fstat")), nativeFiles,
                                        CommandToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
531
532
533
534
535
536
537
538
    if (result2.error) {
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
        return;
    }

    QStringList stdOutLines = result2.stdOut.split(QLatin1Char('\n'));
    QStringList depotFileNames;
hjk's avatar
hjk committed
539
540
    foreach (const QString &line, stdOutLines) {
        if (line.startsWith("... depotFile"))
con's avatar
con committed
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
            depotFileNames.append(line.mid(14));
    }
    if (depotFileNames.isEmpty()) {
        showOutput(tr("Project has no files"));
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
        return;
    }

    openPerforceSubmitEditor(m_changeTmpFile->fileName(), depotFileNames);
}

Core::IEditor *PerforcePlugin::openPerforceSubmitEditor(const QString &fileName, const QStringList &depotFileNames)
{
    Core::IEditor *editor =
            m_coreInstance->editorManager()->openEditor(fileName, Constants::PERFORCESUBMITEDITOR_KIND);
    m_coreInstance->editorManager()->ensureEditorManagerVisible();
    PerforceSubmitEditor *submitEditor = dynamic_cast<PerforceSubmitEditor*>(editor);
hjk's avatar
hjk committed
559
    QTC_ASSERT(submitEditor, return 0);
con's avatar
con committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
    submitEditor->restrictToProjectFiles(depotFileNames);
    connect(submitEditor, SIGNAL(diffSelectedFiles(QStringList)), this, SLOT(slotDiff(QStringList)));
    // The actions are for some reason enabled by the context switching
    // mechanism. Disable them correctly.
    m_diffSelectedFiles->setEnabled(false);
    m_undoAction->setEnabled(false);
    m_redoAction->setEnabled(false);
    return editor;
}

void PerforcePlugin::printPendingChanges()
{
    qApp->setOverrideCursor(Qt::WaitCursor);
    PendingChangesDialog dia(pendingChangesData(), m_coreInstance->mainWindow());
    qApp->restoreOverrideCursor();
    if (dia.exec() == QDialog::Accepted) {
576
577
578
579
        const int i = dia.changeNumber();
        QStringList args(QLatin1String("submit"));
        args << QLatin1String("-c") << QString::number(i);
        runP4Cmd(args, QStringList(), CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    }
}

void PerforcePlugin::describeChange()
{
    ChangeNumberDialog dia;
    if (dia.exec() == QDialog::Accepted && dia.number() > 0)
        describe(QString(), QString::number(dia.number()));
}

void PerforcePlugin::annotateCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        annotate(file);
}

void PerforcePlugin::annotate()
{
    const QString file = QFileDialog::getOpenFileName(0, tr("p4 annotate"), currentFileName());
    if (!file.isEmpty())
        annotate(file);
}

void PerforcePlugin::annotate(const QString &fileName)
{
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(m_coreInstance, fileName);
    QStringList args;
    args << QLatin1String("annotate") << QLatin1String("-cqi") << fileName;
609
610
    const PerforceResponse result = runP4Cmd(args, QStringList(),
                                             CommandToWindow|StdErrToWindow|ErrorToWindow, codec);
con's avatar
con committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
    if (!result.error) {
        const QFileInfo fi(fileName);
        showOutputInEditor(tr("p4 annotate %1").arg(fi.fileName()), result.stdOut, VCSBase::AnnotateOutput, codec);
    }
}

void PerforcePlugin::filelogCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        filelog(file);
}

void PerforcePlugin::filelog()
{
    const QString file = QFileDialog::getOpenFileName(0, tr("p4 filelog"), currentFileName());
    if (!file.isEmpty())
        filelog(file);
}

void PerforcePlugin::filelog(const QString &fileName)
{
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(m_coreInstance, fileName);
    QStringList args;
    args << QLatin1String("filelog") << QLatin1String("-li") << fileName;
636
637
    const PerforceResponse result = runP4Cmd(args, QStringList(),
                                             CommandToWindow|StdErrToWindow|ErrorToWindow, codec);
con's avatar
con committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    if (!result.error) {
        const QFileInfo fi(fileName);
        showOutputInEditor(tr("p4 filelog %1").arg(fi.fileName()), result.stdOut, VCSBase::LogOutput, codec);
    }
}

void PerforcePlugin::updateActions()
{
    QString fileName = currentFileName();
    QString baseName = QFileInfo(fileName).fileName();
    const bool hasFile = !currentFileName().isEmpty();
    m_editAction->setEnabled(hasFile);
    m_addAction->setEnabled(hasFile);
    m_deleteAction->setEnabled(hasFile);
    m_revertAction->setEnabled(hasFile);
    m_diffCurrentAction->setEnabled(hasFile);
    m_annotateCurrentAction->setEnabled(hasFile);
    m_filelogCurrentAction->setEnabled(hasFile);
    if (hasFile) {
        m_editAction->setText(tr("Edit %1").arg(baseName));
        m_addAction->setText(tr("Add %1").arg(baseName));
        m_deleteAction->setText(tr("Delete %1").arg(baseName));
        m_revertAction->setText(tr("Revert %1").arg(baseName));
        m_diffCurrentAction->setText(tr("Diff %1").arg(baseName));
        m_annotateCurrentAction->setText(tr("Annotate %1").arg(baseName));
        m_filelogCurrentAction->setText(tr("Filelog %1").arg(baseName));
    } else {
        m_editAction->setText(tr("Edit"));
        m_addAction->setText(tr("Add"));
        m_deleteAction->setText(tr("Delete"));
        m_revertAction->setText(tr("Revert"));
        m_diffCurrentAction->setText(tr("Diff"));
        m_annotateCurrentAction->setText(tr("Annotate Current File"));
        m_filelogCurrentAction->setText(tr("Filelog Current File"));
    }
    if (m_projectExplorer && m_projectExplorer->currentProject()) {
        m_diffProjectAction->setEnabled(true);
        m_diffProjectAction->setText(tr("Diff Project %1").arg(m_projectExplorer->currentProject()->name()));
        m_submitAction->setEnabled(true);
    } else {
        m_diffProjectAction->setEnabled(false);
        m_diffProjectAction->setText(tr("Diff Current Project/Soluion"));
        m_submitAction->setEnabled(false);
    }
    m_diffAllAction->setEnabled(true);
    m_openedAction->setEnabled(true);
    m_describeAction->setEnabled(true);
    m_annotateAction->setEnabled(true);
    m_filelogAction->setEnabled(true);
    m_pendingAction->setEnabled(true);


#ifdef USE_P4_API
    m_resolveAction->setEnabled(m_enableP4APIActions);
#endif
}

bool PerforcePlugin::managesDirectory(const QString &directory) const
{
    const QString p4Path = directory + QLatin1String("/...");
    QStringList args;
    args << QLatin1String("fstat") << QLatin1String("-m1") << p4Path;

701
    const PerforceResponse result = runP4Cmd(args, QStringList(), 0u);
con's avatar
con committed
702
703
704
705
706
707
    return result.stdOut.contains("depotFile") || result.stdErr.contains("... - no such file(s)");
}

QString PerforcePlugin::findTopLevelForDirectory(const QString & /* dir */) const
{
    // First check with p4 client -o
708
    PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("client") << QLatin1String("-o"), QStringList(), 0u);
con's avatar
con committed
709
710
711
712
    if (result.error)
        return QString::null;

    QRegExp regExp(QLatin1String("(\\n|\\r\\n|\\r)Root:\\s*(.*)(\\n|\\r\\n|\\r)"));
hjk's avatar
hjk committed
713
    QTC_ASSERT(regExp.isValid(), /**/);
con's avatar
con committed
714
715
716
717
718
719
720
721
722
723
724
    regExp.setMinimal(true);
    if (regExp.indexIn(result.stdOut) != -1) {
        QString file = regExp.cap(2).trimmed();
        if (QFileInfo(file).exists())
            return file;
    }
    return QString::null;
}

bool PerforcePlugin::vcsOpen(const QString &fileName)
{
725
726
    PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("edit") << QDir::toNativeSeparators(fileName), QStringList(),
                                       CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
727
728
729
730
731
    return !result.error;
}

bool PerforcePlugin::vcsAdd(const QString &fileName)
{
732
733
    PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("add") << fileName, QStringList(),
                                       CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
734
735
736
737
738
    return !result.error;
}

bool PerforcePlugin::vcsDelete(const QString &fileName)
{
739
740
741
742
    PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("revert") << fileName, QStringList(),
                                       CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
    PerforceResponse result2 = runP4Cmd(QStringList() << QLatin1String("delete") << fileName, QStringList(),
                                        CommandToWindow|StdOutToWindow|StdErrToWindow|ErrorToWindow);
con's avatar
con committed
743
744
745
746
747
748
749
750
751
752
753
754
    // TODO need to carefully parse the actual messages from perforce
    // or do a fstat before to decide what to do

    // Different states are:
    // File is in depot and unopened => p4 delete %
    // File is in depot and opened => p4 revert %, p4 delete %
    // File is not in depot => p4 revert %
    return !(result.error && result2.error);
}

PerforceResponse PerforcePlugin::runP4Cmd(const QStringList &args,
                                          const QStringList &extraArgs,
755
                                          unsigned logFlags,
con's avatar
con committed
756
757
758
759
760
761
                                          QTextCodec *outputCodec) const
{
    if (Perforce::Constants::debug)
        qDebug() << "PerforcePlugin::runP4Cmd" << args << extraArgs << debugCodec(outputCodec);
    PerforceResponse response;
    response.error = true;
hjk's avatar
hjk committed
762
    QTC_ASSERT(m_coreInstance, return response);
con's avatar
con committed
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    if (!checkP4Command()) {
        response.message = tr("No p4 executable specified!");
        m_perforceOutputWindow->append(response.message, true);
        return response;
    }

    // handle extra args
    QTemporaryFile tempfile;
    tempfile.setAutoRemove(true);
    const QChar newLine = QLatin1Char('\n');
    const QChar blank = QLatin1Char(' ');
    QStringList actualArgs = basicP4Args();
    if (!extraArgs.isEmpty()) {
        if (tempfile.open()) {
            QTextStream stream(&tempfile);
            stream << extraArgs.join(QString(newLine));
            actualArgs << QLatin1String("-x") << tempfile.fileName();
            tempfile.close();
        } else {
            qWarning()<<"Could not create temporary file. Appending all file names to command line.";
            actualArgs << extraArgs;
        }
    }
    actualArgs << args;

788
789
790
791
792
793
794
795
    if (logFlags & CommandToWindow) {
        QString command = m_settings.p4Command;
        command += blank;
        command += actualArgs.join(QString(blank));
        const QString timeStamp = QTime::currentTime().toString(QLatin1String("HH:mm"));
        const QString outputText = tr("%1 Executing: %2\n").arg(timeStamp, command);
        showOutput(outputText, false);
    }
con's avatar
con committed
796
797
798
799
800
801
802
803

    // Run, connect stderr to the output window
    Core::Utils::SynchronousProcess process;
    process.setTimeout(p4Timeout);
    process.setStdOutCodec(outputCodec);
    process.setEnvironment(environment());

    // connect stderr to the output window if desired
804
    if (logFlags & StdErrToWindow) {
con's avatar
con committed
805
806
807
808
809
        process.setStdErrBufferedSignalsEnabled(true);
        connect(&process, SIGNAL(stdErrBuffered(QString,bool)), m_perforceOutputWindow, SLOT(append(QString,bool)));
    }

    // connect stdout to the output window if desired
810
    if (logFlags & StdOutToWindow) {
con's avatar
con committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
        process.setStdOutBufferedSignalsEnabled(true);
        connect(&process, SIGNAL(stdOutBuffered(QString,bool)), m_perforceOutputWindow, SLOT(append(QString,bool)));
    }

    const Core::Utils::SynchronousProcessResponse sp_resp = process.run(m_settings.p4Command, actualArgs);
    if (Perforce::Constants::debug)
        qDebug() << sp_resp;

    response.error = true;
    response.stdErr = sp_resp.stdErr;
    response.stdOut = sp_resp.stdOut;
    switch (sp_resp.result) {
    case Core::Utils::SynchronousProcessResponse::Finished:
        response.error = false;
        break;
    case Core::Utils::SynchronousProcessResponse::FinishedError:
        response.message = tr("The process terminated with exit code %1.").arg(sp_resp.exitCode);
        break;
    case Core::Utils::SynchronousProcessResponse::TerminatedAbnormally:
        response.message = tr("The process terminated abnormally.");
        break;
    case Core::Utils::SynchronousProcessResponse::StartFailed:
        response.message = tr("Could not start perforce '%1'. Please check your settings in the preferences.").arg(m_settings.p4Command);
        break;
    case Core::Utils::SynchronousProcessResponse::Hang:
836
        response.message = tr("Perforce did not respond within timeout limit (%1 ms).").arg(p4Timeout );
con's avatar
con committed
837
838
        break;
    }
839
840
841
842
843
844
    if (response.error) {
        if (Perforce::Constants::debug)
            qDebug() << response.message;
        if (logFlags & ErrorToWindow)
            m_perforceOutputWindow->append(response.message, true);
    }
con's avatar
con committed
845
846
847
848
849
850
851
    return response;
}

Core::IEditor * PerforcePlugin::showOutputInEditor(const QString& title, const QString output,
                                                   int editorType, QTextCodec *codec)
{
    const VCSBase::VCSBaseEditorParameters *params = findType(editorType);
hjk's avatar
hjk committed
852
    QTC_ASSERT(params, return 0);
con's avatar
con committed
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
    const QString kind = QLatin1String(params->kind);
    if (Perforce::Constants::debug)
        qDebug() << "PerforcePlugin::showOutputInEditor" << title << kind <<  "Size= " << output.size() <<  " Type=" << editorType << debugCodec(codec);
    QString s = title;
    Core::IEditor *ediface = m_coreInstance->editorManager()->
        newFile(kind, &s, output.toLocal8Bit());
    PerforceEditor *e = qobject_cast<PerforceEditor*>(ediface->widget());
    if (!e)
        return 0;
    s.replace(QLatin1Char(' '), QLatin1Char('_'));
    e->setSuggestedFileName(s);
    if (codec)
        e->setCodec(codec);
    return e->editableInterface();
}

QStringList PerforcePlugin::environment() const
{
    QStringList newEnv = QProcess::systemEnvironment();
    const QString name = "P4DIFF";
    for (int i=0; i<newEnv.count(); ++i) {
        if (newEnv.at(i).startsWith(name)) {
            newEnv.removeAt(i);
            return newEnv;
        }
    }
    return newEnv;
}

void PerforcePlugin::slotDiff(const QStringList &files)
{
    p4Diff(files);
}

void PerforcePlugin::p4Diff(const QStringList &files, QString diffname)
{
    Core::IEditor *editor = 0;
    bool displayInEditor = true;
    Core::IEditor *existingEditor = 0;
    QTextCodec *codec = files.empty() ? static_cast<QTextCodec *>(0) : VCSBase::VCSBaseEditor::getCodec(m_coreInstance, files.front());
    if (Perforce::Constants::debug)
        qDebug() << Q_FUNC_INFO << files << debugCodec(codec);

    // diff of a single file? re-use an existing view if possible to support the common
    // usage pattern of continuously changing and diffing a file
    if (files.count() == 1) {
        const QString fileName = files.at(0);
        if (diffname.isEmpty()) {
            const QFileInfo fi(fileName);
            diffname = fi.fileName();
        }

        foreach (Core::IEditor *ed, m_coreInstance->editorManager()->openedEditors()) {
            if (ed->property("originalFileName").toString() == fileName) {
                existingEditor = ed;
                displayInEditor = false;
                break;
            }
        }
    }

914
    const PerforceResponse result = runP4Cmd(QStringList() << QLatin1String("diff") << QLatin1String("-du"), files, CommandToWindow|StdErrToWindow|ErrorToWindow, codec);
con's avatar
con committed
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
    if (result.error)
        return;

    if (displayInEditor)
        editor = showOutputInEditor(tr("p4 diff %1").arg(diffname), result.stdOut, VCSBase::DiffOutput, codec);


    if (files.count() == 1) {
        if (displayInEditor && editor != 0) {
            editor->setProperty("originalFileName", files.at(0));
        } else if (!displayInEditor && existingEditor) {
            if (existingEditor) {
                existingEditor->createNew(result.stdOut);
                m_coreInstance->editorManager()->setCurrentEditor(existingEditor);
            }
        }
    }
}

void PerforcePlugin::describe(const QString & source, const QString &n)
{
    QTextCodec *codec = source.isEmpty() ? static_cast<QTextCodec *>(0) : VCSBase::VCSBaseEditor::getCodec(m_coreInstance, source);
    QStringList args;
    args << QLatin1String("describe") << QLatin1String("-du") << n;
939
    const PerforceResponse result = runP4Cmd(args, QStringList(), CommandToWindow|StdErrToWindow|ErrorToWindow, codec);
con's avatar
con committed
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
    if (!result.error)
        showOutputInEditor(tr("p4 describe %1").arg(n), result.stdOut, VCSBase::DiffOutput, codec);
}

void PerforcePlugin::submitCurrentLog()
{
    m_coreInstance->editorManager()->closeEditors(QList<Core::IEditor*>()
        << m_coreInstance->editorManager()->currentEditor());
}

bool PerforcePlugin::editorAboutToClose(Core::IEditor *editor)
{
    if (!m_changeTmpFile || !editor)
        return true;
    Core::IFile *fileIFace = editor->file();
    if (!fileIFace)
        return true;
    QFileInfo editorFile(fileIFace->fileName());
    QFileInfo changeFile(m_changeTmpFile->fileName());
    if (editorFile.absoluteFilePath() == changeFile.absoluteFilePath()) {
        const QMessageBox::StandardButton answer = QMessageBox::question(m_coreInstance->mainWindow(), tr("Closing p4 Editor"),  tr("Do you want to submit this change list?"),
                                                                         QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel, QMessageBox::Yes);
        if (answer == QMessageBox::Cancel) {
            return false;
        }

        m_coreInstance->fileManager()->blockFileChange(fileIFace);
        fileIFace->save();
        m_coreInstance->fileManager()->unblockFileChange(fileIFace);
        if (answer == QMessageBox::Yes) {
            QByteArray change = m_changeTmpFile->readAll();
            m_changeTmpFile->close();
            if (!checkP4Command()) {
                showOutput(tr("No p4 executable specified!"));
                delete m_changeTmpFile;
                m_changeTmpFile = 0;
                return false;
            }
            QProcess proc;
            proc.setEnvironment(environment());

            QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
            proc.start(m_settings.p4Command,
                basicP4Args() << QLatin1String("submit") << QLatin1String("-i"));
            if (!proc.waitForStarted(3000)) {
                showOutput(tr("Cannot execute p4 submit."));
                QApplication::restoreOverrideCursor();
                delete m_changeTmpFile;
                m_changeTmpFile = 0;
                return false;
            }
            proc.write(change);
            proc.closeWriteChannel();

            if (!proc.waitForFinished()) {
                showOutput(tr("Cannot execute p4 submit."));
                QApplication::restoreOverrideCursor();
                delete m_changeTmpFile;
                m_changeTmpFile = 0;
                return false;
            }
            QString output = QString::fromUtf8(proc.readAll());
            showOutput(output);
            if (output.contains("Out of date files must be resolved or reverted")) {
                QMessageBox::warning(editor->widget(), "Pending change", "Could not submit the change, because your workspace was out of date. Created a pending submit instead.");
            }
            QApplication::restoreOverrideCursor();
        }
        m_changeTmpFile->close();
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
    }
    return true;
}

void PerforcePlugin::openFiles(const QStringList &files)
{
    foreach (QString s, files) {
        m_coreInstance->editorManager()->openEditor(clientFilePath(s));
    }
    m_coreInstance->editorManager()->ensureEditorManagerVisible();
}

QString PerforcePlugin::clientFilePath(const QString &serverFilePath)
{
hjk's avatar
hjk committed
1025
    QTC_ASSERT(m_coreInstance, return QString());
con's avatar
con committed
1026
    if (!checkP4Command())
hjk's avatar
hjk committed
1027
        return QString();
con's avatar
con committed
1028
1029
1030
1031
1032
1033
1034

    QApplication::setOverrideCursor(Qt::WaitCursor);
    QProcess proc;
    proc.setEnvironment(environment());
    proc.start(m_settings.p4Command,
        basicP4Args() << QLatin1String("fstat") << serverFilePath);

hjk's avatar
hjk committed
1035
    QString path;
con's avatar
con committed
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    if (proc.waitForFinished(3000)) {
        QString output = QString::fromUtf8(proc.readAllStandardOutput());
        if (!output.isEmpty()) {
            QRegExp r(QLatin1String("\\.\\.\\.\\sclientFile\\s(.+)\n"));
            r.setMinimal(true);
            if (r.indexIn(output) != -1)
                path = r.cap(1).trimmed();
        }
    }
    QApplication::restoreOverrideCursor();
    return path;
}

QString PerforcePlugin::currentFileName()
{
    QString fileName = m_coreInstance->fileManager()->currentFile();

    // TODO: Use FileManager::fixPath
    const QFileInfo fileInfo(fileName);
    if (fileInfo.exists())
        fileName = fileInfo.absoluteFilePath();
    fileName = QDir::toNativeSeparators(fileName);
    return fileName;
}

QStringList PerforcePlugin::basicP4Args() const
{
    QStringList lst;
    if (!m_settings.defaultEnv) {
        lst << QLatin1String("-c") << m_settings.p4Client;
        lst << QLatin1String("-p") << m_settings.p4Port;
        lst << QLatin1String("-u") << m_settings.p4User;
    }
    return lst;
}

bool PerforcePlugin::checkP4Command() const
{
    if (m_settings.p4Command.isEmpty())
        return false;
    return true;
}

#ifdef USE_P4_API
void PerforcePlugin::runP4APICmd(const QString &cmd, const QStringList &args)
{
    m_enableP4APIActions = false;
    updateActions();

    ClientApi client;
    if (!m_settings.defaultEnv) {
        client.SetClient(m_settings.p4Client.toLatin1().constData());
        client.SetPort(m_settings.p4Port.toLatin1().constData());
        client.SetUser(m_settings.p4User.toLatin1().constData());
    }

    Error err;
    m_coreInstance->messageManager()->displayStatusBarMessage(tr("Connecting to p4 server..."));
    client.SetProtocol("api", "56");
    client.Init(&err);
    if (err.Test()) {
        StrBuf msg;
        err.Fmt(&msg);
        QMessageBox::critical(m_coreInstance->mainWindow(), tr("Perforce Plugin"), tr("Failed to connect to p4 server <b>%1</b>!").arg(msg.Text()));
        client.Final(&err);
        m_coreInstance->messageManager()->displayStatusBarMessage(tr("Connection to p4 server failed!"), 3000);
        return;
    }
    m_coreInstance->messageManager()->displayStatusBarMessage(tr("Connection to p4 server established."), 3000);

    // ????
    //client.SetCwd("c:\\depot\\research\\qworkbench\\src");

    int argc = args.count();
    char **argv = (char**)malloc(argc*sizeof(char*));
    int i = 0;
    foreach (QString s, args)
        argv[i++] = qstrdup(s.toLatin1().constData());

    client.SetArgv( argc, argv );
    try {
        client.Run(cmd.toLatin1().constData(), m_workbenchClientUser);
    } catch (...) {
        QMessageBox::critical(m_coreInstance->mainWindow(), tr("Perforce Plugin"), tr("Failed to run command <b>%1</b>!").arg(cmd));
    }
    client.Final(&err);
    i = 0;
    while (i<argc)
        free(argv[i++]);
    free(argv);

    m_enableP4APIActions = true;
    updateActions();

    Core::IEditor *edt = m_coreInstance->editorManager()->currentEditor();
    if (edt && edt->widget())
        edt->widget()->setFocus();
}
#endif

QString PerforcePlugin::pendingChangesData()
{
    QString data;
    Q_ASSERT(m_coreInstance);
    if (!checkP4Command())
        return data;

    QString user;
    QProcess proc;
    proc.setEnvironment(environment());
    proc.start(m_settings.p4Command,
        basicP4Args() << QLatin1String("info"));
    if (proc.waitForFinished(3000)) {
        QString output = QString::fromUtf8(proc.readAllStandardOutput());
        if (!output.isEmpty()) {
            QRegExp r(QLatin1String("User\\sname:\\s(\\S+)\\s*\n"));
            r.setMinimal(true);
            if (r.indexIn(output) != -1)
                user = r.cap(1).trimmed();
        }
    }
    if (user.isEmpty())
        return data;
    proc.start(m_settings.p4Command,
        basicP4Args() << QLatin1String("changes") << QLatin1String("-s") << QLatin1String("pending") << QLatin1String("-u") << user);
    if (proc.waitForFinished(3000))
        data = QString::fromUtf8(proc.readAllStandardOutput());
    return data;
}

void PerforcePlugin::showOutput(const QString &output, bool popup) const
{
    m_perforceOutputWindow->append(output, popup);
}

PerforcePlugin::~PerforcePlugin()
{
    if (m_settingsPage) {
        removeObject(m_settingsPage);
        delete m_settingsPage;
        m_settingsPage = 0;
    }

#ifdef USE_P4_API
    if (m_workbenchClientUser) {
        delete m_workbenchClientUser;
        m_workbenchClientUser = 0;
    }
#endif
    if (m_perforceOutputWindow) {
        removeObject(m_perforceOutputWindow);
        delete  m_perforceOutputWindow;
        m_perforceOutputWindow = 0;
    }
    if (m_submitEditorFactory) {
        removeObject(m_submitEditorFactory);
        delete m_submitEditorFactory;
        m_submitEditorFactory = 0;
    }
    if (m_versionControl) {
        removeObject(m_versionControl);
        delete m_versionControl;
        m_versionControl = 0;
    }

    if (!m_editorFactories.empty()) {
hjk's avatar
hjk committed
1202
        foreach (Core::IEditorFactory *pf, m_editorFactories)
con's avatar
con committed
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
            removeObject(pf);
        qDeleteAll(m_editorFactories);
        m_editorFactories.clear();
    }

    if (m_coreListener) {
        removeObject(m_coreListener);
        delete m_coreListener;
        m_coreListener = 0;
    }
}

PerforceSettings PerforcePlugin::settings() const
{
    return m_settings;
}

void PerforcePlugin::setSettings(const PerforceSettings &s)
{
    if (s != m_settings) {
        m_settings = s;
        if (QSettings *settings = m_coreInstance->settings())
            m_settings.toSettings(settings);
    }
}

// Map a perforce name "//xx" to its real name in the file system
QString PerforcePlugin::fileNameFromPerforceName(const QString& perforceName,
                                                 QString *errorMessage) const
{
    // All happy, already mapped
    if (!perforceName.startsWith(QLatin1String("//")))
        return perforceName;
    // "where" remaps the file to client file tree
    QProcess proc;
    QStringList args(basicP4Args());
    args << QLatin1String("where") << perforceName;
    proc.start(m_settings.p4Command, args);
    if (!proc.waitForFinished()) {
        *errorMessage = tr("Timeout waiting for \"where\" (%1).").arg(perforceName);
        return QString();
    }

    QString output = QString::fromLocal8Bit(proc.readAllStandardOutput());
    if (output.endsWith(QLatin1Char('\r')))
        output.chop(1);
    if (output.endsWith(QLatin1Char('\n')))
        output.chop(1);

    if (output.isEmpty()) {
        *errorMessage = tr("Error running \"where\" on %1: The file is not mapped").arg(perforceName);
        return QString();
    }
    const QString rc = output.mid(output.lastIndexOf(QLatin1Char(' ')) + 1);
    if (Perforce::Constants::debug)
        qDebug() << "fileNameFromPerforceName" << perforceName << rc;
    return rc;
}

hjk's avatar
hjk committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
Core::ICore *PerforcePlugin::coreInstance()
{       
    QTC_ASSERT(m_coreInstance, return 0);
    return m_coreInstance;
}

PerforcePlugin *PerforcePlugin::perforcePluginInstance()
{
    QTC_ASSERT(m_perforcePluginInstance, return 0);
    return m_perforcePluginInstance;
}

con's avatar
con committed
1274
1275
Q_EXPORT_PLUGIN(PerforcePlugin)