Example #1
0
void TagTree::addOffset(LFA_FileRef file)
{
	// 3 points for doing it here: shortness, convenience, 64bit forks needed 
	#if WIN_ENV
		addComment( "offset: 0x%I64X", LFA_Tell( file ) );
	#else
		addComment( "offset: 0x%ll.16X", LFA_Tell( file ) );
	#endif
}
Example #2
0
void CommentsView::loadComments()
{
    for( int i = 0; i < m_model->rowCount(); ++i )  //Reload comments
    {
        addComment( m_model->index( i, 0 ), m_rootWidget, 0 );
    }
}
bool
Reader::readComment()
{
   Location commentBegin = current_ - 1;
   Char c = getNextChar();
   bool successful = false;
   if ( c == '*' )
      successful = readCStyleComment();
   else if ( c == '/' )
      successful = readCppStyleComment();
   if ( !successful )
      return false;

   if ( collectComments_ )
   {
      CommentPlacement placement = commentBefore;
      if ( lastValueEnd_  &&  !containsNewLine( lastValueEnd_, commentBegin ) )
      {
         if ( c != '*'  ||  !containsNewLine( commentBegin, current_ ) )
            placement = commentAfterOnSameLine;
      }

      addComment( commentBegin, current_, placement );
   }
   return true;
}
Example #4
0
void TagTree::addComment(const char* format, ...)
{
	char buffer[4096];
	va_list args;
	va_start(args, format);
		vsprintf(buffer, format, args);
	va_end(args);

	addComment( std::string(buffer) );
}
Example #5
0
// handleEmailComment - handles an email received from from with subject subject and body body.
// Returns true if the mail was processed, else false.
// The email is considered to have been processed if it comments on an existing Consultation Note.
bool Notes_Logic::handleEmailComment (string from, string subject, string body)
{
  // Check whether the Consultation Notes Identifier in the subject exists in the notes database.
  // The CNID looks like: (CNID123456789)
  size_t pos = subject.find ("(CNID");
  if (pos == string::npos) return false;
  subject = subject.substr (pos + 5);
  pos = subject.find (")");
  if (pos == string::npos) return false;
  subject = subject.substr (0, pos);
  // Webserver request.
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  // At this stage, the subject contains an identifier.
  // Check that the identifier is an existing Consultation Note.
  int identifier = convert_to_int (subject);
  Database_Notes database_notes (webserver_request);
  if (!database_notes.identifierExists (identifier)) return false;
  // Check that the from address of the email belongs to an existing user.
  // Or else use the obfuscated email address as the user name.
  string username;
  from = filter_string_extract_email (from);
  if (request->database_users()->emailExists (from)) {
    username = request->database_users()->getEmailToUser (from);
  } else {
    username = from;
    username = filter_string_str_replace ("@", " ", username);
    username = filter_string_str_replace (".", " ", username);
  }
  // Clean the email's body.
  string year = convert_to_string (filter_date_numerical_year (filter_date_seconds_since_epoch ()));
  string sender = Database_Config_General::getSiteMailName();
  body = filter_string_extract_body (body, year, sender);
  // Remove any new lines from the body. This cleans up the email considerably,
  // because some emails that get posted would otherwise look untidy,
  // when the many new lines take up a lot of space.
  body = filter_string_str_replace ("\n", " ", body);
  // Make comment on the consultation note.
  string sessionuser = request->session_logic ()->currentUser ();
  request->session_logic ()->setUsername (username);
  addComment (identifier, body);
  request->session_logic ()->setUsername (sessionuser);
  // Mail confirmation to the username.
  if (request->database_config_user()->getUserNotifyMeOfMyPosts (username)) {
    Database_Mail database_mail = Database_Mail (webserver_request);
    string subject = translate("Your comment was posted");
    subject.append (" [CNID");
    subject.append (convert_to_string (identifier));
    subject.append ("]");
    database_mail.send (username, subject, body);
  }
  // Log operation.
  Database_Logs::log ("Comment posted: " + body);
  // Job done.
  return true;
}
Example #6
0
void CommentsView::setModel( QAbstractItemModel* model )
{
    AbstractItemView::setModel( model );
    connect( model, SIGNAL( modelReset() ), SLOT( reloadComments() ) );

    m_rootWidget = new QGraphicsWidget( m_commentsFrame );
    for( int i = 0; i < m_model->rowCount(); ++i )
    {
        addComment( m_model->index( i, 0 ), m_rootWidget, 0 );
    }
}
Example #7
0
PhotoDialog::PhotoDialog(RsPhoto *rs_photo, const RsPhotoPhoto &photo, QWidget *parent) :
    QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint),
    ui(new Ui::PhotoDialog), mRsPhoto(rs_photo), mPhotoQueue(new TokenQueue(mRsPhoto->getTokenService(), this)),
    mPhotoDetails(photo)
{
    ui->setupUi(this);
    setAttribute ( Qt::WA_DeleteOnClose, true );

    connect(ui->pushButton_AddComment, SIGNAL(clicked()), this, SLOT(createComment()));
    connect(ui->pushButton_AddCommentDlg, SIGNAL(clicked()), this, SLOT(addComment()));
    connect(ui->fullscreenButton, SIGNAL(clicked()),this, SLOT(setFullScreen()));

#if QT_VERSION >= 0x040700
    ui->lineEdit->setPlaceholderText(tr("Write a comment...")) ;
#endif

    setUp();
}
Example #8
0
CommentNode* BaseCompiler::comment(const char* fmt, ...) {
  char buf[256];
  char* p = buf;

  if (fmt) {
    *p++ = ';';
    *p++ = ' ';

    va_list ap;
    va_start(ap, fmt);
    p += vsnprintf(p, 254, fmt, ap);
    va_end(ap);
  }

  p[0] = '\n';
  p[1] = '\0';

  return addComment(fmt);
}
Example #9
0
void PersonView::slotLinkClicked( const QUrl &url )
{
  qDebug() << "CLICKED" << url;

  if ( url.scheme() == "polka" ) {
    QStringList path = url.path().split("/");
    QString action = path.first();
    qDebug() << "ACTION" << action;

    if ( action == "editName" ) editName();

    else if ( action == "addEmail" ) addEmail();
    else if ( action == "editEmail" ) editEmail( path.value( 1 ) );
    else if ( action == "removeEmail" ) removeEmail( path.value( 1 ) );
    else if ( action == "commentEmail" ) commentEmail( path.value( 1 ) );

    else if ( action == "addPhone" ) addPhone();
    else if ( action == "editPhone" ) editPhone( path.value( 1 ) );
    else if ( action == "removePhone" ) removePhone( path.value( 1 ) );
    else if ( action == "commentPhone" ) commentPhone( path.value( 1 ) );

    else if ( action == "addLink" ) addLink();
    else if ( action == "editLink" ) editLink( path.value( 1 ) );
    else if ( action == "removeLink" ) removeLink( path.value( 1 ) );
    else if ( action == "commentLink" ) commentLink( path.value( 1 ) );

    else if ( action == "addAddress" ) addAddress();
    else if ( action == "editAddress" ) editAddress( path.value( 1 ) );
    else if ( action == "removeAddress" ) removeAddress( path.value( 1 ) );
    else if ( action == "commentAddress" ) commentAddress( path.value( 1 ) );

    else if ( action == "addComment" ) addComment();
    else if ( action == "editComment" ) editComment( path.value( 1 ) );
    else if ( action == "removeComment" ) removeComment( path.value( 1 ) );

    else if ( action == "close" ) requestClose();
    else if ( action == "magic" ) debugHtml();

    else qDebug() << "unknown action" << action;
  } else {
    new KRun( QUrl( url ), this );
  }
}
Example #10
0
void CommentsModel::setContact(Vreen::Contact *contact)
{
    if (contact == m_contact.data())
        return;
    if (!m_session.isNull()) {
        clear();
        m_session.data()->deleteLater();
    }
    if (!contact)
        return;
    auto session = new Vreen::CommentSession(contact);
    connect(session, SIGNAL(commentAdded(QVariantMap)), SLOT(addComment(QVariantMap)));
    connect(session, SIGNAL(commentDeleted(int)), SLOT(deleteComment(int)));
    session->setPostId(m_postId);

    m_contact = contact;
    m_session = session;
    emit contactChanged(contact);
}
Example #11
0
void UContainerTag::menu(QMenu &menu)
{
    QMenu *m;
    if(isIndependent())
    {
        m=menu.addMenu("Insert within");
    }else
        m=&menu;
    m->addAction("  - Insert -")->setEnabled(false);
    m->addAction("Condition",this,SLOT(addCondition()));
    m->addAction("Traverse",this,SLOT(addTraverse()));
    m->addAction("Loop",this,SLOT(addLoop()));
    m->addAction("Break loop",this,SLOT(addBreak()));
    m->addAction("Continue loop",this,SLOT(addContinue()));
    m->addAction("Function call",this,SLOT(addFunction()));
    m->addAction("Variable assign",this,SLOT(addAssign()));
    m->addAction("Return",this,SLOT(addReturn()));
    m->addAction("Python command",this,SLOT(addExec()));
    m->addAction("Comment",this,SLOT(addComment()));
}
Example #12
0
void eGuiOpPage::loadFromXml(const QDomElement &node)
{
    m_opPage->setUserName(eString(node.attribute("name").toAscii()));

    // Load in operators of this page.
    QDomElement xmlOp = node.firstChildElement("operator");

    while (!xmlOp.isNull())
    {
        const QString opType = xmlOp.attribute("type");
        const eID opId = xmlOp.attribute("id").toInt();
        const eU32 xpos = xmlOp.attribute("xpos").toInt();
        const eU32 ypos = xmlOp.attribute("ypos").toInt();
        const eU32 width = xmlOp.attribute("width").toInt();

        eIOperator *op =  m_opPage->addOperator(opType.toAscii().constData(), ePoint(xpos, ypos), width, eFALSE, opId);
        eASSERT(op != eNULL);
        eGuiOperator *guiOp = new eGuiOperator(op, this);
        eASSERT(guiOp != eNULL);
        addItem(guiOp);
        guiOp->loadFromXml(xmlOp);

        xmlOp = xmlOp.nextSiblingElement("operator");
    }

    // Load in comments of this page.
    QDomElement xmlCmt = node.firstChildElement("comment");

    while (!xmlCmt.isNull())
    {
        const eF32 xpos = xmlCmt.attribute("xpos").toFloat();
        const eF32 ypos = xmlCmt.attribute("ypos").toFloat();
        const QString text = xmlCmt.attribute("text");

        addComment(text, QPointF(xpos, ypos));

        xmlCmt = xmlCmt.nextSiblingElement("comment");
    }
}
Example #13
0
CommentsViewItem* CommentsView::addComment( const QModelIndex& index, QGraphicsWidget* parent, int depth )
{
    CommentsViewItem* item = new CommentsViewItem( parent );
    item->setReplyEnabled( qobject_cast<GluonPlayer::CommentsModel*>( m_model )->isOnline() );
    item->setParent( parent );
    item->setDepth( depth );
    item->setModelIndex( index );
    item->setAcceptHoverEvents( true );
    item->installEventFilter( this );
    connect( item, SIGNAL( replyClicked() ), SLOT( showReply() ) );
    item->setRowInLayout( m_commentsLayout->count() );
    m_commentsLayout->addItem( item );

    if( m_model->hasChildren( index ) )  //There are one or more children
    {
        for( int i = 0; i < m_model->rowCount( index ); ++i )
        {
            addComment( index.child( i, 0 ), item, depth + 1 );
        }
    }

    return item;
}
Example #14
0
void PhotoDialog::loadComment(uint32_t token)
{

    clearComments();

    PhotoRelatedCommentResult results;
    mRsPhoto->getPhotoRelatedComment(token, results);

    PhotoRelatedCommentResult::iterator mit = results.begin();

    for(; mit != results.end(); ++mit)
    {
        const std::vector<RsPhotoComment>& commentV = mit->second;
        std::vector<RsPhotoComment>::const_iterator vit = commentV.begin();

        for(; vit != commentV.end(); ++vit)
        {
            addComment(*vit);
        }
    }

    resetComments();
}
Example #15
0
///////////////////////////////////////////////////////////////////////////////
// Basic test steps for most virtual methods in SkCanvas that draw or affect
// the state of the canvas.

SIMPLE_TEST_STEP(Translate, translate(SkIntToScalar(1), SkIntToScalar(2)));
SIMPLE_TEST_STEP(Scale, scale(SkIntToScalar(1), SkIntToScalar(2)));
SIMPLE_TEST_STEP(Rotate, rotate(SkIntToScalar(1)));
SIMPLE_TEST_STEP(Skew, skew(SkIntToScalar(1), SkIntToScalar(2)));
SIMPLE_TEST_STEP(Concat, concat(d.fMatrix));
SIMPLE_TEST_STEP(SetMatrix, setMatrix(d.fMatrix));
SIMPLE_TEST_STEP(ClipRect, clipRect(d.fRect));
SIMPLE_TEST_STEP(ClipPath, clipPath(d.fPath));
SIMPLE_TEST_STEP(ClipRegion, clipRegion(d.fRegion, SkRegion::kReplace_Op));
SIMPLE_TEST_STEP(Clear, clear(d.fColor));
SIMPLE_TEST_STEP(BeginGroup, beginCommentGroup(d.fText.c_str()));
SIMPLE_TEST_STEP(AddComment, addComment(d.fText.c_str(), d.fText.c_str()));
SIMPLE_TEST_STEP(EndGroup, endCommentGroup());

///////////////////////////////////////////////////////////////////////////////
// Complex test steps

static void SaveMatrixClipStep(SkCanvas* canvas, const TestData& d,
                               skiatest::Reporter* reporter, CanvasTestStep* testStep) {
    int saveCount = canvas->getSaveCount();
    canvas->save();
    canvas->translate(SkIntToScalar(1), SkIntToScalar(2));
    canvas->clipRegion(d.fRegion);
    canvas->restore();
    REPORTER_ASSERT_MESSAGE(reporter, canvas->getSaveCount() == saveCount,
        testStep->assertMessage());
    REPORTER_ASSERT_MESSAGE(reporter, canvas->getTotalMatrix().isIdentity(),
Example #16
0
File: c.c Project: LucasAbreu/c
int main (int argc, const char * argv[]) {

    // Get the current directory
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != NULL)
        ;
    else
        perror("getcwd() error");

    int numargs, all=0, asc=0, desc=0, push=0, uk=0, help=0, current=0, clean=0;
    const char *c;

    numargs = argc;

    while (--numargs > 0) {
        c = argv[numargs];

        if (!strcmp(argv[numargs], "all"))
            all = 1;
        else if (!strcmp(argv[numargs], "-h") || !strcmp(argv[numargs], "--help"))
            help = 1;
        else if (!strcmp(argv[numargs], "."))
            current = 1;
        else if (!strcmp(argv[numargs], "-p") || !strcmp(argv[numargs], "--push"))
            push = 1;
        else if (!strcmp(argv[numargs], "-"))
            desc = 1;
        else if (!strcmp(argv[numargs], "+"))
            asc = 1;
        else if (!strcmp(argv[numargs], "clean"))
            clean = 1;
        else
            uk++;
    }

    int args;
    args = argc;

    if (uk > 2) {
        printUsage();
        return 1;
    }

    switch(args) {
        // Show the comment for the current directory
        case 1: printUsage();
                return 1;
                break;
        case 2:
                // Show the help menu
                if (help) {
                    printUsage();
                    return 1;
                }
                // Show all the files
                else if (all) {
                    makeDir(cwd);
                    printFiles(cwd);
                }
                // Show comment for the current directory
                else if (current) {
                    // checkComment(argv[1], cwd);
                    printCurrentComment(cwd);
                }
                // Show comment for the entered file
                else {
                    // char *file = argv[1];
                    makeDir(cwd);
                    checkComment(argv[1], cwd);
                }
                break;
        case 3:

                if ( current && !clean ) {										// Add comment to the current directory
                    // char *file;
                    // file = "CURRENT";
                    addComment(argv[1], cwd, argv[2], false);
                } else if (all && desc) {					// Print all files in descending order
                    makeDir(cwd);
                    printAllOrder(cwd, true);
                } else if (all && asc) {					// Print all files in ascending order
                    makeDir(cwd);
                    printAllOrder(cwd, false);
                } else if ( clean ){
                    cleanComment( argv[1] );                 // Clean file comment
                }
                else {														// Add comment to to given file
                    makeDir(cwd);
                    addComment(argv[1], cwd, argv[2], false);
                }
                break;

        case 4:
                // Push comment to the current directory
                if (current && push) {
                    addComment(argv[1], cwd, argv[3], true);
                    // Add a comment to the given filename
                }
                // Push comment to given file
                else	if ( push) {
                    makeDir(cwd);
                    addComment(argv[1], cwd, argv[3], true);
                }
                break;

                // Not certain
        default: printUsage();
    }
    return 0;
}
Example #17
0
void AXmlElement::fromAFile(AFile& file)
{
  AString str(1024, 256);

  //a_Find <
  if (AConstant::npos == file.skipUntilOneOf('<'))
    return;

  //a_Skip over whitespace between < and tagname
  file.skipUntilNotOneOf();

  //a_Extract name and skip over whitespace
  m_Name.clear();
  file.readUntilOneOf(m_Name, AXmlElement::sstr_EndOrWhitespace, false);
  file.skipUntilNotOneOf();
  
  //a_Find /> or >
  char c = ' ';
  if (0 == m_Name.find(ASW("!--",3)))
  {
    if (m_Name.rfind("--", 2) == m_Name.getSize() - 2)  //TODO:
    //a_Special case for comment, must end with '-->' and may contain '>' inside
    file.readUntil(str, AXmlElement::sstr_EndComment);
    addComment(str);
    return;
  }
  else
    file.readUntilOneOf(str, AXmlElement::sstr_End);

  if (!str.isEmpty() && str.at(str.getSize() - 1) == '/')
  {
    c = '/';  //a_Singular mode
    str.setSize(str.getSize() - 1);
  }
  str.stripTrailing();

  //a_Parse attributes
  if (!str.isEmpty())
    m_Attributes.parse(str);

  bool boolEndTagFound = (c == '/');
  while (!boolEndTagFound)
  {
    //a_Read data until next tag starts
    file.skipUntilNotOneOf();                //a_Skip over whitespace
    str.clear();
    if (AConstant::npos == file.readUntilOneOf(str, AXmlElement::sstr_Start))
      break;

    str.stripTrailing();
    if (!str.isEmpty())
    {
      addData(str);
    }

    //a_Skip over whitespace between < and start of the tag name
    file.skipUntilNotOneOf();

    file.peek(c);
    switch(c)
    {
      case '/':
      {
        //a_End of tag found
        file.read(c);
        str.clear();
        file.readUntilOneOf(str, AXmlElement::sstr_EndOrWhitespace);
        file.skipUntilNotOneOf(AXmlElement::sstr_EndOrWhitespace);                //a_Skip over whitespace and >
        if (str != m_Name)
          ATHROW_EX(&file, AException::InvalidData, AString("Close tag </")+str+"> does not match opened tag <"+m_Name+">");
        
        boolEndTagFound = true;
      }
      break;

      //a_Handle embedded CDATA, comments and such
      case '!':
      {
        file.putBack('<');
        str.clear();
        
        file.peek(str, 9);    //a_ either "<!--*--"  or "<![CDATA["
        if (0 == str.findNoCase(AXmlData::sstr_StartCDATA))
        {
          //a_CDATA found
          file.skip(AXmlData::sstr_StartCDATA.getSize());

          AString data;
          file.readUntil(data, AXmlData::sstr_EndCDATA, true, true);
          addData(data, AXmlElement::ENC_CDATADIRECT);
        }
        else if (0 == str.findNoCase(AXmlElement::sstr_StartComment))
        {
          //a_Comment (!--) found
          file.skip(AXmlElement::sstr_StartComment.getSize());

          AString comment;
          file.readUntil(comment, AXmlElement::sstr_EndComment, true, true);
          addComment(comment);
        }
        else
        {
          addData(str);
        }
      }
      break;

      default:
      {
        //a_Put the start tag back
        file.putBack('<');

        //a_Another element
        AAutoPtr<AXmlElement> psubElement(new AXmlElement(), true);
        psubElement->fromAFile(file);
        psubElement.setOwnership(false);
        addContent(psubElement.use());
      }
      break;
    }
  }
}
Example #18
0
	virtual void on_playback_new_track(metadb_handle_ptr track)
	{
		pfc::string8		out = "";
		pfc::string8		fullTitle = "";
		pfc::string8		artist = "";
		pfc::string8		title = "";

       	char	songTitle[1024] = "";
	    char	songTitle2[1024] = "";
	    static	char currentTitle[1024] = "";
	    int		windowTitle = 1;
        char    newTitle[2046] = "";


        if (track != NULL) {
            track->metadb_lock();
			const file_info * info;
			track->get_info_async_locked(info);
            if (info) {
				freeComment();
                int numInfos = info->meta_get_count();
                for (int i=0;i<numInfos;i++) {
                    const char *pName = info->meta_enum_name(i);
                    const char *pValue = info->meta_enum_value(i,0);
                    char *buffer;
                    int bufferlen = 0;
                    bufferlen = strlen(pName) + strlen(pValue) + strlen("=") + 1;
                    buffer = (char *)calloc(1, bufferlen);
                    sprintf(buffer, "%s=%s", pName, pValue);
                    pfc::string8 theout = "";
                    theout.add_string(buffer);
					addComment((char *)(const char *)pfc::stringcvt::string_ansi_from_utf8(theout));
                    free(buffer);
					if (pName) {
						if (!stricmp(pName, "ARTIST")) {
							if (pValue) {
								artist.add_string(pValue);
							}
						}
						if (!stricmp(pName, "TITLE")) {
							if (pValue) {
								title.add_string(" - ");
								title.add_string(pValue);
							}
						}
					}
                }
				if (numInfos == 0) {
			        static const char * TITLE_FORMAT = "%_filename%";
					track->format_title_legacy(0,fullTitle,TITLE_FORMAT,0);
				}
				else {
					fullTitle.add_string(artist);
					fullTitle.add_string(title);
					/*
					track->handle_query_meta_field("ARTIST", 0, out);
					fullTitle.add_string(out);
					track->handle_query_meta_field("TITLE", 0, out);
					fullTitle.add_string(" - ");
					fullTitle.add_string(out);
					*/
					;
				}
	    	    setMetadataFromMediaPlayer((char *)(const char *)pfc::stringcvt::string_ansi_from_utf8(fullTitle));
            }
			track->metadb_unlock();
        }
	}
Example #19
0
AREXPORT ArRobotParams::ArRobotParams() :
  ArConfig(NULL, true),
  myIRUnitGetFunctor(this, &ArRobotParams::getIRUnits),
  myIRUnitSetFunctor(this, &ArRobotParams::parseIRUnit),
  mySonarUnitGetFunctor(this, &ArRobotParams::getSonarUnits),
  mySonarUnitSetFunctor(this, &ArRobotParams::parseSonarUnit)
{
  sprintf(myClass, "Pioneer");
  mySubClass[0] = '\0';
  myRobotRadius = 250;
  myRobotDiagonal = 120;
  myRobotWidth = 400;
  myRobotLength = 500; 
  myRobotLengthFront = 0; 
  myRobotLengthRear = 0; 
  myHolonomic = true;
  myAbsoluteMaxVelocity = 0;
  myAbsoluteMaxRVelocity = 0;
  myHaveMoveCommand = true;
  myAngleConvFactor = 0.001534;
  myDistConvFactor = 0;
  myVelConvFactor = 1.0;
  myRangeConvFactor = 0;
  myVel2Divisor = 20;
  myGyroScaler = 1.626;
  myNumSonar = 0;
  myTableSensingIR = false;
  myNewTableSensingIR = false;
  myFrontBumpers = false;
  myNumFrontBumpers = 5;
  myRearBumpers = false;
  myNumRearBumpers = 5;
  myNumSonar = 0;
  myNumIR = 0;
  mySonarMap.clear();
  myIRMap.clear();
  myLaserPossessed = false;
  sprintf(myLaserPort, "COM3");
  myLaserFlipped = false;
  myLaserPowerControlled = true;
  myLaserX = 0;
  myLaserY = 0;
  myLaserTh = 0.0;
  myLaserIgnore[0] = '\0';
  
  myRequestIOPackets = false;
  myRequestEncoderPackets = false;
  mySwitchToBaudRate = 38400;

  mySettableVelMaxes = true;
  myTransVelMax = 0;
  myRotVelMax = 0;

  mySettableAccsDecs = true;
  myTransAccel = 0;
  myTransDecel = 0;
  myRotAccel = 0;
  myRotDecel = 0;

  addComment("Robot parameter file");
//  addComment("");
  //addComment("General settings");
  std::string section;
  section = "General settings";
  addParam(ArConfigArg("Class", myClass, "general type of robot", 
		 sizeof(myClass)), section.c_str(), ArPriority::TRIVIAL);
  addParam(ArConfigArg("Subclass", mySubClass, "specific type of robot", 
		       sizeof(mySubClass)), section.c_str(), 
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("RobotRadius", &myRobotRadius, "radius in mm"), 
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("RobotDiagonal", &myRobotDiagonal, 
		 "half-height to diagonal of octagon"), "General settings",
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("RobotWidth", &myRobotWidth, "width in mm"), 
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("RobotLength", &myRobotLength, "length in mm of the whole robot"),
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("RobotLengthFront", &myRobotLengthFront, "length in mm to the front of the robot (if this is 0 (or non existant) this value will be set to half of RobotLength)"),
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("RobotLengthRear", &myRobotLengthRear, "length in mm to the rear of the robot (if this is 0 (or non existant) this value will be set to half of RobotLength)"), 
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("Holonomic", &myHolonomic, "turns in own radius"), 
	   section.c_str(), ArPriority::TRIVIAL);
  addParam(ArConfigArg("MaxRVelocity", &myAbsoluteMaxRVelocity, 
		       "absolute maximum degrees / sec"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("MaxVelocity", &myAbsoluteMaxVelocity, 
		 "absolute maximum mm / sec"), section.c_str(), 
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("HasMoveCommand", &myHaveMoveCommand, 
		 "has built in move command"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("RequestIOPackets", &myRequestIOPackets,
		 "automatically request IO packets"), section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("RequestEncoderPackets", &myRequestEncoderPackets,
		       "automatically request encoder packets"), 
	   section.c_str(), ArPriority::NORMAL);
  addParam(ArConfigArg("SwitchToBaudRate", &mySwitchToBaudRate, 
		 "switch to this baud if non-0 and supported on robot"), 
	   section.c_str(), ArPriority::IMPORTANT);
  
  section = "Conversion factors";
  addParam(ArConfigArg("AngleConvFactor", &myAngleConvFactor,
		     "radians per angular unit (2PI/4096)"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("DistConvFactor", &myDistConvFactor,
		       "multiplier to mm from robot units"), section.c_str(),
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("VelConvFactor", &myVelConvFactor,
		     "multiplier to mm/sec from robot units"), 
	   section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("RangeConvFactor", &myRangeConvFactor, 
		       "multiplier to mm from sonar units"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("DiffConvFactor", &myDiffConvFactor, 
		     "ratio of angular velocity to wheel velocity (unused in newer firmware that calculates and returns this)"), 
	   section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("Vel2Divisor", &myVel2Divisor, 
		       "divisor for VEL2 commands"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("GyroScaler", &myGyroScaler, 
		     "Scaling factor for gyro readings"), section.c_str(),
	   ArPriority::IMPORTANT);

  section = "Accessories the robot has";
  addParam(ArConfigArg("TableSensingIR", &myTableSensingIR,
		       "if robot has upwards facing table sensing IR"), 
	   section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("NewTableSensingIR", &myNewTableSensingIR,
		 "if table sensing IR are sent in IO packet"), 
	   section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("FrontBumpers", &myFrontBumpers, 
		 "if robot has a front bump ring"), section.c_str(),
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("NumFrontBumpers", &myNumFrontBumpers,
		     "number of front bumpers on the robot"), 
	   section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("RearBumpers", &myRearBumpers,
		       "if the robot has a rear bump ring"), section.c_str(),
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("NumRearBumpers", &myNumRearBumpers,
		       "number of rear bumpers on the robot"), section.c_str(),
	   ArPriority::TRIVIAL);

  section = "IR parameters";
  addParam(ArConfigArg("IRNum", &myNumIR, "number of IRs on the robot"), section.c_str(), ArPriority::NORMAL);
   addParam(ArConfigArg("IRUnit", &myIRUnitSetFunctor, &myIRUnitGetFunctor,
			"IRUnit <IR Number> <IR Type> <Persistance, cycles> <x position, mm> <y position, mm>"), 
	    section.c_str(), ArPriority::TRIVIAL);


  section = "Sonar parameters";
  addParam(ArConfigArg("SonarNum", &myNumSonar, 
		     "number of sonar on the robot"), section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("SonarUnit", &mySonarUnitSetFunctor, 
		     &mySonarUnitGetFunctor,
		     "SonarUnit <sonarNumber> <x position, mm> <y position, mm> <heading of disc, degrees>"), section.c_str(), ArPriority::TRIVIAL);


  section = "Laser parameters";
  addParam(ArConfigArg("LaserPossessed", &myLaserPossessed, 
		     "if there is a laser on the robot"), section.c_str(),
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("LaserPort", myLaserPort, "port the laser is on", 
		     sizeof(myLaserPort)), section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("LaserFlipped", &myLaserFlipped,
		     "if the laser is upside-down or not"), section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("LaserPowerControlled", &myLaserPowerControlled,
		     "if the power to the laser is controlled by serial"), 
	   section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("LaserX", &myLaserX, "x location of laser, mm"), 
	   section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("LaserY", &myLaserY, "y location of laser, mm"), 
	   section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("LaserTh", &myLaserTh, "rotation of laser, deg"), 
	   section.c_str(),
	   ArPriority::NORMAL);
  addParam(ArConfigArg("LaserIgnore", myLaserIgnore, "Readings within a degree of the listed degrees (separated by a space) will be ignored", sizeof(myLaserIgnore)), 
	   section.c_str(),
	   ArPriority::NORMAL);

  section = "Movement control parameters";
  setSectionComment(section.c_str(), "if these are 0 the parameters from robot flash will be used, otherwise these values will be used");
  addParam(ArConfigArg("SettableVelMaxes", &mySettableVelMaxes, "if TransVelMax and RotVelMax can be set"), section.c_str(),
	   ArPriority::TRIVIAL);
  addParam(ArConfigArg("TransVelMax", &myTransVelMax, "maximum desired translational velocity for the robot"), section.c_str(), 
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("RotVelMax", &myRotVelMax, "maximum desired rotational velocity for the robot"), section.c_str(),
	   ArPriority::IMPORTANT);
  addParam(ArConfigArg("SettableAccsDecs", &mySettableAccsDecs, "if the accel and decel parameters can be set"), section.c_str(), ArPriority::TRIVIAL);
  addParam(ArConfigArg("TransAccel", &myTransAccel, "translational acceleration"), 
	   section.c_str(), ArPriority::IMPORTANT);
  addParam(ArConfigArg("TransDecel", &myTransDecel, "translational deceleration"), 

	   section.c_str(), ArPriority::IMPORTANT);
  addParam(ArConfigArg("RotAccel", &myRotAccel, "rotational acceleration"), 
	   section.c_str());
  addParam(ArConfigArg("RotDecel", &myRotDecel, "rotational deceleration"),
	   section.c_str(), ArPriority::IMPORTANT);

}
void DailymotionComment::addComment(const QVariantMap &comment) {
    loadComment(comment);
    addComment();
}
void AbstractDecorator::decorate(const QString &text, int state)
{
    if (text.contains("\n")) {
        qDebug() << "Wrong block found";
        return;
    }

    prepare(text);

    QmlJS::Scanner scanner;
    QList<QmlJS::Token> tokens = scanner(text, state);
    for (int i = 0; i < tokens.count(); i++) {
        const QmlJS::Token token = tokens.at(i);

        switch (token.kind) {
        case QmlJS::Token::Keyword:
            addKeyword(token.offset, token.length);
            break;
        case QmlJS::Token::Identifier: {
                QString entry = text.mid(token.offset, token.length);

                if (maybeQmlKeyword(entry)) {
                    // check the previous token
                    if (i == 0 || tokens.at(i - 1).isNot(QmlJS::Token::Dot)) {
                        if (i + 1 == tokens.count() || tokens.at(i + 1).isNot(QmlJS::Token::Colon)) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }
                } else if (i > 0 && maybeQmlBuiltinType(entry)) {
                    const QmlJS::Token &previousToken = tokens.at(i - 1);
                    if (previousToken.is(QmlJS::Token::Identifier)
                        && text.mid(previousToken.offset, previousToken.length) == QLatin1String("property")) {
                        addKeyword(token.offset, token.length);
                        break;
                    }
                }

                if (maybeMacro(entry)) {
                    addMacro(token.offset, token.length);
                    break;
                }

                if (entry.at(0).isUpper()) {
                    // Check if we are importing a module
                    if (i > 0) {
                        const QmlJS::Token &previousToken = tokens.first();
                        if (previousToken.is(QmlJS::Token::Identifier)
                            && text.mid(previousToken.offset, previousToken.length) == QLatin1String("import")) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }

                    addComponent(token.offset, token.length);
                    break;
                }

                // Try to find if it is a property
                // The easy ones are followed by a { or a :
                if (i + 1 < tokens.count()) {
                    const QmlJS::Token &nextToken = tokens.at(i + 1);
                    if (nextToken.is(QmlJS::Token::Colon)
                        || nextToken.is(QmlJS::Token::LeftBrace)) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }

                // A harder one is anchors.fill:
                if (i + 3 < tokens.count()) {
                    const QmlJS::Token &next1Token = tokens.at(i + 1);
                    const QmlJS::Token &next2Token = tokens.at(i + 2);
                    const QmlJS::Token &next3Token = tokens.at(i + 3);

                    if (next1Token.is(QmlJS::Token::Dot)
                        && next2Token.is(QmlJS::Token::Identifier)
                        && (next3Token.is(QmlJS::Token::Colon)
                            || next3Token.is(QmlJS::Token::LeftBrace))) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }
            }
            break;
        case QmlJS::Token::String:
            addString(token.offset, token.length);
            break;
        case QmlJS::Token::Comment:
            addComment(token.offset, token.length);
            break;
        case QmlJS::Token::Number:
            addNumber(token.offset, token.length);
            break;
        default:
            break;
        }
    }

    setState(scanner.state());
    finalize();
}
 foreach (Papyro::CommentData * child, ordered) {
     addComment(child);
 }
Example #23
0
namespace SkRecords {

// FIXME: SkBitmaps are stateful, so we need to copy them to play back in multiple threads.
static SkBitmap shallow_copy(const SkBitmap& bitmap) {
    return bitmap;
}

// NoOps draw nothing.
template <> void Draw::draw(const NoOp&) {}

#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }
DRAW(Restore, restore());
DRAW(Save, save());
DRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));
DRAW(PopCull, popCull());
DRAW(PushCull, pushCull(r.rect));
DRAW(Clear, clear(r.color));
DRAW(SetMatrix, setMatrix(SkMatrix::Concat(fInitialCTM, r.matrix)));

DRAW(ClipPath, clipPath(r.path, r.op, r.doAA));
DRAW(ClipRRect, clipRRect(r.rrect, r.op, r.doAA));
DRAW(ClipRect, clipRect(r.rect, r.op, r.doAA));
DRAW(ClipRegion, clipRegion(r.region, r.op));

DRAW(BeginCommentGroup, beginCommentGroup(r.description));
DRAW(AddComment, addComment(r.key, r.value));
DRAW(EndCommentGroup, endCommentGroup());

DRAW(DrawBitmap, drawBitmap(shallow_copy(r.bitmap), r.left, r.top, r.paint));
DRAW(DrawBitmapMatrix, drawBitmapMatrix(shallow_copy(r.bitmap), r.matrix, r.paint));
DRAW(DrawBitmapNine, drawBitmapNine(shallow_copy(r.bitmap), r.center, r.dst, r.paint));
DRAW(DrawBitmapRectToRect,
        drawBitmapRectToRect(shallow_copy(r.bitmap), r.src, r.dst, r.paint, r.flags));
DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
DRAW(DrawImage, drawImage(r.image, r.left, r.top, r.paint));
DRAW(DrawImageRect, drawImageRect(r.image, r.src, r.dst, r.paint));
DRAW(DrawOval, drawOval(r.oval, r.paint));
DRAW(DrawPaint, drawPaint(r.paint));
DRAW(DrawPath, drawPath(r.path, r.paint));
DRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.xmode, r.paint));
DRAW(DrawPicture, drawPicture(r.picture, r.matrix, r.paint));
DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
DRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));
DRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));
DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
DRAW(DrawRect, drawRect(r.rect, r.paint));
DRAW(DrawSprite, drawSprite(shallow_copy(r.bitmap), r.left, r.top, r.paint));
DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
DRAW(DrawTextBlob, drawTextBlob(r.blob, r.x, r.y, r.paint));
DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));
DRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,
                                r.xmode.get(), r.indices, r.indexCount, r.paint));
DRAW(DrawData, drawData(r.data, r.length));
#undef DRAW

// This is an SkRecord visitor that fills an SkBBoxHierarchy.
//
// The interesting part here is how to calculate bounds for ops which don't
// have intrinsic bounds.  What is the bounds of a Save or a Translate?
//
// We answer this by thinking about a particular definition of bounds: if I
// don't execute this op, pixels in this rectangle might draw incorrectly.  So
// the bounds of a Save, a Translate, a Restore, etc. are the union of the
// bounds of Draw* ops that they might have an effect on.  For any given
// Save/Restore block, the bounds of the Save, the Restore, and any other
// non-drawing ("control") ops inside are exactly the union of the bounds of
// the drawing ops inside that block.
//
// To implement this, we keep a stack of active Save blocks.  As we consume ops
// inside the Save/Restore block, drawing ops are unioned with the bounds of
// the block, and control ops are stashed away for later.  When we finish the
// block with a Restore, our bounds are complete, and we go back and fill them
// in for all the control ops we stashed away.
class FillBounds : SkNoncopyable {
public:
    FillBounds(const SkRect& cullRect, const SkRecord& record, SkBBoxHierarchy* bbh) 
        : fCullRect(cullRect)
        , fBounds(record.count()) {
        // Calculate bounds for all ops.  This won't go quite in order, so we'll need
        // to store the bounds separately then feed them in to the BBH later in order.
        fCTM = &SkMatrix::I();
        fCurrentClipBounds = fCullRect;
        for (fCurrentOp = 0; fCurrentOp < record.count(); fCurrentOp++) {
            record.visit<void>(fCurrentOp, *this);
        }

        // If we have any lingering unpaired Saves, simulate restores to make
        // sure all ops in those Save blocks have their bounds calculated.
        while (!fSaveStack.isEmpty()) {
            this->popSaveBlock();
        }

        // Any control ops not part of any Save/Restore block draw everywhere.
        while (!fControlIndices.isEmpty()) {
            this->popControl(fCullRect);
        }

        // Finally feed all stored bounds into the BBH.  They'll be returned in this order.
        SkASSERT(bbh);
        bbh->insert(&fBounds, record.count());
    }

    template <typename T> void operator()(const T& op) {
        this->updateCTM(op);
        this->updateClipBounds(op);
        this->trackBounds(op);
    }

private:
    // In this file, SkRect are in local coordinates, Bounds are translated back to identity space.
    typedef SkRect Bounds;

    struct SaveBounds {
        int controlOps;        // Number of control ops in this Save block, including the Save.
        Bounds bounds;         // Bounds of everything in the block.
        const SkPaint* paint;  // Unowned.  If set, adjusts the bounds of all ops in this block.
    };

    // Only Restore and SetMatrix change the CTM.
    template <typename T> void updateCTM(const T&) {}
    void updateCTM(const Restore& op)   { fCTM = &op.matrix; }
    void updateCTM(const SetMatrix& op) { fCTM = &op.matrix; }

    // Most ops don't change the clip.
    template <typename T> void updateClipBounds(const T&) {}

    // Clip{Path,RRect,Rect,Region} obviously change the clip.  They all know their bounds already.
    void updateClipBounds(const ClipPath&   op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRRect&  op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRect&   op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRegion& op) { this->updateClipBoundsForClipOp(op.devBounds); }

    // The bounds of clip ops need to be adjusted for the paints of saveLayers they're inside.
    void updateClipBoundsForClipOp(const SkIRect& devBounds) {
        Bounds clip = SkRect::Make(devBounds);
        // We don't call adjustAndMap() because as its last step it would intersect the adjusted
        // clip bounds with the previous clip, exactly what we can't do when the clip grows.
        fCurrentClipBounds = this->adjustForSaveLayerPaints(&clip) ? clip : fCullRect;
    }

    // Restore holds the devBounds for the clip after the {save,saveLayer}/restore block completes.
    void updateClipBounds(const Restore& op) {
        // This is just like the clip ops above, but we need to skip the effects (if any) of our
        // paired saveLayer (if it is one); it has not yet been popped off the save stack.  Our
        // devBounds reflect the state of the world after the saveLayer/restore block is done,
        // so they are not affected by the saveLayer's paint.
        const int kSavesToIgnore = 1;
        Bounds clip = SkRect::Make(op.devBounds);
        fCurrentClipBounds =
            this->adjustForSaveLayerPaints(&clip, kSavesToIgnore) ? clip : fCullRect;
    }

    // We also take advantage of SaveLayer bounds when present to further cut the clip down.
    void updateClipBounds(const SaveLayer& op)  {
        if (op.bounds) {
            // adjustAndMap() intersects these layer bounds with the previous clip for us.
            fCurrentClipBounds = this->adjustAndMap(*op.bounds, op.paint);
        }
    }

    // The bounds of these ops must be calculated when we hit the Restore
    // from the bounds of the ops in the same Save block.
    void trackBounds(const Save&)          { this->pushSaveBlock(NULL); }
    void trackBounds(const SaveLayer& op)  { this->pushSaveBlock(op.paint); }
    void trackBounds(const Restore&) { fBounds[fCurrentOp] = this->popSaveBlock(); }

    void trackBounds(const SetMatrix&)         { this->pushControl(); }
    void trackBounds(const ClipRect&)          { this->pushControl(); }
    void trackBounds(const ClipRRect&)         { this->pushControl(); }
    void trackBounds(const ClipPath&)          { this->pushControl(); }
    void trackBounds(const ClipRegion&)        { this->pushControl(); }
    void trackBounds(const PushCull&)          { this->pushControl(); }
    void trackBounds(const PopCull&)           { this->pushControl(); }
    void trackBounds(const BeginCommentGroup&) { this->pushControl(); }
    void trackBounds(const AddComment&)        { this->pushControl(); }
    void trackBounds(const EndCommentGroup&)   { this->pushControl(); }
    void trackBounds(const DrawData&)          { this->pushControl(); }

    // For all other ops, we can calculate and store the bounds directly now.
    template <typename T> void trackBounds(const T& op) {
        fBounds[fCurrentOp] = this->bounds(op);
        this->updateSaveBounds(fBounds[fCurrentOp]);
    }

    void pushSaveBlock(const SkPaint* paint) {
        // Starting a new Save block.  Push a new entry to represent that.
        SaveBounds sb;
        sb.controlOps = 0;
        // If the paint affects transparent black, the bound shouldn't be smaller
        // than the current clip bounds.
        sb.bounds =
            PaintMayAffectTransparentBlack(paint) ? fCurrentClipBounds : Bounds::MakeEmpty();
        sb.paint = paint;

        fSaveStack.push(sb);
        this->pushControl();
    }

    static bool PaintMayAffectTransparentBlack(const SkPaint* paint) {
        if (paint) {
            // FIXME: this is very conservative
            if (paint->getImageFilter() || paint->getColorFilter()) {
                return true;
            }

            // Unusual Xfermodes require us to process a saved layer
            // even with operations outisde the clip.
            // For example, DstIn is used by masking layers.
            // https://code.google.com/p/skia/issues/detail?id=1291
            // https://crbug.com/401593
            SkXfermode* xfermode = paint->getXfermode();
            SkXfermode::Mode mode;
            // SrcOver is ok, and is also the common case with a NULL xfermode.
            // So we should make that the fast path and bypass the mode extraction
            // and test.
            if (xfermode && xfermode->asMode(&mode)) {
                switch (mode) {
                    // For each of the following transfer modes, if the source
                    // alpha is zero (our transparent black), the resulting
                    // blended alpha is not necessarily equal to the original
                    // destination alpha.
                    case SkXfermode::kClear_Mode:
                    case SkXfermode::kSrc_Mode:
                    case SkXfermode::kSrcIn_Mode:
                    case SkXfermode::kDstIn_Mode:
                    case SkXfermode::kSrcOut_Mode:
                    case SkXfermode::kDstATop_Mode:
                    case SkXfermode::kModulate_Mode:
                        return true;
                        break;
                    default:
                        break;
                }
            }
        }
        return false;
    }

    Bounds popSaveBlock() {
        // We're done the Save block.  Apply the block's bounds to all control ops inside it.
        SaveBounds sb;
        fSaveStack.pop(&sb);

        while (sb.controlOps --> 0) {
            this->popControl(sb.bounds);
        }

        // This whole Save block may be part another Save block.
        this->updateSaveBounds(sb.bounds);

        // If called from a real Restore (not a phony one for balance), it'll need the bounds.
        return sb.bounds;
    }

    void pushControl() {
        fControlIndices.push(fCurrentOp);
        if (!fSaveStack.isEmpty()) {
            fSaveStack.top().controlOps++;
        }
    }

    void popControl(const Bounds& bounds) {
        fBounds[fControlIndices.top()] = bounds;
        fControlIndices.pop();
    }

    void updateSaveBounds(const Bounds& bounds) {
        // If we're in a Save block, expand its bounds to cover these bounds too.
        if (!fSaveStack.isEmpty()) {
            fSaveStack.top().bounds.join(bounds);
        }
    }

    // FIXME: this method could use better bounds
    Bounds bounds(const DrawText&) const { return fCurrentClipBounds; }

    Bounds bounds(const Clear&) const { return fCullRect; }             // Ignores the clip.
    Bounds bounds(const DrawPaint&) const { return fCurrentClipBounds; }
    Bounds bounds(const NoOp&)  const { return Bounds::MakeEmpty(); }    // NoOps don't draw.

    Bounds bounds(const DrawSprite& op) const {
        const SkBitmap& bm = op.bitmap;
        return Bounds::MakeXYWH(op.left, op.top, bm.width(), bm.height());  // Ignores the matrix.
    }

    Bounds bounds(const DrawRect& op) const { return this->adjustAndMap(op.rect, &op.paint); }
    Bounds bounds(const DrawOval& op) const { return this->adjustAndMap(op.oval, &op.paint); }
    Bounds bounds(const DrawRRect& op) const {
        return this->adjustAndMap(op.rrect.rect(), &op.paint);
    }
    Bounds bounds(const DrawDRRect& op) const {
        return this->adjustAndMap(op.outer.rect(), &op.paint);
    }
    Bounds bounds(const DrawImage& op) const {
        const SkImage* image = op.image;
        SkRect rect = SkRect::MakeXYWH(op.left, op.top, image->width(), image->height());

        return this->adjustAndMap(rect, op.paint);
    }
    Bounds bounds(const DrawImageRect& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmapRectToRect& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmapNine& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmap& op) const {
        const SkBitmap& bm = op.bitmap;
        return this->adjustAndMap(SkRect::MakeXYWH(op.left, op.top, bm.width(), bm.height()),
                                  op.paint);
    }
    Bounds bounds(const DrawBitmapMatrix& op) const {
        const SkBitmap& bm = op.bitmap;
        SkRect dst = SkRect::MakeWH(bm.width(), bm.height());
        op.matrix.mapRect(&dst);
        return this->adjustAndMap(dst, op.paint);
    }

    Bounds bounds(const DrawPath& op) const {
        return op.path.isInverseFillType() ? fCurrentClipBounds
                                           : this->adjustAndMap(op.path.getBounds(), &op.paint);
    }
    Bounds bounds(const DrawPoints& op) const {
        SkRect dst;
        dst.set(op.pts, op.count);

        // Pad the bounding box a little to make sure hairline points' bounds aren't empty.
        SkScalar stroke = SkMaxScalar(op.paint.getStrokeWidth(), 0.01f);
        dst.outset(stroke/2, stroke/2);

        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawPatch& op) const {
        SkRect dst;
        dst.set(op.cubics, SkPatchUtils::kNumCtrlPts);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawVertices& op) const {
        SkRect dst;
        dst.set(op.vertices, op.vertexCount);
        return this->adjustAndMap(dst, &op.paint);
    }

    Bounds bounds(const DrawPicture& op) const {
        SkRect dst = op.picture->cullRect();
        if (op.matrix) {
            op.matrix->mapRect(&dst);
        }
        return this->adjustAndMap(dst, op.paint);
    }

    Bounds bounds(const DrawPosText& op) const {
        const int N = op.paint.countText(op.text, op.byteLength);
        if (N == 0) {
            return Bounds::MakeEmpty();
        }

        SkRect dst;
        dst.set(op.pos, N);
        AdjustTextForFontMetrics(&dst, op.paint);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawPosTextH& op) const {
        const int N = op.paint.countText(op.text, op.byteLength);
        if (N == 0) {
            return Bounds::MakeEmpty();
        }

        SkScalar left = op.xpos[0], right = op.xpos[0];
        for (int i = 1; i < N; i++) {
            left  = SkMinScalar(left,  op.xpos[i]);
            right = SkMaxScalar(right, op.xpos[i]);
        }
        SkRect dst = { left, op.y, right, op.y };
        AdjustTextForFontMetrics(&dst, op.paint);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawTextOnPath& op) const {
        SkRect dst = op.path.getBounds();

        // Pad all sides by the maximum padding in any direction we'd normally apply.
        SkRect pad = { 0, 0, 0, 0};
        AdjustTextForFontMetrics(&pad, op.paint);

        // That maximum padding happens to always be the right pad today.
        SkASSERT(pad.fLeft == -pad.fRight);
        SkASSERT(pad.fTop  == -pad.fBottom);
        SkASSERT(pad.fRight > pad.fBottom);
        dst.outset(pad.fRight, pad.fRight);

        return this->adjustAndMap(dst, &op.paint);
    }

    Bounds bounds(const DrawTextBlob& op) const {
        SkRect dst = op.blob->bounds();
        dst.offset(op.x, op.y);
        return this->adjustAndMap(dst, &op.paint);
    }

    static void AdjustTextForFontMetrics(SkRect* rect, const SkPaint& paint) {
#ifdef SK_DEBUG
        SkRect correct = *rect;
#endif
        // crbug.com/373785 ~~> xPad = 4x yPad
        // crbug.com/424824 ~~> bump yPad from 2x text size to 2.5x
        const SkScalar yPad = 2.5f * paint.getTextSize(),
                       xPad = 4.0f * yPad;
        rect->outset(xPad, yPad);
#ifdef SK_DEBUG
        SkPaint::FontMetrics metrics;
        paint.getFontMetrics(&metrics);
        correct.fLeft   += metrics.fXMin;
        correct.fTop    += metrics.fTop;
        correct.fRight  += metrics.fXMax;
        correct.fBottom += metrics.fBottom;
        // See skia:2862 for why we ignore small text sizes.
        SkASSERTF(paint.getTextSize() < 0.001f || rect->contains(correct),
                  "%f %f %f %f vs. %f %f %f %f\n",
                  -xPad, -yPad, +xPad, +yPad,
                  metrics.fXMin, metrics.fTop, metrics.fXMax, metrics.fBottom);
#endif
    }

    // Returns true if rect was meaningfully adjusted for the effects of paint,
    // false if the paint could affect the rect in unknown ways.
    static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {
        if (paint) {
            if (paint->canComputeFastBounds()) {
                *rect = paint->computeFastBounds(*rect, rect);
                return true;
            }
            return false;
        }
        return true;
    }

    bool adjustForSaveLayerPaints(SkRect* rect, int savesToIgnore = 0) const {
        for (int i = fSaveStack.count() - 1 - savesToIgnore; i >= 0; i--) {
            if (!AdjustForPaint(fSaveStack[i].paint, rect)) {
                return false;
            }
        }
        return true;
    }

    // Adjust rect for all paints that may affect its geometry, then map it to identity space.
    Bounds adjustAndMap(SkRect rect, const SkPaint* paint) const {
        // Inverted rectangles really confuse our BBHs.
        rect.sort();

        // Adjust the rect for its own paint.
        if (!AdjustForPaint(paint, &rect)) {
            // The paint could do anything to our bounds.  The only safe answer is the current clip.
            return fCurrentClipBounds;
        }

        // Adjust rect for all the paints from the SaveLayers we're inside.
        if (!this->adjustForSaveLayerPaints(&rect)) {
            // Same deal as above.
            return fCurrentClipBounds;
        }

        // Map the rect back to identity space.
        fCTM->mapRect(&rect);

        // Nothing can draw outside the current clip.
        // (Only bounded ops call into this method, so oddballs like Clear don't matter here.)
        rect.intersect(fCurrentClipBounds);
        return rect;
    }

    // We do not guarantee anything for operations outside of the cull rect
    const SkRect fCullRect;

    // Conservative identity-space bounds for each op in the SkRecord.
    SkAutoTMalloc<Bounds> fBounds;

    // We walk fCurrentOp through the SkRecord, as we go using updateCTM()
    // and updateClipBounds() to maintain the exact CTM (fCTM) and conservative
    // identity-space bounds of the current clip (fCurrentClipBounds).
    unsigned fCurrentOp;
    const SkMatrix* fCTM;
    Bounds fCurrentClipBounds;

    // Used to track the bounds of Save/Restore blocks and the control ops inside them.
    SkTDArray<SaveBounds> fSaveStack;
    SkTDArray<unsigned>   fControlIndices;
};

}  // namespace SkRecords
    kTestRect, NULL));
SIMPLE_TEST_STEP(DrawBitmapNinePaint, drawBitmapNine(kTestBitmap, kTestIRect,
    kTestRect, &kTestPaint));
SIMPLE_TEST_STEP(DrawSprite, drawSprite(kTestBitmap, 0, 0, NULL));
SIMPLE_TEST_STEP(DrawSpritePaint, drawSprite(kTestBitmap, 0, 0, &kTestPaint));
SIMPLE_TEST_STEP(DrawText, drawText(kTestText.c_str(), kTestText.size(),
    0, 1, kTestPaint));
SIMPLE_TEST_STEP(DrawPosText, drawPosText(kTestText.c_str(),
    kTestText.size(), kTestPoints2, kTestPaint));
SIMPLE_TEST_STEP(DrawTextOnPath, drawTextOnPath(kTestText.c_str(),
    kTestText.size(), kTestPath, NULL, kTestPaint));
SIMPLE_TEST_STEP(DrawTextOnPathMatrix, drawTextOnPath(kTestText.c_str(),
    kTestText.size(), kTestPath, &kTestMatrix, kTestPaint));
SIMPLE_TEST_STEP(DrawData, drawData(kTestText.c_str(), kTestText.size()));
SIMPLE_TEST_STEP(BeginGroup, beginCommentGroup(kTestText.c_str()));
SIMPLE_TEST_STEP(AddComment, addComment(kTestText.c_str(), kTestText.c_str()));
SIMPLE_TEST_STEP(EndGroup, endCommentGroup());

///////////////////////////////////////////////////////////////////////////////
// Complex test steps

// Save/restore calls cannot be in isolated simple test steps because the test
// cases that use SkPicture require that save and restore calls be balanced.
static void SaveMatrixStep(SkCanvas* canvas,
                           skiatest::Reporter* reporter,
                           CanvasTestStep* testStep) {
    int saveCount = canvas->getSaveCount();
    canvas->save(SkCanvas::kMatrix_SaveFlag);
    canvas->clipRegion(kTestRegion);
    canvas->translate(SkIntToScalar(1), SkIntToScalar(2));
    canvas->restore();
Example #25
0
/*----------------------------------------------------------------*
 * checkArgs:                                                     *
 *   Check command line parameters                                *
 *----------------------------------------------------------------*/
static void checkArgs(int argc, char *argv[]) {

  strcpy(prgName, (char *)argv[0]); 
  strcpy(name, prgName); 

  while (--argc > 0) {
    ++argv;    /* next parameter. */
    match = 0; /* no match so far. */

    if (strcmp((char *)argv[0],"-region")==0) {
      if ((argc-1)>0 && (*(argv+1))[0] != '-') {
	--argc;
	++argv;
	strcpy(rpName, (char *)argv[0]);     
      } else
	strcat(rpName, dotEnd);
      printf("Region profiling to output file %s.\n", rpName);
      match = 1;
      makeRP = 1;
    } 

    if (strcmp((char *)argv[0],"-stack")==0) {
      if ((argc-1)>0 && (*(argv+1))[0] != '-') {
	--argc;
	++argv;
	strcpy(stackName, (char *)argv[0]);     
      } else
	strcat(stackName, dotEnd);
      printf("Stack profiling to output file %s.\n", stackName);
      match = 1;
      makeSP = 1;
    } 

    if (strcmp((char *)argv[0],"-object")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a region number. */
	if ((regionNo = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the region number after the -object switch.\n");
	  printUsage();
	}
      } else {
	printf("No region number after the -object switch.\n");
	printUsage();
      }
    
      if ((argc-1)>0 && (*(argv+1))[0] != '-') {
	--argc;
	++argv;
	strcpy(objName, (char *)argv[0]);     
      } else {
	sprintf(tempStr, "%d", regionNo);
	strcat(objName, tempStr);
	strcat(objName, dotEnd);
      }
      printf("Object profiling on region %d to output file %s.\n", regionNo, objName);
      match = 1;
      makeObjP = 1;
    } 

    if (strcmp((char *)argv[0],"-findPrgPoint")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a number. */
	if ((prgPoint = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the number after the -findPrgPoint switch.\n");
	  printUsage();
	}
      } else {
	printf("No number after the -findPrgPoint switch.\n");
	printUsage();
      }
      printf("Find program point %d.\n", prgPoint);
      findPrgPoint = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-noOfBands")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a number. */
	if ((noOfBands = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the number after the -noOfBands switch.\n");
	  printUsage();
	}
      } else {
	printf("No number after the -noOfBands switch.\n");
	printUsage();
      }
      noOfBands = min(noOfBands, MAX_NO_OF_BANDS);
      printf("Show %d bands on graph.\n", noOfBands);
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-fixedYRange")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a number. */
	if ((fixedYRange = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the number after the -fixedYRange switch.\n");
	  printUsage();
	}
      } else {
	printf("No number after the -fixedYRange switch.\n");
	printUsage();
      }
      if (fixedYRange < 0)
	printf("Do not use fixed range on y-axis.\n");
      else
	printf("Use %d bytes as fixed range on y-axis.\n", fixedYRange);
      match = 1;
    } 
    
    if (strcmp((char *)argv[0], "-print")==0) {
      printf("Print profile\n");
      printProfile = 1;
      match = 1;
    } 
          
    if (strcmp((char *)argv[0], "-interactive")==0) {
      printf("Interactive\n");
      match = 1;
      interact = 1;
    } 

    if ((strcmp((char *)argv[0], "-h")==0) ||
	(strcmp((char *)argv[0], "-help")==0)) {
      printf("Help\n");
      match = 1;
      printUsage();
    }

    if (strcmp((char *)argv[0],"-pregion")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a region number. */
	if ((regionNo2 = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the region number after the -pregion switch.\n");
	  printUsage();
	}
      } else {
	printf("No region number after the -pregion switch.\n");
	printUsage();
      }
      printf("Print region %d.\n", regionNo2);
      match = 1;
      printRegion = 1;
    }

    if (strcmp((char *)argv[0],"-source")==0) {
      if ((argc-1)>0 && (*(argv+1))[0] != '-') {
	--argc;
	++argv;
	strcpy(logName, (char *)argv[0]);     
      } else {
	printf("No filename after the -source switch.\n");
	printUsage();
      }
      printf("Using input file %s.\n", logName);
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-name")==0) {
      if ((argc-1)>0 && (*(argv+1))[0] != '-') {
	--argc;
	++argv;
	strcpy(name, (char *)argv[0]);     
      } else {
	printf("No name after the -name switch.\n");
	printUsage();
      }
      printf("Using name %s.\n", name);
      match = 1;
    } 

    if (strcmp((char *)argv[0], "-stat")==0) {
      printf("Print some statistics\n");
      match = 1;
      printSomeStat = 1;
    }

    if (strcmp((char *)argv[0],"-eps")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a width. */
	if ((epsfwidth = atof((char *)argv[0])) == 0) {
	  printf("Something wrong with width after the -eps switch.\n");
	  printUsage();
	}
	if (--argc > 0 && (*++argv)[0]) { /* in, mm or pt. */
	  if (strcmp((char *)argv[0], "in") == 0)
	    epsfwidth *= 72.0;
	  else if (strcmp((char *)argv[0], "mm") == 0)
	    epsfwidth = (float) (epsfwidth*2.834646);
	  else if (strcmp((char *)argv[0], "pt") != 0) {
	    printf("No/wrong in, mm or pt after -eps width switch\n");
	    printUsage();
	  }
	} else {
	  printf("No in, mm or pt after -eps width switch\n");
	  printUsage();
	}
      } else {
	printf("No width after -eps switch.\n");
	printUsage();
      }
      printf("Using encapsulated postscript with width %0.0f pt.\n", epsfwidth);
      eflag = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-comment")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a time. */
	if ((commenttime = atof((char *)argv[0])) == 0) {
	  printf("Something wrong with time after the -comment switch.\n");
	  printUsage();
	}
	if (--argc > 0 && (*++argv)[0]) { /* comment string. */
	  addComment(commenttime, (char *)argv[0]);
	} else {
	  printf("No comment string after -comment time switch\n");
	  printUsage();
	}
      } else {
	printf("No time after -comment switch.\n");
	printUsage();
      }
      printf("Inserting comment %s at time %4.2f.\n", (char*)argv[0], commenttime);
      cflag = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-mark")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a time. */
	if ((commenttime = atof((char *)argv[0])) == 0) {
	  printf("Something wrong with time after the -mark switch.\n");
	  printUsage();
	}
	else {
	  addMark(commenttime);
	}
      } else {
	printf("No time after -mark switch.\n");
	printUsage();
      }
      printf("Inserting mark at time %4.2f.\n", commenttime);
      mflag = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0], "-vert")==0) {
      printf("Show vertical lines in graph.\n");
      yflag = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0], "-sortByTime")==0) {
      printf("Chose sampleMax samples equally distributed over sample numbers.\n");
      sortOpt = TAKE_BY_SAMPLE_NO;
      match = 1;
    } 

    if (strcmp((char *)argv[0], "-sortBySize")==0) {
      printf("Chose the sampleMax largest samples.\n");
      sortOpt = TAKE_BY_SIZE;
      match = 1;
    } 

    if (strcmp((char *)argv[0], "-useTickNo")==0) {
      printf("Use tick numbers on x-axis instead of elapsed time.\n");
      useTickNo = 1;
      match = 1;
    } 

    if (strcmp((char *)argv[0],"-sampleMax")==0) {
      if (--argc > 0 && (*++argv)[0]) { /* Is there a number. */
	if ((SampleMax = atoi((char *)argv[0])) == 0) {
	  printf("Something wrong with the number after the -sampleMax switch.\n");
	  printUsage();
	}
      } else {
	printf("No number after the -sampleMax switch.\n");
	printUsage();
      }
      printf("Using %d samples.\n", SampleMax);
      match = 1;
    } 

    if (match == 0) {
      printf("Something wrong with the switches, maybe an unknown switch...\n");
      printUsage();
    }
  }

  return;
}
Example #26
0
File: c.c Project: AlwaysLately/c
int main (int argc, const char *argv[]) {
	// Get the current directory
	char cwd[1024];
	if (!getcwd(cwd, sizeof(cwd))) {
		perror("getcwd() error");
	}

	int numargs, all = 0, asc = 0, desc = 0, push = 0, uk = 0, help = 0, current = 0;
	const char *c;

	numargs = argc;

	// TODO: Convert to getopt
	while (--numargs > 0) {
		c = argv[numargs];

		if (!strcmp(argv[numargs], "all"))
			all = 1;
		else if (!strcmp(argv[numargs], "-h") || !strcmp(argv[numargs], "--help"))
			help = 1;
		else if (!strcmp(argv[numargs], "."))
			current = 1;
		else if (!strcmp(argv[numargs], "-p") || !strcmp(argv[numargs], "--push"))
			push = 1;
		else if (!strcmp(argv[numargs], "-"))
			desc = 1;
		else if (!strcmp(argv[numargs], "+"))
			asc = 1;
		else
			uk++;
	}

	int args;
	args = argc;

	if (uk > 2) {
		printUsage();
		return EXIT_FAILURE;
	}

	if (args == 1) {
			printUsage();
			return EXIT_FAILURE;
	} else if (args == 2) {
		// Show the help menu
		if (help) {
			printUsage();
			return EXIT_FAILURE;
		}
		// Show all the files
		else if (all) {
			makeDir(cwd);
			printFiles(cwd);
		}
		// Show comment for the current directory
		else if (current) {
			// checkComment(argv[1], cwd);
			printCurrentComment(cwd);
		}
		// Show comment for the entered file
		else {
			// char *file = argv[1];
			makeDir(cwd);
			checkComment(argv[1], cwd);
		}
	} else if (args == 3) {
		if (current) {                               // Add comment to the current directory
			// char *file;
			// file = "CURRENT";
			addComment(argv[1], cwd, argv[2], false);
		} else if (all && desc) {                    // Print all files in descending order
			makeDir(cwd);
			printAllOrder(cwd, true);
		} else if (all && asc) {                     // Print all files in ascending order
			makeDir(cwd);
			printAllOrder(cwd, false);
		} else {                                     // Add comment to to given file
			makeDir(cwd);
			addComment(argv[1], cwd, argv[2], false);
		}
	} else if (args == 4) {
		if (current && push) { // Push comment to the current directory
			// Add a comment to the given filename
			addComment(argv[1], cwd, argv[3], true);
		} else if (push) {       // Push comment to given file
			makeDir(cwd);
			addComment(argv[1], cwd, argv[3], true);
		}
	} else {
		// Not certain
		printUsage();
	}
	return EXIT_SUCCESS;
}