formeditorw.cpp 27 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 35 36 37 38 39 40 41 42 43
#include "formeditorw.h"
#include "formwindoweditor.h"
#include "designerconstants.h"
#include "settingsmanager.h"
#include "settingspage.h"
#include "editorwidget.h"
#include "workbenchintegration.h"

#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
44
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
45
#include <coreplugin/editormanager/editormanager.h>
hjk's avatar
hjk committed
46
#include <utils/qtcassert.h>
con's avatar
con committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 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

#include <QtDesigner/QDesignerFormEditorPluginInterface>
#include <QtDesigner/private/pluginmanager_p.h>

#include <QtDesigner/private/iconloader_p.h>  // createIconSet
#include <QtDesigner/private/qdesigner_formwindowmanager_p.h>
#include <QtDesigner/private/formwindowbase_p.h>
#include <QtDesigner/QDesignerFormEditorInterface>
#include <QtDesigner/QDesignerComponents>

#include <QtDesigner/QDesignerWidgetBoxInterface>
#include <QtDesigner/abstractobjectinspector.h>
#include <QtDesigner/QDesignerComponents>
#include <QtDesigner/QDesignerPropertyEditorInterface>
#include <QtDesigner/QDesignerActionEditorInterface>

#include <QtCore/QPluginLoader>
#include <QtCore/QTemporaryFile>
#include <QtCore/QDir>
#include <QtCore/QTime>
#include <QtGui/QAction>
#include <QtGui/QActionGroup>
#include <QtGui/QApplication>
#include <QtGui/QCursor>
#include <QtGui/QMenu>
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
#include <QtGui/QKeySequence>
#include <QtGui/QPrintDialog>
#include <QtGui/QPrinter>
#include <QtGui/QPainter>
#include <QtGui/QStatusBar>
#include <QtGui/QStyle>
#include <QtGui/QToolBar>

#include <QtCore/QDebug>
#include <QtCore/QSettings>

enum { debugFormEditor = 0 };
enum { wantCodeGenerationAction = 0 };

static const char *editorWidgetStateKeyC = "editorWidgetState";
static const char *settingsGroup = "Designer";

static inline QIcon designerIcon(const QString &iconName)
{
    const QIcon icon = qdesigner_internal::createIconSet(iconName);
    if (icon.isNull())
        qWarning() << "Unable to locate " << iconName;
    return icon;
}

// Create an action to activate a designer tool
static inline QAction *createEditModeAction(QActionGroup *ag,
                                     const QList<int> &context,
102
                                     Core::ActionManager *am,
con's avatar
con committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
                                     Core::IActionContainer *medit,
                                     const QString &actionName,
                                     const QString &name,
                                     int toolNumber,
                                     const QString &iconName =  QString(),
                                     const QString &keySequence = QString())
{
    QAction *rc = new QAction(actionName, ag);
    rc->setCheckable(true);
    if (!iconName.isEmpty())
         rc->setIcon(designerIcon(iconName));
    Core::ICommand *command = am->registerAction(rc, name, context);
    if (!keySequence.isEmpty())
        command->setDefaultKeySequence(QKeySequence(keySequence));
    command->setAttribute(Core::ICommand::CA_Hide);
    medit->addAction(command, Core::Constants::G_EDIT_OTHER);
    rc->setData(toolNumber);
    ag->addAction(rc);
    return rc;
}


// Create a menu separato
static inline QAction * createSeparator(QObject *parent,
127
                                 Core::ActionManager *am,
con's avatar
con committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141
                                 const QList<int> &context,
                                 Core::IActionContainer *container,
                                 const QString &name = QString(),
                                 const QString &group = QString())
{
    QAction *actSeparator = new QAction(parent);
    actSeparator->setSeparator(true);
    Core::ICommand *command = am->registerAction(actSeparator, name, context);
    container->addAction(command, group);
    return actSeparator;
}

// Create a tool action
static inline void addToolAction(QAction *a,
142
                   Core::ActionManager *am,
con's avatar
con committed
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
                   const QList<int> &context,
                   const QString &name,
                   Core::IActionContainer *c1,
                   const QString &keySequence = QString())
{
    Core::ICommand *command = am->registerAction(a, name, context);
    if (!keySequence.isEmpty())
        command->setDefaultKeySequence(QKeySequence(keySequence));
    c1->addAction(command);
}

// --------- FormEditorW

using namespace Designer::Internal;
using namespace Designer::Constants;

FormEditorW *FormEditorW::m_self = 0;

FormEditorW::FormEditorW() :
    m_formeditor(QDesignerComponents::createFormEditor(0)),
    m_integration(0),
    m_fwm(0),
    m_core(ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>()),
    m_initStage(RegisterPlugins),
    m_actionGroupEditMode(0),
    m_actionPrint(0),
    m_actionGenerateCode(0)
{
    if (debugFormEditor)
        qDebug() << Q_FUNC_INFO;
hjk's avatar
hjk committed
173
    QTC_ASSERT(!m_self, return);
con's avatar
con committed
174
    m_self = this;
hjk's avatar
hjk committed
175
    QTC_ASSERT(m_core, return);
con's avatar
con committed
176 177 178 179 180 181 182 183

    qFill(m_designerSubWindows, m_designerSubWindows + Designer::Constants::DesignerSubWindowCount,
          static_cast<QWidget *>(0));

    m_formeditor->setTopLevel(qobject_cast<QWidget *>(m_core->editorManager()));
    m_formeditor->setSettingsManager(new SettingsManager());

    m_fwm = qobject_cast<qdesigner_internal::QDesignerFormWindowManager*>(m_formeditor->formWindowManager());
hjk's avatar
hjk committed
184
    QTC_ASSERT(m_fwm, return);
con's avatar
con committed
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

    const int uid = m_core->uniqueIDManager()->uniqueIdentifier(QLatin1String(C_FORMEDITOR));
    m_context << uid;

    setupActions();

    foreach (QDesignerOptionsPageInterface *designerPage, m_formeditor->optionsPages()) {
        SettingsPage *settingsPage = new SettingsPage(designerPage);
        ExtensionSystem::PluginManager::instance()->addObject(settingsPage);
        m_settingsPages.append(settingsPage);
    }
    restoreSettings(m_core->settings());

    connect(m_core->editorManager(), SIGNAL(currentEditorChanged(Core::IEditor *)),
            this, SLOT(currentEditorChanged(Core::IEditor *)));
}

FormEditorW::~FormEditorW()
{
    saveSettings(m_core->settings());

    for (int i = 0; i < Designer::Constants::DesignerSubWindowCount; ++i)
        delete m_designerSubWindows[i];

    delete m_formeditor;
    foreach (SettingsPage *settingsPage, m_settingsPages) {
        ExtensionSystem::PluginManager::instance()->removeObject(settingsPage);
        delete settingsPage;
    }
    delete  m_integration;
    m_self = 0;
}

void FormEditorW::fullInit()
{
hjk's avatar
hjk committed
220
    QTC_ASSERT(m_initStage == RegisterPlugins, return);
con's avatar
con committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 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
    QTime *initTime = 0;
    if (debugFormEditor) {
        initTime = new QTime;
        initTime->start();
    }

    QDesignerComponents::createTaskMenu(m_formeditor, parent());
    QDesignerComponents::initializePlugins(designerEditor());
    QDesignerComponents::initializeResources();
    initDesignerSubWindows();
    m_integration = new WorkbenchIntegration(m_formeditor, this);
    m_formeditor->setIntegration(m_integration);

    /**
     * This will initialize our TabOrder, Signals and slots and Buddy editors.
     */
    QList<QObject*> plugins = QPluginLoader::staticInstances();
    plugins += m_formeditor->pluginManager()->instances();
    foreach (QObject *plugin, plugins) {
        if (QDesignerFormEditorPluginInterface *formEditorPlugin = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) {
            if (!formEditorPlugin->isInitialized())
                formEditorPlugin->initialize(m_formeditor);
        }
    }

    if (debugFormEditor) {
        qDebug() << Q_FUNC_INFO << initTime->elapsed() << "ms";
        delete initTime;
    }
    m_initStage = FullyInitialized;
}

void FormEditorW::initDesignerSubWindows()
{
    qFill(m_designerSubWindows, m_designerSubWindows + Designer::Constants::DesignerSubWindowCount, static_cast<QWidget*>(0));

    QDesignerWidgetBoxInterface *wb = QDesignerComponents::createWidgetBox(m_formeditor, 0);
    wb->setWindowTitle(tr("Designer widgetbox"));
    m_formeditor->setWidgetBox(wb);
    m_designerSubWindows[WidgetBoxSubWindow] = wb;

    QDesignerObjectInspectorInterface *oi = QDesignerComponents::createObjectInspector(m_formeditor, 0);
    oi->setWindowTitle(tr("Object inspector"));
    m_formeditor->setObjectInspector(oi);
    m_designerSubWindows[ObjectInspectorSubWindow] = oi;

    QDesignerPropertyEditorInterface *pe = QDesignerComponents::createPropertyEditor(m_formeditor, 0);
    pe->setWindowTitle(tr("Property editor"));
    m_formeditor->setPropertyEditor(pe);
    m_designerSubWindows[PropertyEditorSubWindow] = pe;

    QWidget *se = QDesignerComponents::createSignalSlotEditor(m_formeditor, 0);
    se->setWindowTitle(tr("Signals and slots editor"));
    m_designerSubWindows[SignalSlotEditorSubWindow] = se;

    QDesignerActionEditorInterface *ae = QDesignerComponents::createActionEditor(m_formeditor, 0);
    ae->setWindowTitle(tr("Action editor"));
    m_formeditor->setActionEditor(ae);
    m_designerSubWindows[ActionEditorSubWindow] = ae;
}

void FormEditorW::ensureInitStage(InitializationStage s)
{
    if (debugFormEditor)
        qDebug() << Q_FUNC_INFO << s;
    if (!m_self)
        m_self = new FormEditorW;
    if (m_self->m_initStage >= s)
        return;
    QApplication::setOverrideCursor(Qt::WaitCursor);
    m_self->fullInit();
    QApplication::restoreOverrideCursor();
}

FormEditorW *FormEditorW::instance()
{
    ensureInitStage(FullyInitialized);
    return m_self;
}

void FormEditorW::deleteInstance()
{
    delete m_self;
}

void FormEditorW::setupActions()
{
308
    Core::ActionManager *am = m_core->actionManager();
con's avatar
con committed
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 376 377 378 379 380 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 411 412 413
    Core::ICommand *command;

    //menus
    Core::IActionContainer *medit =
        am->actionContainer(Core::Constants::M_EDIT);
    Core::IActionContainer *mtools =
        am->actionContainer(Core::Constants::M_TOOLS);

    Core::IActionContainer *mformtools =
        am->createMenu(M_FORMEDITOR);
    mformtools->menu()->setTitle(tr("For&m editor"));
    mtools->addMenu(mformtools);

    //overridden actions
    am->registerAction(m_fwm->actionUndo(), Core::Constants::UNDO, m_context);
    am->registerAction(m_fwm->actionRedo(), Core::Constants::REDO, m_context);
    am->registerAction(m_fwm->actionCut(), Core::Constants::CUT, m_context);
    am->registerAction(m_fwm->actionCopy(), Core::Constants::COPY, m_context);
    am->registerAction(m_fwm->actionPaste(), Core::Constants::PASTE, m_context);
    am->registerAction(m_fwm->actionSelectAll(), Core::Constants::SELECTALL, m_context);

    m_actionPrint = new QAction(this);
    am->registerAction(m_actionPrint, Core::Constants::PRINT, m_context);
    connect(m_actionPrint, SIGNAL(triggered()), this, SLOT(print()));

    //'delete' action
    command = am->registerAction(m_fwm->actionDelete(), QLatin1String("FormEditor.Edit.Delete"), m_context);
    command->setDefaultKeySequence(QKeySequence::Delete);
    command->setAttribute(Core::ICommand::CA_Hide);
    medit->addAction(command, Core::Constants::G_EDIT_COPYPASTE);

    //editor Modes. Store ids for editor tool bars
    m_actionGroupEditMode = new QActionGroup(this);
    m_actionGroupEditMode->setExclusive(true);
    connect(m_actionGroupEditMode, SIGNAL(triggered(QAction*)), this, SLOT(activateEditMode(QAction*)));

    m_toolActionIds.push_back(QLatin1String("FormEditor.WidgetEditor"));
    createEditModeAction(m_actionGroupEditMode, m_context, am, medit,
                         QLatin1String("Edit widgets"), m_toolActionIds.back(),
                         EditModeWidgetEditor, QLatin1String("widgettool.png"), tr("F3"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.SignalsSlotsEditor"));
    createEditModeAction(m_actionGroupEditMode,  m_context, am, medit,
                         QLatin1String("Edit signals/slots"), m_toolActionIds.back(),
                         EditModeSignalsSlotEditor, QLatin1String("signalslottool.png"), tr("F4"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.BuddyEditor"));
    createEditModeAction(m_actionGroupEditMode,  m_context, am, medit,
                         QLatin1String("Edit buddies"), m_toolActionIds.back(),
                         EditModeBuddyEditor, QLatin1String("buddytool.png"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.TabOrderEditor"));
    createEditModeAction(m_actionGroupEditMode,  m_context, am, medit,
                         QLatin1String("Edit tab order"),  m_toolActionIds.back(),
                         EditModeTabOrderEditor, QLatin1String("tabordertool.png"));

    //tool actions
    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutHorizontally"));
    addToolAction(m_fwm->actionHorizontalLayout(), am, m_context,
                  m_toolActionIds.back(), mformtools, tr("Ctrl+H"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutVertically"));
    addToolAction(m_fwm->actionVerticalLayout(), am, m_context,
                  m_toolActionIds.back(),  mformtools, tr("Ctrl+L"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.SplitHorizontal"));
    addToolAction(m_fwm->actionSplitHorizontal(), am, m_context,
                  m_toolActionIds.back(), mformtools);

    m_toolActionIds.push_back(QLatin1String("FormEditor.SplitVertical"));
    addToolAction(m_fwm->actionSplitVertical(), am, m_context,
                  m_toolActionIds.back(), mformtools);

    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutForm"));
    addToolAction(m_fwm->actionFormLayout(), am, m_context,
                  m_toolActionIds.back(),  mformtools);

    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutGrid"));
    addToolAction(m_fwm->actionGridLayout(), am, m_context,
                  m_toolActionIds.back(),  mformtools, tr("Ctrl+G"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutBreak"));
    addToolAction(m_fwm->actionBreakLayout(), am, m_context,
                  m_toolActionIds.back(), mformtools);

    m_toolActionIds.push_back(QLatin1String("FormEditor.LayoutAdjustSize"));
    addToolAction(m_fwm->actionAdjustSize(), am, m_context,
                  m_toolActionIds.back(),  mformtools, tr("Ctrl+J"));

    m_toolActionIds.push_back(QLatin1String("FormEditor.SimplifyLayout"));
    addToolAction(m_fwm->actionSimplifyLayout(), am, m_context,
                  m_toolActionIds.back(),  mformtools);

    createSeparator(this, am, m_context, mformtools, QLatin1String("FormEditor.Menu.Tools.Separator1"));

    addToolAction(m_fwm->actionLower(), am, m_context,
                  QLatin1String("FormEditor.Lower"), mformtools);

    addToolAction(m_fwm->actionRaise(), am, m_context,
                  QLatin1String("FormEditor.Raise"), mformtools);

    // Commands that do not go into the editor toolbar
    createSeparator(this, am, m_context, mformtools, QLatin1String("FormEditor.Menu.Tools.Separator2"));

    m_actionPreview = m_fwm->actionDefaultPreview();
hjk's avatar
hjk committed
414
    QTC_ASSERT(m_actionPreview, return);
con's avatar
con committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    addToolAction(m_actionPreview,  am,  m_context,
                   QLatin1String("FormEditor.Preview"), mformtools, tr("Ctrl+Alt+R"));

    // Preview in style...
    m_actionGroupPreviewInStyle = m_fwm->actionGroupPreviewInStyle();
    mformtools->addMenu(createPreviewStyleMenu(am, m_actionGroupPreviewInStyle));

    // Disabled since we cannot reliably locate uic.
    if (wantCodeGenerationAction) {
        m_actionGenerateCode = new QAction(tr("View &code"), this);
        addToolAction(m_actionGenerateCode, am, m_context,
                      QLatin1String("FormEditor.ViewCode"), mformtools);
        connect(m_actionGenerateCode, SIGNAL(triggered()), this, SLOT(generateCode()));
    }
    // Form settings
    createSeparator(this, am, m_context,  medit, QLatin1String("FormEditor.Edit.Separator2"), Core::Constants::G_EDIT_OTHER);

#if QT_VERSION >= 0x040500
    createSeparator(this, am, m_context, mformtools, QLatin1String("FormEditor.Menu.Tools.Separator3"));
    QAction *actionFormSettings = m_fwm->actionShowFormWindowSettingsDialog();
    addToolAction(actionFormSettings, am, m_context, QLatin1String("FormEditor.FormSettings"), mformtools);
#endif
    // FWM
    connect(m_fwm, SIGNAL(activeFormWindowChanged(QDesignerFormWindowInterface *)), this, SLOT(activeFormWindowChanged(QDesignerFormWindowInterface *)));
}


QToolBar *FormEditorW::createEditorToolBar() const
{
    QToolBar *rc = new QToolBar;
    rc->addSeparator();
446
    Core::ActionManager *am = m_core->actionManager();
con's avatar
con committed
447 448
    const QStringList::const_iterator cend = m_toolActionIds.constEnd();
    for (QStringList::const_iterator it = m_toolActionIds.constBegin(); it != cend; ++it) {
hjk's avatar
hjk committed
449 450
        Core::ICommand *cmd = am->command(*it);
        QTC_ASSERT(cmd, continue);
con's avatar
con committed
451 452 453 454 455 456 457 458 459
        QAction *action = cmd->action();
        if (!action->icon().isNull()) // Simplify grid has no action yet
            rc->addAction(action);
    }
    int size = rc->style()->pixelMetric(QStyle::PM_SmallIconSize);
    rc->setIconSize(QSize(size, size));
    return rc;
}

460
Core::IActionContainer *FormEditorW::createPreviewStyleMenu(Core::ActionManager *am,
con's avatar
con committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
                                                            QActionGroup *actionGroup)
{
    const QString menuId = QLatin1String(M_FORMEDITOR_PREVIEW);
    Core::IActionContainer *menuPreviewStyle = am->createMenu(menuId);
    menuPreviewStyle->menu()->setTitle(tr("Preview in"));

    // The preview menu is a list of invisible actions for the embedded design
    // device profiles (integer data) followed by a separator and the styles
    // (string data). Make device profiles update their text and hide them
    // in the configuration dialog.
    const QList<QAction*> actions = actionGroup->actions();

    const QString deviceProfilePrefix = QLatin1String("DeviceProfile");
    const QChar dot = QLatin1Char('.');

hjk's avatar
hjk committed
476
    foreach (QAction* a, actions) {
con's avatar
con committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        QString name = menuId;
        name += dot;
        const QVariant data = a->data();
        const bool isDeviceProfile = data.type() == QVariant::Int;
        if (isDeviceProfile) {
            name += deviceProfilePrefix;
            name += dot;
        }
        name += data.toString();
        Core::ICommand *command = am->registerAction(a, name, m_context);
        if (isDeviceProfile) {
            command->setAttribute(Core::ICommand::CA_UpdateText);
            command->setAttribute(Core::ICommand::CA_NonConfigureable);
        }
        menuPreviewStyle->addAction(command);
    }
    return menuPreviewStyle;
}

void FormEditorW::saveSettings(QSettings *s)
{
    s->beginGroup(settingsGroup);
    s->setValue(QLatin1String(editorWidgetStateKeyC), EditorWidget::state().toVariant());
    s->endGroup();
}

void FormEditorW::restoreSettings(const QSettings *s)
{
    QString key = QLatin1String(settingsGroup) + QLatin1Char('/')
                                + QLatin1String(editorWidgetStateKeyC);
    const QVariant ev = s->value(key);
    if (ev.type() != QVariant::Invalid) {
        EditorWidgetState st;
        if (st.fromVariant(ev))
            EditorWidget::setState(st);
    }
}

void FormEditorW::generateCode()
{
    const FormWindowEditor *fww = activeFormWindow();
    if (!fww)
        return;

    bool ok = false;
    QString errorMessage;

    do {
        QByteArray header;
        if (!fww->generateCode(header, errorMessage))
            break;

        QString tempPattern = QDir::tempPath();
        if (!tempPattern.endsWith(QDir::separator())) // platform-dependant
            tempPattern += QDir::separator();
        tempPattern += QLatin1String("ui_headerXXXXXX.h");
        QTemporaryFile headerFile(tempPattern);
        headerFile.setAutoRemove (false);
        if (!headerFile.open() || !headerFile.write(header)) {
            errorMessage = tr("Unable to write to a temporary file.");
            break;
        }
        const QString headerFileName = headerFile.fileName();
        headerFile.close();
        Core::IEditor *eif = m_core->editorManager()->openEditor(headerFileName);
        if (!eif) {
            errorMessage = tr("Unable open %1.").arg(headerFileName);
            break;
        }
        ok = true;
    } while (false);
    if (!ok)
        critical(errorMessage);
}

void FormEditorW::critical(const QString &errorMessage)
{
    QMessageBox::critical(m_core->mainWindow(), tr("Designer"),  errorMessage);
}

FormWindowEditor *FormEditorW::createFormWindowEditor(QWidget* parentWidget)
{
    m_fwm->closeAllPreviews();
    QDesignerFormWindowInterface *form = m_fwm->createFormWindow(0);
    connect(form, SIGNAL(toolChanged(int)), this, SLOT(toolChanged(int)));
    qdesigner_internal::FormWindowBase::setupDefaultAction(form);
    FormWindowEditor *fww = new FormWindowEditor(m_core, m_context, form, parentWidget);
    // Store a pointer to all form windows so we can unselect all other formwindows except the active one.
    m_formWindows.append(fww);
    connect(fww, SIGNAL(destroyed()), this, SLOT(editorDestroyed()));
    return fww;
}

void FormEditorW::editorDestroyed()
{
    QObject *source = sender();

    if (debugFormEditor)
        qDebug() << "FormEditorW::editorDestroyed()" << source;

    for (EditorList::iterator it = m_formWindows.begin(); it != m_formWindows.end(); ) {
        if (*it == source) {
            it = m_formWindows.erase(it);
            break;
        } else {
            ++it;
        }
    }
}

void FormEditorW::currentEditorChanged(Core::IEditor *editor)
{
    if (debugFormEditor)
        qDebug() << "FormEditorW::currentEditorChanged" << editor << " of " << m_fwm->formWindowCount();

    // Deactivate Designer if a non-form is being edited
    if (editor && !qstrcmp(editor->kind(), Constants::C_FORMWINDOW)) {
        FormWindowEditor *fw = qobject_cast<FormWindowEditor *>(editor);
hjk's avatar
hjk committed
595
        QTC_ASSERT(fw, return);
con's avatar
con committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 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 636 637 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 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
        fw->activate();
        m_fwm->setActiveFormWindow(fw->formWindow());
    } else {
        m_fwm->setActiveFormWindow(0);
    }
}

void FormEditorW::activeFormWindowChanged(QDesignerFormWindowInterface *afw)
{
    if (debugFormEditor)
        qDebug() << "FormEditorW::activeFormWindowChanged" << afw << " of " << m_fwm->formWindowCount() << m_formWindows;

    m_fwm->closeAllPreviews();

    bool foundFormWindow = false;
    // Display form selection handles only on active window
    EditorList::const_iterator cend = m_formWindows.constEnd();
    for (EditorList::const_iterator it = m_formWindows.constBegin(); it != cend ; ++it) {
        FormWindowEditor *fwe = *it;
        const bool active = fwe->formWindow() == afw;
        if (active)
            foundFormWindow = true;
        fwe->updateFormWindowSelectionHandles(active);
    }

    m_actionPreview->setEnabled(foundFormWindow);
    if (m_actionGenerateCode)
        m_actionGenerateCode->setEnabled(foundFormWindow);
    m_actionGroupPreviewInStyle->setEnabled(foundFormWindow);
}

FormWindowEditor *FormEditorW::activeFormWindow()
{
    QDesignerFormWindowInterface *afw = m_fwm->activeFormWindow();
    for (int i = 0; i < m_formWindows.count(); ++i) {
        if (FormWindowEditor *fw = m_formWindows[i]) {
            QDesignerFormWindowInterface *fwd = fw->formWindow();
            if (fwd == afw) {
                return fw;
            }
        }
    }
    return 0;
}

void FormEditorW::activateEditMode(int id)
{
    if (const int count = m_fwm->formWindowCount())
        for (int i = 0; i <  count; i++)
             m_fwm->formWindow(i)->setCurrentTool(id);
}

void FormEditorW::activateEditMode(QAction* a)
{
    activateEditMode(a->data().toInt());
}

void FormEditorW::toolChanged(int t)
{
    typedef QList<QAction *> ActionList;
    if (const QAction *currentAction = m_actionGroupEditMode->checkedAction())
        if (currentAction->data().toInt() == t)
            return;
    const ActionList actions = m_actionGroupEditMode->actions();
    const ActionList::const_iterator cend = actions.constEnd();
    for (ActionList::const_iterator it = actions.constBegin(); it != cend; ++it)
        if ( (*it)->data().toInt() == t) {
            (*it)->setChecked(true);
            break;
        }
}

void FormEditorW::print()
{
    // Printing code courtesy of designer_actions.cpp
    QDesignerFormWindowInterface *fw = m_fwm->activeFormWindow();
    if (!fw)
        return;

    const bool oldFullPage =  m_core->printer()->fullPage();
    const QPrinter::Orientation oldOrientation =  m_core->printer()->orientation ();
    m_core->printer()->setFullPage(false);
    do {

        // Grab the image to be able to a suggest suitable orientation
        QString errorMessage;
        const QPixmap pixmap = m_fwm->createPreviewPixmap(&errorMessage);
        if (pixmap.isNull()) {
            critical(tr("The image could not be create: %1").arg(errorMessage));
            break;
        }

        const QSizeF pixmapSize = pixmap.size();
        m_core->printer()->setOrientation( pixmapSize.width() > pixmapSize.height() ?  QPrinter::Landscape :  QPrinter::Portrait);

        // Printer parameters
        QPrintDialog dialog(m_core->printer(), fw);
        if (!dialog.exec())
           break;

        const QCursor oldCursor = m_core->mainWindow()->cursor();
        m_core->mainWindow()->setCursor(Qt::WaitCursor);
        // Estimate of required scaling to make form look the same on screen and printer.
        const double suggestedScaling = static_cast<double>(m_core->printer()->physicalDpiX()) /  static_cast<double>(fw->physicalDpiX());

        QPainter painter(m_core->printer());
        painter.setRenderHint(QPainter::SmoothPixmapTransform);

        // Clamp to page
        const QRectF page =  painter.viewport();
        const double maxScaling = qMin(page.size().width() / pixmapSize.width(), page.size().height() / pixmapSize.height());
        const double scaling = qMin(suggestedScaling, maxScaling);

        const double xOffset = page.left() + qMax(0.0, (page.size().width()  - scaling * pixmapSize.width())  / 2.0);
        const double yOffset = page.top()  + qMax(0.0, (page.size().height() - scaling * pixmapSize.height()) / 2.0);

        // Draw.
        painter.translate(xOffset, yOffset);
        painter.scale(scaling, scaling);
        painter.drawPixmap(0, 0, pixmap);
        m_core->mainWindow()->setCursor(oldCursor);

con's avatar
con committed
718
//        m_core->statusBar()->showMessage(tr("Printed %1...").arg(QFileInfo(fw->fileName()).fileName()));
con's avatar
con committed
719 720 721 722
    } while (false);
    m_core->printer()->setFullPage(oldFullPage);
    m_core->printer()->setOrientation(oldOrientation);
}