Пример #1
0
bool TxtBox::keyboardEvent (int key, int /* scancode */, int action, int modifiers)
{
   if (mEditable && focused())
   {
      if (action == PRESS || action == REPEAT)
      {
         if (key == KEY_LEFT)
         {
            if (modifiers == SHIFT_DOWN)
            {
               if (mSelectionPos == -1)
                  mSelectionPos = mCursorPos;
            }
            else
               mSelectionPos = -1;
            if (mCursorPos > 0)
               mCursorPos--;
         }
         else
            if (key == KEY_RIGHT)
            {
               if (modifiers == SHIFT_DOWN)
               {
                  if (mSelectionPos == -1)
                     mSelectionPos = mCursorPos;
               }
               else
                  mSelectionPos = -1;
               if (mCursorPos < (int) mValueTemp.length())
                  mCursorPos++;
            }
            else
               if (key == KEY_HOME)
               {
                  if (modifiers == SHIFT_DOWN)
                  {
                     if (mSelectionPos == -1)
                        mSelectionPos = mCursorPos;
                  }
                  else
                     mSelectionPos = -1;
                  mCursorPos = 0;
               }
               else
                  if (key == KEY_END)
                  {
                     if (modifiers == SHIFT_DOWN)
                     {
                        if (mSelectionPos == -1)
                           mSelectionPos = mCursorPos;
                     }
                     else
                        mSelectionPos = -1;
                     mCursorPos = (int) mValueTemp.size();
                  }
                  else
                     if (key == KEY_BACKSPACE)
                     {
                        if (!deleteSelection())
                        {
                           if (mCursorPos > 0)
                           {
                              mValueTemp.erase (mValueTemp.begin() + mCursorPos - 1);
                              mCursorPos--;
                           }
                        }
                     }
                     else
                        if (key == KEY_DELETE)
                        {
                           if (!deleteSelection())
                           {
                              if (mCursorPos < (int) mValueTemp.length())
                                 mValueTemp.erase (mValueTemp.begin() + mCursorPos);
                           }
                        }
                        else
                           if (key == KEY_RETURN)
                           {
                              if (!mCommitted)
                                 focusEvent (false);
                           }
                           else
                              if (key == KEY_a && modifiers == SYSTEM_COMMAND_MOD)
                              {
                                 mCursorPos = (int) mValueTemp.length();
                                 mSelectionPos = 0;
                              }
                              else
                                 if (key == KEY_x && modifiers == SYSTEM_COMMAND_MOD)
                                 {
                                    copySelection();
                                    deleteSelection();
                                 }
                                 else
                                    if (key == KEY_c && modifiers == SYSTEM_COMMAND_MOD)
                                       copySelection();
                                    else
                                       if (key == KEY_v && modifiers == SYSTEM_COMMAND_MOD)
                                       {
                                          deleteSelection();
                                          pasteFromClipboard();
                                       }
         mValidFormat =
            (mValueTemp == "") || checkFormat (mValueTemp, mFormat);
      }
      return true;
   }
   return false;
}
Пример #2
0
void KoToolBase::cut()
{
    copy();
    deleteSelection();
}
Пример #3
0
void InsertTextCommand::doApply()
{
    ASSERT(m_text.find('\n') == notFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(m_text, m_selectInsertedText))
            return;
        deleteSelection(false, true, true, false);
        // deleteSelection eventually makes a new endingSelection out of a Position. If that Position doesn't have
        // a renderer (e.g. it is on a <frameset> in the DOM), the VisibleSelection cannot be canonicalized to 
        // anything other than NoSelection. The rest of this function requires a real endingSelection, so bail out.
        if (endingSelection().isNone())
            return;
    }

    Position startPosition(endingSelection().start());
    
    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content 
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }
    
    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();
    
    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
    if (!startPosition.anchorNode()->inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();
    
    startPosition = positionAvoidingSpecialElementBoundary(startPosition);
    
    Position endPosition;
    
    if (m_text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
    } else {
        // Make sure the document is set up to receive m_text
        startPosition = positionInsideTextNode(startPosition);
        ASSERT(startPosition.anchorType() == Position::PositionIsOffsetInAnchor);
        ASSERT(startPosition.containerNode());
        ASSERT(startPosition.containerNode()->isTextNode());
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        RefPtr<Text> textNode = startPosition.containerText();
        const unsigned offset = startPosition.offsetInContainerNode();

        insertTextIntoNode(textNode, offset, m_text);
        endPosition = Position(textNode, offset + m_text.length());

        if (m_rebalanceType == RebalanceLeadingAndTrailingWhitespaces) {
            // The insertion may require adjusting adjacent whitespace, if it is present.
            rebalanceWhitespaceAt(endPosition);
            // Rebalancing on both sides isn't necessary if we've inserted only spaces.
            if (!shouldRebalanceLeadingWhitespaceFor(m_text))
                rebalanceWhitespaceAt(startPosition);
        } else {
            ASSERT(m_rebalanceType == RebalanceAllWhitespaces);
            if (canRebalance(startPosition) && canRebalance(endPosition))
                rebalanceWhitespaceOnTextSubstring(textNode, startPosition.offsetInContainerNode(), endPosition.offsetInContainerNode());
        }
    }

    // We could have inserted a part of composed character sequence,
    // so we are basically treating ending selection as a range to avoid validation.
    // <http://bugs.webkit.org/show_bug.cgi?id=15781>
    VisibleSelection forcedEndingSelection;
    forcedEndingSelection.setWithoutValidation(startPosition, endPosition);
    forcedEndingSelection.setIsDirectional(endingSelection().isDirectional());
    setEndingSelection(forcedEndingSelection);

    // Handle the case where there is a typing style.
    if (RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle()) {
        typingStyle->prepareToApplyAt(endPosition, EditingStyle::PreserveWritingDirection);
        if (!typingStyle->isEmpty())
            applyStyle(typingStyle.get());
    }

    if (!m_selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity(), endingSelection().isDirectional()));
}
Пример #4
0
PlotWindow::PlotWindow(
	boost::shared_ptr<GoogleMapWindow> google_map, 
	boost::shared_ptr<DataStatisticsWindow> stats_view)
{
	// Create the plot
	_plot = new QwtPlot();

	// Create HR zone markers
	const QColor hr_zone_colours[5] = 
		{HR_ZONE1_COLOUR, HR_ZONE2_COLOUR, HR_ZONE3_COLOUR, HR_ZONE4_COLOUR, HR_ZONE5_COLOUR};
	_hr_zone_markers.resize(5);
	for (unsigned int i=0; i < _hr_zone_markers.size(); ++i)
	{
		_hr_zone_markers[i] = new HRZoneItem;

		_hr_zone_markers[i]->attach(_plot);
		_hr_zone_markers[i]->hide();
		
		// Set the fill colour
		QColor c(hr_zone_colours[i]);
		c.setAlpha(40);
		_hr_zone_markers[i]->setColour(c);
	}

	// Create lap markers
	_lap_markers.resize(0);
	
	// Connect this window to the google map
	connect(this, SIGNAL(setMarkerPosition(int)), google_map.get(), SLOT(setMarkerPosition(int)));
	connect(this, SIGNAL(beginSelection(int)), google_map.get(), SLOT(beginSelection(int)));
	connect(this, SIGNAL(endSelection(int)), google_map.get(), SLOT(endSelection(int)));
	connect(this, SIGNAL(zoomSelection(int,int)), google_map.get(), SLOT(zoomSelection(int,int)));
	connect(this, SIGNAL(deleteSelection()), google_map.get(), SLOT(deleteSelection()));
	connect(this, SIGNAL(panSelection(int)), google_map.get(), SLOT(moveSelection(int)));
	connect(this, SIGNAL(panAndHoldSelection(int)), google_map.get(), SLOT(moveAndHoldSelection(int)));
	connect(this, SIGNAL(updateDataView()), google_map.get(), SLOT(definePathColour()));

	// Connect this window to the statistical viewer
	connect(this, SIGNAL(zoomSelection(int,int)), stats_view.get(), SLOT(displaySelectedRideStats(int,int)));
	connect(this, SIGNAL(panAndHoldSelection(int)), stats_view.get(), SLOT(moveSelection(int)));
	connect(this, SIGNAL(deleteSelection()), stats_view.get(), SLOT(deleteSelection()));
	connect(this, SIGNAL(updateDataView()), stats_view.get(), SLOT(displayCompleteRideStats()));
	
	// Setup the axis
	_plot->enableAxis(QwtPlot::yRight,true);
	_plot->setAxisAutoScale(QwtPlot::xBottom,true);

	QwtText axis_text;
	QFont font = _plot->axisFont(QwtPlot::xBottom);
	font.setPointSize(8);
	axis_text.setFont(font);

	axis_text.setText("HR (bpm) Speed (km/h) Cadence (rpm)\nPower (W) Temp (C)");
	_plot->setAxisTitle(QwtPlot::yLeft,axis_text);

	axis_text.setText("Elevation (m)");
	_plot->setAxisTitle(QwtPlot::yRight,axis_text);

	axis_text.setText("Distance (km)");
	_plot->setAxisTitle(QwtPlot::xBottom,axis_text);

	// Define the curves to plot
	QColor c;

	_curve_hr = new QwtPlotCurve("Heart Rate");
	c = HR_COLOUR;
	_curve_hr->setPen(c);
	_curve_hr->setYAxis(QwtPlot::yLeft);

	_curve_cadence = new QwtPlotCurve("Cadence");
	c = CADENCE_COLOUR;
	_curve_cadence->setPen(c);
	_curve_cadence->setYAxis(QwtPlot::yLeft);

	_curve_speed = new QwtPlotCurve("Speed");
	c = SPEED_COLOUR;
	_curve_speed->setPen(c);
	_curve_speed->setYAxis(QwtPlot::yLeft);

	_curve_power = new QwtPlotCurve("Power");
	c = POWER_COLOUR;
	_curve_power->setPen(c);
	_curve_power->setYAxis(QwtPlot::yLeft);

	_curve_temp = new QwtPlotCurve("Temp");
	c = TEMP_COLOUR;
	_curve_temp->setPen(c);
	_curve_temp->setYAxis(QwtPlot::yLeft);

	_curve_alt = new QwtPlotCurve("Elevation");
	_curve_alt->setRenderHint(QwtPlotItem::RenderAntialiased);
	c = ALT_COLOUR;
	_curve_alt->setPen(c);
    _curve_alt->setBrush(c);
	_curve_alt->setYAxis(QwtPlot::yRight);
	_curve_alt->setBaseline(-300.0); // ensure display is correct even when -ve altitude

	_curve_alt->attach(_plot);
	_curve_cadence->attach(_plot);
	_curve_speed->attach(_plot);
	_curve_hr->attach(_plot);
	_curve_power->attach(_plot);
	_curve_temp->attach(_plot);

	// Checkboxes for graph plots
	_hr_cb.reset(new QCheckBox("Heart Rate"));
	_speed_cb.reset(new QCheckBox("Speed"));
	_alt_cb.reset(new QCheckBox("Elevation"));
	_cadence_cb.reset(new QCheckBox("Cadence"));
	_power_cb.reset(new QCheckBox("Power"));
	_temp_cb.reset(new QCheckBox("Temp"));
	_laps_cb = new QCheckBox("Laps");
	_hr_zones_cb = new QCheckBox("HR Zones");
	_hr_cb->setChecked(true);
	_speed_cb->setChecked(true);
	_alt_cb->setChecked(true);
	_cadence_cb->setChecked(true);
	_power_cb->setChecked(false);
	_temp_cb->setChecked(false);
	_laps_cb->setChecked(true);
	_hr_zones_cb->setChecked(false);

	QPalette plt;
	plt.setColor(QPalette::WindowText, HR_COLOUR);
	_hr_cb->setPalette(plt);
	plt.setColor(QPalette::WindowText, SPEED_COLOUR);
	_speed_cb->setPalette(plt);
	plt.setColor(QPalette::WindowText, ALT_COLOUR);
	_alt_cb->setPalette(plt);
	plt.setColor(QPalette::WindowText, CADENCE_COLOUR);
	_cadence_cb->setPalette(plt);
	plt.setColor(QPalette::WindowText, POWER_COLOUR);
	_power_cb->setPalette(plt);
	plt.setColor(QPalette::WindowText, TEMP_COLOUR);
	_temp_cb->setPalette(plt);

	connect(_hr_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_speed_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_alt_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_cadence_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_power_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_temp_cb.get(), SIGNAL(stateChanged(int)),this,SLOT(curveSelectionChanged()));
	connect(_laps_cb, SIGNAL(stateChanged(int)),this,SLOT(lapSelectionChanged()));
	connect(_hr_zones_cb, SIGNAL(stateChanged(int)),this,SLOT(hrZoneSelectionChanged()));

	// Plot picker for numerical display
	_plot_picker1 = 
		new QwtCustomPlotPicker(
		QwtPlot::xBottom, QwtPlot::yLeft, 
		_data_log, 
		_plot->canvas(), 
		_hr_cb, _speed_cb, _alt_cb, _cadence_cb, _power_cb, _temp_cb);
		
	_plot_picker1->setRubberBandPen(QColor(Qt::white));
    _plot_picker1->setTrackerPen(QColor(Qt::black));
	_plot_picker1->setStateMachine(new QwtPickerTrackerMachine());
	connect(_plot_picker1, SIGNAL(moved(const QPointF&)), this, SLOT(setMarkerPosition(const QPointF&)));
	
	// Plot picker for drawing user selection
	_plot_picker2 = 
		new QwtPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft, QwtPlotPicker::NoRubberBand, QwtPicker::AlwaysOff, _plot->canvas());
	_plot_picker2->setStateMachine(new QwtPickerDragPointMachine());
	connect(_plot_picker2, SIGNAL(appended(const QPointF&)), this, SLOT(beginSelection(const QPointF&)));
	connect(_plot_picker2, SIGNAL(moved(const QPointF&)), this, SLOT(endSelection(const QPointF&)));

	// Plot zoomer
	_plot_zoomer = new QwtCustomPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft, _plot->canvas());
	_plot_zoomer->setRubberBand(QwtPicker::UserRubberBand);
    _plot_zoomer->setRubberBandPen(QColor(Qt::white));
    _plot_zoomer->setTrackerMode(QwtPicker::AlwaysOff);
    _plot_zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier);
    _plot_zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton);
	connect(_plot_zoomer, SIGNAL(zoomed(const QRectF&)), this, SLOT(zoomSelection(const QRectF&)));

	// Plot panner
	_plot_panner = new QwtPlotPanner(_plot->canvas());
	_plot_panner->setMouseButton(Qt::MidButton);
	connect(_plot_panner, SIGNAL(moved(int, int)), this, SLOT(panSelection(int, int)));
	connect(_plot_panner, SIGNAL(panned(int, int)), this, SLOT(panAndHoldSelection(int, int)));

	// Selection for x-axis measurement
	_x_axis_measurement = new QComboBox;
	_x_axis_measurement->insertItem(0, "x-axis = time");
	_x_axis_measurement->insertItem(1, "x-axis = distance");
	_x_axis_measurement->setCurrentIndex(1);
	_plot->setAxisScaleDraw(QwtPlot::xBottom, new XAxisScaleDraw(tr("dist")));
	connect(_x_axis_measurement,SIGNAL(currentIndexChanged(int)), this, SLOT(xAxisUnitsChanged(int)));
	connect(_x_axis_measurement,SIGNAL(currentIndexChanged(int)), _plot_picker1, SLOT(xAxisUnitsChanged(int)));

	// Selection for signal smoothing
	_smoothing_selection = new QSpinBox;
	_smoothing_selection->setRange(1,50);
	_smoothing_selection->setPrefix("Smoothing: ");
	_smoothing_selection->setValue(5); // default value
	connect(_smoothing_selection, SIGNAL(valueChanged(int)),this,SLOT(signalSmoothingChanged()));

	// Layout the GUI
	QWidget* plot_options_widget = new QWidget;
	QVBoxLayout* vlayout1 = new QVBoxLayout(plot_options_widget);
	vlayout1->addWidget(_hr_cb.get());
	vlayout1->addWidget(_speed_cb.get());
	vlayout1->addWidget(_alt_cb.get());
	vlayout1->addWidget(_cadence_cb.get());
	vlayout1->addWidget(_power_cb.get());
	vlayout1->addWidget(_temp_cb.get());
	vlayout1->addWidget(_x_axis_measurement);
	vlayout1->addWidget(_smoothing_selection);
	vlayout1->addWidget(_laps_cb);
	vlayout1->addWidget(_hr_zones_cb);
	vlayout1->addStretch();

	QHBoxLayout* hlayout2 = new QHBoxLayout(this);
	hlayout2->addWidget(_plot);
	hlayout2->addWidget(plot_options_widget);
	
	resize(700,270);

	// Disable all controls until ride data is loaded
	setEnabled(false);
}
Пример #5
0
MainWindow::MainWindow(ConfigHandler *aConfig, Database * aDb)
    : QMainWindow(0), config(aConfig), ui(new Ui::MainWindow), db(aDb)
{
	qDebug() << "Main Window Construct";
    // Aufsetzen der GUI Grundumgebung + Logger
    ui->setupUi(this);
    resize(config->getAppSize());
    move(config->getAppPosition());


    this->setWindowTitle("BirdCensus");

    // Der QGIS Umgebung
    qgsPvrRegistry = QgsProviderRegistry::instance();
    qgsLyrRegistry = QgsMapLayerRegistry::instance();
    qgsCheckProviders();

    guiInitAdditionals();

//	QPalette dark_palette = ui->tbwObjects->palette();
//	ui->tbwObjects->viewport()->setBackgroundRole(QPalette::AlternateBase);
////	dark_palette.setColor(QPalette::Window, Qt::lightGray);
//	dark_palette.setColor(QPalette::AlternateBase, Qt::gray);
//	ui->tbwObjects->setPalette(dark_palette);

	initSessionFrame();

    object_table_model = db->getObjectView();
    ui->tbwObjects->setModel(object_table_model);
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("ux"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("uy"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("lx"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("ly"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("cam"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("img"));
    ui->tbwObjects->hideColumn(object_table_model->fieldIndex("session"));
//    ui->tbwObjects->setBackgroundRole(QPalette::Base);
//    ui->tbwObjects->setAutoFillBackground( true );
    ui->tbwObjects->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);


    if (config->getAdmin()) {
        ui->option_admin->setEnabled(false);
        ui->option_admin->setIcon(QIcon::fromTheme("object-unlocked"));
    }

/*
 * TODO:
 * werden die beiden tableview selectionModels wirklich gebraucht?
 */

    objSelector = ui->tbwObjects->selectionModel();

    connect( ui->btnMapSelect, SIGNAL(clicked()), this, SLOT(clearSelection()));

    connect( ui->btnMapRmObj, SIGNAL(clicked()), this, SLOT(deleteSelection()));

    connect( objSelector, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(objUpdateSelection(QModelIndex,QModelIndex)));

    connect( ui->cmbSession, SIGNAL(currentIndexChanged(int)), this, SLOT(handleSessionSelection()));

    connect( ui->chbHideMarker, SIGNAL(clicked(bool)), mapCanvas, SLOT(hideMarker(bool)));

    connect( ui->option_admin, SIGNAL(clicked()), this, SLOT(handleAdminPass()));

    connect( ui->chbNotReady, SIGNAL(stateChanged(int)), this, SLOT(handleMissingCheckBox(int)));

    connect( ui->image_table->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(handleHeaderFilter(int)));

    connect( ui->option_location, SIGNAL(clicked()), this, SLOT(handleLocationSelection()));
}
void InsertParagraphSeparatorCommand::doApply()
{
    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    Position insertionPosition = endingSelection().start();

    EAffinity affinity = endingSelection().affinity();

    // Delete the current selection.
    if (endingSelection().isRange()) {
        calculateStyleBeforeInsertion(insertionPosition);
        deleteSelection(false, true);
        insertionPosition = endingSelection().start();
        affinity = endingSelection().affinity();
    }

    // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enclosingBlock.
    RefPtr<Element> startBlock = enclosingBlock(insertionPosition.parentAnchoredEquivalent().containerNode());
    Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
    if (!startBlock
        || !startBlock->nonShadowBoundaryParentNode()
        // FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
        || (!canonicalPos.isNull() && isRenderedTableElement(canonicalPos.deprecatedNode()))) {
        applyCommandToComposite(InsertLineBreakCommand::create(document()));
        return;
    }

    // Use the leftmost candidate.
    insertionPosition = insertionPosition.upstream();
    if (!insertionPosition.isCandidate())
        insertionPosition = insertionPosition.downstream();

    // Adjust the insertion position after the delete
    insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition);
    VisiblePosition visiblePos(insertionPosition, affinity);
    calculateStyleBeforeInsertion(insertionPosition);

    //---------------------------------------------------------------------
    // Handle special case of typing return on an empty list item
    if (breakOutOfEmptyListItem())
        return;

    //---------------------------------------------------------------------
    // Prepare for more general cases.

    bool isFirstInBlock = isStartOfBlock(visiblePos);
    bool isLastInBlock = isEndOfBlock(visiblePos);
    bool nestNewBlock = false;

    // Create block to be inserted.
    RefPtr<Element> blockToInsert = nullptr;
    if (startBlock->isRootEditableElement()) {
        blockToInsert = createDefaultParagraphElement(document());
        nestNewBlock = true;
    } else if (shouldUseDefaultParagraphElement(startBlock.get())) {
        blockToInsert = createDefaultParagraphElement(document());
    } else {
        blockToInsert = startBlock->cloneElementWithoutChildren();
    }

    //---------------------------------------------------------------------
    // Handle case when position is in the last visible position in its block,
    // including when the block is empty.
    if (isLastInBlock) {
        if (nestNewBlock) {
            if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
                // The block is empty.  Create an empty block to
                // represent the paragraph that we're leaving.
                RefPtr<HTMLElement> extraBlock = createDefaultParagraphElement(document());
                appendNode(extraBlock, startBlock);
            }
            appendNode(blockToInsert, startBlock);
        } else {
            // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists). However,
            // for div nodes, this can result in nested div tags that are hard to break out of.
            Element* siblingElement = startBlock.get();
            insertNodeAfter(blockToInsert, siblingElement);
        }

        // Recreate the same structure in the new paragraph.

        Vector<RefPtr<Element> > ancestors;
        getAncestorsInsideBlock(positionOutsideTabSpan(insertionPosition).deprecatedNode(), startBlock.get(), ancestors);
        RefPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert);

        setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), DOWNSTREAM, endingSelection().isDirectional()));
        return;
    }


    //---------------------------------------------------------------------
    // Handle case when position is in the first visible position in its block, and
    // similar case where previous position is in another, presumeably nested, block.
    if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
        Node* refNode = 0;
        insertionPosition = positionOutsideTabSpan(insertionPosition);

        if (isFirstInBlock && !nestNewBlock) {
            refNode = startBlock.get();
        } else if (isFirstInBlock && nestNewBlock) {
            // startBlock should always have children, otherwise isLastInBlock would be true and it's handled above.
            ASSERT(startBlock->hasChildren());
            refNode = startBlock->firstChild();
        }
        else if (insertionPosition.deprecatedNode() == startBlock && nestNewBlock) {
            refNode = NodeTraversal::childAt(*startBlock, insertionPosition.deprecatedEditingOffset());
            ASSERT(refNode); // must be true or we'd be in the end of block case
        } else
            refNode = insertionPosition.deprecatedNode();

        // find ending selection position easily before inserting the paragraph
        insertionPosition = insertionPosition.downstream();

        if (refNode)
            insertNodeBefore(blockToInsert, refNode);

        // Recreate the same structure in the new paragraph.

        Vector<RefPtr<Element> > ancestors;
        getAncestorsInsideBlock(positionAvoidingSpecialElementBoundary(positionOutsideTabSpan(insertionPosition)).deprecatedNode(), startBlock.get(), ancestors);

        // In this case, we need to set the new ending selection.
        setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endingSelection().isDirectional()));
        return;
    }

    //---------------------------------------------------------------------
    // Handle the (more complicated) general case,

    // Move downstream. Typing style code will take care of carrying along the
    // style of the upstream position.
    insertionPosition = insertionPosition.downstream();

    // At this point, the insertionPosition's node could be a container, and we want to make sure we include
    // all of the correct nodes when building the ancestor list.  So this needs to be the deepest representation of the position
    // before we walk the DOM tree.
    insertionPosition = positionOutsideTabSpan(VisiblePosition(insertionPosition).deepEquivalent());

    // If the returned position lies either at the end or at the start of an element that is ignored by editing
    // we should move to its upstream or downstream position.
    if (editingIgnoresContent(insertionPosition.deprecatedNode())) {
        if (insertionPosition.atLastEditingPositionForNode())
            insertionPosition = insertionPosition.downstream();
        else if (insertionPosition.atFirstEditingPositionForNode())
            insertionPosition = insertionPosition.upstream();
    }

    // Make sure we do not cause a rendered space to become unrendered.
    // FIXME: We need the affinity for pos, but pos.downstream() does not give it
    Position leadingWhitespace = leadingWhitespacePosition(insertionPosition, VP_DEFAULT_AFFINITY);
    // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
    // after the preserved newline, causing the newline to be turned into a nbsp.
    if (leadingWhitespace.isNotNull() && leadingWhitespace.deprecatedNode()->isTextNode()) {
        Text* textNode = toText(leadingWhitespace.deprecatedNode());
        ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
        replaceTextInNodePreservingMarkers(textNode, leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
    }

    // Split at pos if in the middle of a text node.
    Position positionAfterSplit;
    if (insertionPosition.anchorType() == Position::PositionIsOffsetInAnchor && insertionPosition.containerNode()->isTextNode()) {
        RefPtr<Text> textNode = toText(insertionPosition.containerNode());
        bool atEnd = static_cast<unsigned>(insertionPosition.offsetInContainerNode()) >= textNode->length();
        if (insertionPosition.deprecatedEditingOffset() > 0 && !atEnd) {
            splitTextNode(textNode, insertionPosition.offsetInContainerNode());
            positionAfterSplit = firstPositionInNode(textNode.get());
            insertionPosition.moveToPosition(textNode->previousSibling(), insertionPosition.offsetInContainerNode());
            visiblePos = VisiblePosition(insertionPosition);
        }
    }

    // If we got detached due to mutation events, just bail out.
    if (!startBlock->parentNode())
        return;

    // Put the added block in the tree.
    if (nestNewBlock) {
        appendNode(blockToInsert.get(), startBlock);
    } else {
        insertNodeAfter(blockToInsert.get(), startBlock);
    }

    document().updateLayoutIgnorePendingStylesheets();

    // Move the start node and the siblings of the start node.
    if (VisiblePosition(insertionPosition) != VisiblePosition(positionBeforeNode(blockToInsert.get()))) {
        Node* n;
        if (insertionPosition.containerNode() == startBlock)
            n = insertionPosition.computeNodeAfterPosition();
        else {
            Node* splitTo = insertionPosition.containerNode();
            if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
                splitTo = NodeTraversal::next(*splitTo, startBlock.get());
            ASSERT(splitTo);
            splitTreeToNode(splitTo, startBlock.get());

            for (n = startBlock->firstChild(); n; n = n->nextSibling()) {
                VisiblePosition beforeNodePosition(positionBeforeNode(n));
                if (!beforeNodePosition.isNull() && comparePositions(VisiblePosition(insertionPosition), beforeNodePosition) <= 0)
                    break;
            }
        }

        moveRemainingSiblingsToNewParent(n, blockToInsert.get(), blockToInsert);
    }

    // Handle whitespace that occurs after the split
    if (positionAfterSplit.isNotNull()) {
        document().updateLayoutIgnorePendingStylesheets();
        if (!positionAfterSplit.isRenderedCharacter()) {
            // Clear out all whitespace and insert one non-breaking space
            ASSERT(!positionAfterSplit.containerNode()->renderer() || positionAfterSplit.containerNode()->renderer()->style()->collapseWhiteSpace());
            deleteInsignificantTextDownstream(positionAfterSplit);
            if (positionAfterSplit.deprecatedNode()->isTextNode())
                insertTextIntoNode(toText(positionAfterSplit.containerNode()), 0, nonBreakingSpaceString());
        }
    }

    setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()), DOWNSTREAM, endingSelection().isDirectional()));
}
void InsertTextCommand::input(const String& text, bool selectInsertedText)
{
    
    ASSERT(text.find('\n') == notFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(text, selectInsertedText))
            return;
        deleteSelection(false, true, true, false);
    }

    Position startPosition(endingSelection().start());
    
    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content 
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }
    
    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();
    
    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.node()));
    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
    if (!startPosition.node()->inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();
    
    startPosition = positionAvoidingSpecialElementBoundary(startPosition);
    
    Position endPosition;
    
    if (text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        m_charactersAdded += 1;
    } else {
        // Make sure the document is set up to receive text
        startPosition = prepareForTextInsertion(startPosition);
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        Text *textNode = static_cast<Text *>(startPosition.node());
        int offset = startPosition.deprecatedEditingOffset();

        insertTextIntoNode(textNode, offset, text);
        endPosition = Position(textNode, offset + text.length());

        // The insertion may require adjusting adjacent whitespace, if it is present.
        rebalanceWhitespaceAt(endPosition);
        // Rebalancing on both sides isn't necessary if we've inserted a space.
        if (text != " ") 
            rebalanceWhitespaceAt(startPosition);
            
        m_charactersAdded += text.length();
    }

    // We could have inserted a part of composed character sequence,
    // so we are basically treating ending selection as a range to avoid validation.
    // <http://bugs.webkit.org/show_bug.cgi?id=15781>
    VisibleSelection forcedEndingSelection;
    forcedEndingSelection.setWithoutValidation(startPosition, endPosition);
    setEndingSelection(forcedEndingSelection);

    // Handle the case where there is a typing style.
    CSSMutableStyleDeclaration* typingStyle = document()->frame()->selection()->typingStyle();
    RefPtr<CSSComputedStyleDeclaration> endingStyle = endPosition.computedStyle();
    RefPtr<CSSValue> unicodeBidi;
    RefPtr<CSSValue> direction;
    if (typingStyle) {
        unicodeBidi = typingStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi);
        direction = typingStyle->getPropertyCSSValue(CSSPropertyDirection);
    }
    endingStyle->diff(typingStyle);
    if (typingStyle && unicodeBidi) {
        ASSERT(unicodeBidi->isPrimitiveValue());
        typingStyle->setProperty(CSSPropertyUnicodeBidi, static_cast<CSSPrimitiveValue*>(unicodeBidi.get())->getIdent());
        if (direction) {
            ASSERT(direction->isPrimitiveValue());
            typingStyle->setProperty(CSSPropertyDirection, static_cast<CSSPrimitiveValue*>(direction.get())->getIdent());
        }
    }

    if (typingStyle && typingStyle->length())
        applyStyle(typingStyle);

    if (!selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity()));
}
Пример #8
0
	void TextField::handleKeyboard( KeyEvent &keyEvent )
	{
		if(handleHotkeys(keyEvent))
		{
			return;
		}

		//delete the next character
		if(keyEvent.getKey() == KEY_DELETE)
		{
			if(getCaretPosition() == getTextLength()
				&& getSelectionStart() == getSelectionEnd())
			{
				return;
			}

			if(isReadOnly())
			{
				return;
			}

			if(getSelectionStart() == getSelectionEnd())
			{
				removeNextCharacter();
			}
			else
			{
				deleteSelection();
			}
			setBlinking(true);
			invalidateBlink();
			return;
		}

		//delete the previous character
		if(keyEvent.getKey() == KEY_BACKSPACE)
		{
			if(getCaretPosition() == 0 && getSelectionStart() == getSelectionEnd())
			{
				return;
			}

			if(isReadOnly())
			{
				return;
			}

			if(getSelectionStart() == getSelectionEnd())
			{
				removeLastCharacter();
			}
			else
			{
				deleteSelection();
			}
			setBlinking(true);
			invalidateBlink();
			return;
		}

		if(keyEvent.getUnichar() >= ' ')
		{
			if(isReadOnly())
			{
				setBlinking(true);
				invalidateBlink();
				return;
			}

			if( isNumeric())
			{
				if(keyEvent.getUnichar() >= 0x30  && keyEvent.getUnichar() <= 0x39 )
				{
					deleteSelection();
					addToNextCharacter(keyEvent.getUnichar());
					setBlinking(true);
					invalidateBlink();
				}
				else if(wantedDecimal() && keyEvent.getUnichar() == 0x2e )
				{
					//check if there is already a decimal
					const char *text = getText().c_str();
					for (int i = 0; i < getTextLength(); ++i)
					{
						if(text[i] == 0x2e)
						{
							return;
						}
					}

					deleteSelection();
					addToNextCharacter(keyEvent.getUnichar());
					setBlinking(true);
					invalidateBlink();
				}
				else if(wantedMinus() && keyEvent.getUnichar() == 0x2d )
				{
					//check if we are in the first position
					if(getCaretPosition() != 0)
					{
						return;
					}

					//check if there is already a minus
					const char *text = getText().c_str();
					for (int i = 0; i < getTextLength(); ++i)
					{
						if(text[i] == 0x2d)
						{
							return;
						}
					}

					deleteSelection();
					addToNextCharacter(keyEvent.getUnichar());
					setBlinking(true);
					invalidateBlink();
				}
				

				return;
			}
			deleteSelection();
			addToNextCharacter(keyEvent.getUnichar());

			setBlinking(true);
			invalidateBlink();
			return;
		}

		switch (keyEvent.getExtendedKey())
		{
		case EXT_KEY_RIGHT:

			if(getCaretPosition() == getTextLength() 
				&& getSelectionStart() != getSelectionEnd() &&
				keyEvent.shift())
			{
				return;
			}
			else if(getCaretPosition() == getTextLength() 
				&& getSelectionStart() == getSelectionEnd())
			{
				return;
			}

			positionCaret(getCaretPosition() + 1);

			if(keyEvent.shift())
			{
				if(getSelectionStart() == getSelectionEnd())
				{
					setSelection(getCaretPosition() - 1, getCaretPosition());
				}
				else
				{
					if(getCaretPosition() - 1 < getSelectionEnd())
						setSelection(getSelectionEnd(), getCaretPosition());
					else
						setSelection(getSelectionStart(), getCaretPosition());
				}
			}
			else if(getSelectionStart() != getSelectionEnd())
			{
				int caretPos = getSelectionEnd();
				setSelection(0,0);
				positionCaret(caretPos);
			}

			setBlinking(true);
			invalidateBlink();
			break;
		case EXT_KEY_LEFT:

			if(getCaretPosition() == 0 
				&& getSelectionStart() != getSelectionEnd() &&
				keyEvent.shift())
			{
				return;
			}
			else if(getCaretPosition() == 0
				&& getSelectionStart() == getSelectionEnd())
			{
				return;
			}

			positionCaret(getCaretPosition() - 1);

			if(keyEvent.shift())
			{
				if(getSelectionStart() == getSelectionEnd())
				{
					setSelection(getCaretPosition() + 1, getCaretPosition());
				}
				else
				{
					if(getCaretPosition() + 1 < getSelectionEnd())
						setSelection(getSelectionEnd(), getCaretPosition());
					else
						setSelection(getSelectionStart(), getCaretPosition());
				}
			}

			else if(getSelectionStart() != getSelectionEnd())
			{
				int caretPos = getSelectionStart();
				setSelection(0,0);
				positionCaret(caretPos);
			}

			setBlinking(true);
			invalidateBlink();
			break;
		}

	}
Пример #9
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _has_unsaved_data(true),
    _current_file(""),
    _can_run(false),
    _is_running(false),
    _is_debug_input(false)
{
    ui->setupUi(this);

    initStyles();
    updateWindowTitle();
    redoAvailable(false);
    undoAvailable(false);
    copyAvailable(false);



    _window = this;

    ui->debugRun->setVisible(false);
    ui->runWidget->setVisible(false);

    registerFileType(tr("Yad.Markov.File"),
                     tr("Markov Algorithm File"),
                     ".yad",
                     1);

    updateDebugMenu();

    //Connect MainWindow menu
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionUndo, SIGNAL(triggered()), this, SIGNAL(undo()));
    connect(ui->actionRedo, SIGNAL(triggered()), this, SIGNAL(redo()));
    connect(ui->actionSelect_All, SIGNAL(triggered()), this, SIGNAL(selectAll()));
    connect(ui->actionCopy, SIGNAL(triggered()), this, SIGNAL(copy()));
    connect(ui->actionPaste, SIGNAL(triggered()), this, SIGNAL(paste()));
    connect(ui->actionCut, SIGNAL(triggered()), this, SIGNAL(cut()));
    connect(ui->actionDelete, SIGNAL(triggered()), this, SIGNAL(deleteSelection()));
    connect(ui->actionNew, SIGNAL(triggered()), this, SIGNAL(newFile()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SIGNAL(open()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SIGNAL(save()));
    connect(ui->actionSave_As, SIGNAL(triggered()), this, SIGNAL(saveAs()));
    connect(ui->actionTutorial, SIGNAL(triggered()), this, SLOT(tutorial()));
    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));

    //Connect InputWidget and HistoryManager
    HistoryManager* history_manager = HistoryManager::getInstance();

    connect(ui->input, SIGNAL(addToHistory(QString)),
            history_manager, SLOT(addToHistory(QString)));
    connect(history_manager, SIGNAL(wordSelected(QString)),
            ui->input, SLOT(setInput(QString)));

    //Connect HistoryWidget and HistoryManager
    connect(ui->history, SIGNAL(inputWordSelected(QString)),
            history_manager, SIGNAL(wordSelected(QString)));
    connect(ui->history, SIGNAL(removeFromHistory(QString)),
            history_manager, SLOT(removeFromHistory(QString)));
    connect(history_manager, SIGNAL(historyChanged(QVector<QString>)),
            ui->history, SLOT(historyChanged(QVector<QString>)));

    //Connect MainWindows and FileManager
    FileManager* file_manager = FileManager::getInstance();
    connect(this, SIGNAL(newFile()), file_manager, SLOT(newFile()));
    connect(this, SIGNAL(open()), file_manager, SLOT(open()));
    connect(this, SIGNAL(save()), file_manager, SLOT(save()));
    connect(this, SIGNAL(saveAs()), file_manager, SLOT(saveAs()));
    connect(file_manager, SIGNAL(hasUnsavedData(bool)),
            this, SLOT(hasUnsavedData(bool)));
    connect(file_manager, SIGNAL(fileNameChanged(QString)),
            this, SLOT(fileNameChanged(QString)));

    //Connect MainWindows and EditorWindowWidget
    connect(this, SIGNAL(undo()), ui->editorWindow, SLOT(undo()));
    connect(this, SIGNAL(redo()), ui->editorWindow, SLOT(redo()));
    connect(this, SIGNAL(selectAll()), ui->editorWindow, SLOT(selectAll()));
    connect(this, SIGNAL(copy()), ui->editorWindow, SLOT(copy()));
    connect(this, SIGNAL(paste()), ui->editorWindow, SLOT(paste()));
    connect(this, SIGNAL(cut()), ui->editorWindow, SLOT(cut()));
    connect(this, SIGNAL(deleteSelection()),
            ui->editorWindow, SLOT(deleteSelection()));

    connect(ui->editorWindow, SIGNAL(redoAvailable(bool)),
            this, SLOT(redoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(undoAvailable(bool)),
            this, SLOT(undoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(copyAvailable(bool)),
            this, SLOT(copyAvailable(bool)));

    //Connect InputWidget and MarkovRunManager
    MarkovRunManager* run_manager = MarkovRunManager::getInstance();

    connect(ui->input, SIGNAL(run(QString)),
            run_manager, SLOT(runWithoutDebug(QString)));
    connect(ui->input, SIGNAL(runWithDebug(QString)),
            run_manager, SLOT(runWithDebug(QString)));
    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            ui->input, SLOT(runStarted()));
    connect(ui->input, SIGNAL(runWithDebugStepByStep(QString)),
            run_manager, SLOT(runWithDebugStepByStep(QString)));
    connect(run_manager, SIGNAL(debugStarted(QString)),
            ui->input, SLOT(runStarted()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(canRunSourceCode(bool)),
            ui->input, SLOT(canRunAlgorithm(bool)));

    //Connect SourceCodeManager and EditorWindowWidget
    SourceCodeManager* source_manager = SourceCodeManager::getInstance();
    connect(source_manager, SIGNAL(newSourceCodeWasLoaded(QString)),
            ui->editorWindow, SLOT(newSourceCode(QString)));
    connect(ui->editorWindow, SIGNAL(sourceCodeChanged(QString)),
            source_manager, SLOT(setSourceCode(QString)));

    //Connect InputWidget and FileManager
    connect(ui->input, SIGNAL(save()), file_manager, SLOT(save()));

    //Connect MarkovRunManager and EditorWindowWidget
    connect(ui->editorWindow, SIGNAL(canRun(bool)),
            run_manager, SLOT(setCanRunSourceCode(bool)));
    connect(ui->editorWindow, SIGNAL(markovAlgorithmChanged(MarkovAlgorithm)),
            run_manager, SLOT(setAlgorithm(MarkovAlgorithm)));

    //Connect SourceCodeManager and FileManager
    connect(file_manager, SIGNAL(newSourceCodeLoaded(QString)),
            source_manager, SLOT(setNewSourceCodeFromFile(QString)));
    connect(source_manager, SIGNAL(sourceCodeChanged(QString)),
            file_manager, SLOT(sourceCodeChanged()));

    //Connect FileManager and HistoryManager
    connect(file_manager, SIGNAL(newHistoryLoaded(QVector<QString>)),
            this, SLOT(newHistoryLoaded(QVector<QString>)));
    connect(history_manager, SIGNAL(historyChanged(QVector<QString>)),
            file_manager, SLOT(historyChanged()));

    //Connect RunWidget and MarkovRunManager
    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            ui->runWidget, SLOT(runStarted(QString)));
    connect(run_manager, SIGNAL(runStepsMade(int)),
            ui->runWidget, SLOT(runStepsMade(int)));
    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            ui->runWidget, SLOT(runFailed(QString,RunError,int)));
    connect(run_manager, SIGNAL(runWithoutDebugFinishSuccess(QString,QString,int)),
            ui->runWidget, SLOT(runSuccess(QString,QString,int)));
    connect(run_manager, SIGNAL(debugStarted(QString)),
            ui->runWidget, SLOT(hide()));

    //Connect DebugRunWidget and MarkovRunManager
    connect(ui->debugRun, SIGNAL(nextStepClicked()),
            run_manager, SLOT(debugNextStep()));
    connect(ui->debugRun, SIGNAL(continueClicked()),
            run_manager, SLOT(debugContinue()));
    connect(ui->debugRun, SIGNAL(stopClicked()),
            run_manager, SLOT(debugStop()));

    connect(run_manager, SIGNAL(debugStarted(QString)),
            ui->debugRun, SLOT(debugStarted(QString)));
    connect(run_manager, SIGNAL(debugFinishSuccess(QString,QString,int)),
            ui->debugRun, SLOT(debugSuccess(QString,QString,int)));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            ui->debugRun, SLOT(debugFailed(QString,RunError,int)));
    connect(run_manager, SIGNAL(debugStepFinished(int,QString,QString,MarkovRule)),
            ui->debugRun, SLOT(debugStepFinished(int,QString,QString,MarkovRule)));
    connect(run_manager, SIGNAL(debugBreakPointReached(int)),
            ui->debugRun, SLOT(breakPointReached(int)));
    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            ui->debugRun, SLOT(hide()));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            ui->runWidget, SLOT(hide()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            ui->debugRun, SLOT(hide()));

    //Connect DebugRunWidget and EditorWindowWidget
    connect(ui->debugRun, SIGNAL(removeBreakPoint()),
            ui->editorWindow, SLOT(removeLineHighlight()));
    connect(ui->debugRun, SIGNAL(showBreakPoint(int)),
            ui->editorWindow, SLOT(showLineHighlight(int)));

    //Connect MarkovRunManager and EditorWindowWidget
    connect(ui->editorWindow, SIGNAL(breakPointAdded(int)),
            run_manager, SLOT(addBreakPoint(int)));
    connect(ui->editorWindow, SIGNAL(breakPointRemoved(int)),
            run_manager, SLOT(removeBreakPoint(int)));

    //Connect top menu
    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            this, SLOT(runStarted()));
    connect(run_manager, SIGNAL(debugStarted(QString)),
            this, SLOT(runStarted()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            this, SLOT(runFinished()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishSuccess(QString,QString,int)),
            this, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            this, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishSuccess(QString,QString,int)),
            this, SLOT(runFinished()));
    connect(run_manager, SIGNAL(canRunSourceCode(bool)),
            this, SLOT(canRunAlgorithm(bool)));
    connect(run_manager, SIGNAL(debugBreakPointReached(int)),
            this, SLOT(debugInputStarted()));
    connect(run_manager, SIGNAL(debugStepFinished(int,QString,QString,MarkovRule)),
            this, SLOT(debugInputFinished()));

    connect(ui->actionRun, SIGNAL(triggered()),
            ui->input, SLOT(runCliked()));
    connect(ui->actionDebug, SIGNAL(triggered()),
            ui->input, SLOT(runWithDebugClicked()));
    connect(ui->actionNext_Step, SIGNAL(triggered()),
            run_manager, SLOT(debugNextStep()));
    connect(ui->actionContinue, SIGNAL(triggered()),
            run_manager, SLOT(debugContinue()));
    connect(ui->actionStop_Debug, SIGNAL(triggered()),
            run_manager, SLOT(debugStop()));
    connect(ui->actionDebug_Step_By_Step, SIGNAL(triggered()),
            ui->input, SLOT(runWithDebugStepByStepClicked()));

    //Read file to open from command line
    QStringList arguments = QCoreApplication::arguments();
    if(arguments.size() >= 2)
    {
        QString file_name = arguments.at(1);
        FileManager::getInstance()->openFile(file_name);
    }
    else
    {
        source_manager->setNewSourceCodeFromFile(tr("//Alphabet\nT = {a, b}\n\n//Rules\nab -> a\na ->. b"));
    }

}
Пример #10
0
//BEGIN class ItemView
ItemView::ItemView(ItemDocument * itemDocument, ViewContainer *viewContainer, uint viewAreaId, const char *name)
		: View(itemDocument, viewContainer, viewAreaId, name) {
	KActionCollection * ac = actionCollection();

	KStdAction::selectAll(itemDocument,	SLOT(selectAll()),	ac);
	KStdAction::zoomIn(this,		SLOT(zoomIn()),		ac);
	KStdAction::zoomOut(this,		SLOT(zoomOut()),	ac);
	KStdAction::actualSize(this,		SLOT(actualSize()),	ac)->setEnabled(false);


	KAccel *pAccel = new KAccel(this);
	pAccel->insert("Cancel", i18n("Cancel"), i18n("Cancel the current operation"), Qt::Key_Escape, itemDocument, SLOT(cancelCurrentOperation()));
	pAccel->readSettings();

	new KAction(i18n("Delete"), "editdelete", Qt::Key_Delete, itemDocument, SLOT(deleteSelection()), ac, "edit_delete");
	new KAction(i18n("Export as Image..."), 0, 0, itemDocument, SLOT(exportToImage()), ac, "file_export_image");

	//BEGIN Item Alignment actions
	new KAction(i18n("Align Horizontally"), 0, 0, itemDocument, SLOT(alignHorizontally()), ac, "align_horizontally");
	new KAction(i18n("Align Vertically"), 0, 0, itemDocument, SLOT(alignVertically()), ac, "align_vertically");
	new KAction(i18n("Distribute Horizontally"), 0, 0, itemDocument, SLOT(distributeHorizontally()), ac, "distribute_horizontally");
	new KAction(i18n("Distribute Vertically"), 0, 0, itemDocument, SLOT(distributeVertically()), ac, "distribute_vertically");
	//END Item Alignment actions


	//BEGIN Draw actions
	KToolBarPopupAction * pa = new KToolBarPopupAction(i18n("Draw"), "paintbrush", 0, 0, 0, ac, "edit_draw");
	pa->setDelayed(false);

	KPopupMenu * m = pa->popupMenu();
	m->insertTitle(i18n("Draw"));

	m->insertItem(KGlobal::iconLoader()->loadIcon("tool_text",	KIcon::Small), i18n("Text"),		DrawPart::da_text);
	m->insertItem(KGlobal::iconLoader()->loadIcon("tool_line",	KIcon::Small), i18n("Line"),		DrawPart::da_line);
	m->insertItem(KGlobal::iconLoader()->loadIcon("tool_arrow",	KIcon::Small), i18n("Arrow"),		DrawPart::da_arrow);
	m->insertItem(KGlobal::iconLoader()->loadIcon("tool_ellipse",	KIcon::Small), i18n("Ellipse"),	DrawPart::da_ellipse);
	m->insertItem(KGlobal::iconLoader()->loadIcon("tool_rectangle", KIcon::Small), i18n("Rectangle"),	DrawPart::da_rectangle);
	m->insertItem(KGlobal::iconLoader()->loadIcon("imagegallery",	KIcon::Small), i18n("Image"),		DrawPart::da_image);
	connect(m, SIGNAL(activated(int)), itemDocument, SLOT(slotSetDrawAction(int)));
	//END Draw actions


	//BEGIN Item Control actions
	new KAction(i18n("Raise Selection"), "bring_forward", Qt::Key_PageUp,   itemDocument, SLOT(raiseZ()), ac, "edit_raise");
	new KAction(i18n("Lower Selection"), "send_backward", Qt::Key_PageDown, itemDocument, SLOT(lowerZ()), ac, "edit_lower");
	//END Item Control actions


	KAction * na = new KAction("", 0, 0, 0, 0, ac, "null_action");
	na->setEnabled(false);

	setXMLFile("ktechlabitemviewui.rc");

	m_pUpdateStatusTmr = new QTimer(this);
	connect(m_pUpdateStatusTmr, SIGNAL(timeout()), this, SLOT(updateStatus()));
	connect(this, SIGNAL(unfocused()), this, SLOT(stopUpdatingStatus()));

	m_pDragItem = 0l;
	p_itemDocument = itemDocument;
	m_zoomLevel = 1.;
	m_CVBEditor = new CVBEditor(p_itemDocument->canvas(), this, "cvbEditor");
	m_CVBEditor->setLineWidth(1);

	connect(m_CVBEditor, SIGNAL(horizontalSliderReleased()), itemDocument, SLOT(requestCanvasResize()));
	connect(m_CVBEditor, SIGNAL(verticalSliderReleased()), itemDocument, SLOT(requestCanvasResize()));

	m_layout->insertWidget(0, m_CVBEditor);

	setAcceptDrops(true);

	setFocusWidget(m_CVBEditor->viewport());
}