コード例 #1
0
ファイル: stars.c プロジェクト: doolse/wingsos
void main() {
	int i,RcvId;
	void *msg;
	int screen;
	
	chan = makeChan();
	screen = open("/dev/screen",O_PROC, chan);
	if (screen == -1) {
		perror("Shit!");
		exit(1);
	}
	retexit(1);
	scrSwitch(screen, SCRO_This);
	while(1) {
		RcvId = recvMsg(chan, &msg);
		switch (* (int *)msg) {
		case PMSG_GetScr: 
				VideoMode();
				InitializeStars();
				EditPalette();
				getRaster();
				check=1;
				initKey();
				setRaster(VBIRute,250);
				break;
		case PMSG_LoseScr:
				freeRaster();
				scrSwitch(screen, SCRO_Next); 
				break;
		}
		replyMsg(RcvId,0);
	}

}
コード例 #2
0
ファイル: taskbar.c プロジェクト: doolse/wingsos
void listener() {
  int channel,rcvid,returncode;
  msgpass * msg = malloc(sizeof(msgpass));

  channel = makeChanP("/sys/taskbar");
  
  while(1) {
    rcvid = recvMsg(channel,(void *)&msg);

    switch(msg->code) {
      case TSKM_KILLED:
      case TSKM_NEWITEM:
      case TSKM_MINIMIZED:
      case TSKM_INFOCUS:
      case TSKM_INBLUR:
        newThread(updateitem,STACK_DFL,msg);
        returncode = 0;
      break;
      case IO_OPEN:
        if(*(int *) (((char *)msg)+6) & (O_PROC|O_STAT))
          returncode = makeCon(rcvid,1);
        else
          returncode = -1;
      break;
    }
    replyMsg(rcvid,returncode);
  }
}
コード例 #3
0
ファイル: irc.c プロジェクト: doolse/wingsos
void outThread(int *tlc) {
    FILE *stream;
    int RcvId;
    char *msg;
    char **upto;
    int count,type;
    int lastone=0;
    int ch;
    stream = fdopen(*tlc,"wb");

    while (1) {
        RcvId = recvMsg(channel, (void *)&msg);
        type = * (int *)msg;
        if (type == SRVMSG) {
            count = * (int *)(msg+2);
            upto = (char **)(msg+4);
            while (count--)
                fputs(*upto++,stream);
            fprintf(stream,"\n");
            fflush(stream);
        } else if (type == KEYINP) {
            ch = * (int *)(msg+2);
            if (ch == '\b' || ch == 0x7f) {
                putchar('\b');
                putchar(' ');
                putchar('\b');
                --inpx;
            } else {
                putchar(ch);
                ++inpx;
            }
            con_update();
        } else if (type == CLRINP) {
            inpx=0;
            con_gotoxy(inpx,inpy);
            con_clrline(LC_End);
            con_update();
        } else {

            con_gotoxy(0,22);
            if (lastone == SCRMSG)
                putchar('\n');
            vprintf(* (char **)(msg+2), (void *)(msg+6));
            lastone = type;
            con_gotoxy(inpx,inpy);
            con_update();
        }
        replyMsg(RcvId,0);
    }

}
コード例 #4
0
ファイル: start.c プロジェクト: doolse/wingsos
void main(int argc, char * argv[]) {
  int channel, rcvid, returncode;

  if(open("/sys/addressbook", O_PROC) != -1) {
    fprintf(stderr, "The addressbook service is already running.\n");
    exit(EXIT_FAILURE);
  }

  xmlfile = XMLloadFile(fpathname("data/addressbook.xml", getappdir(), 1));
  xmlelem = XMLgetNode(xmlfile, "xml");

  channel = makeChanP("/sys/addressbook");

  retexit(1);

  while(1) {
    rcvid = recvMsg(channel,(void *)&msg); 

    switch(msg->code) {
      case GET_ATTRIB:
        returncode = getattrib();
      break;
      case GET_ALL_LIST:
        returncode = getalllist();
      break;
      case MAKE_ENTRY:
        returncode = makeentry();
      break;
      case PUT_ATTRIB:
        returncode = putattrib();
      break;
      case DEL_ENTRY:
        returncode = deleteentry();
      break;
      case DEL_ATTRIB:
        returncode = deleteattrib();
      break;
      case IO_OPEN:
        if(*(int *)( ((char*)msg) +6) & (O_PROC|O_STAT))
          returncode = makeCon(rcvid, 1);
        else 
          returncode = -1;
      break;
    }

    replyMsg(rcvid, returncode);    
  }
} 
コード例 #5
0
void
HTGAvatarView::postTweet()
{
	std::string replyMsg( "" );
	std::string replyId( "" );
	std::string postMsg = urlEncode(fMessage->Text());
	if( twitObj->statusUpdate(postMsg, replyId) )  {
		printf( "Status update: OK\n" );
		twitObj->getLastWebResponse(replyMsg);
		int errorStart = replyMsg.find("<error>");
		int errorEnd = replyMsg.find("<\error>");
		if(errorStart-errorEnd > 0)
			HTGErrorHandling::displayError(replyMsg.substr(errorStart, errorEnd-errorStart).c_str());
		else { // Send "status updated" to parent, so we can refresh timelines
			BMessage* statusUpdated = new BMessage(STATUS_UPDATED);
			statusUpdated->AddString("content", fMessage->Text());
			fParent->MessageReceived(statusUpdated);
		}
	}
コード例 #6
0
/********************************************************************
  parseCmds loops through a list of hear functions and tries to match queries 
  and execute reply response functions

********************************************************************/
void ArduinoSlackBot::parseCmds() {

  struct slre_cap matches[4];

  //you must reference the bot to get a response
  if (slre_match(botID, slackMsg.text, strlen(slackMsg.text), matches, 4, 0) > 0) {
    PRINTLN(ESP.getFreeHeap());

    for (int i=0; i <= qrListLength-1; i++) {
     
      //match the provided regex
      if (slre_match(qrList[i]->query, slackMsg.text, strlen(slackMsg.text), matches, 4, 0) > 0) {  
        PRINTLN(matches[0].ptr);
        qrList[i]->resp(); //execute provided bot response
        return; //stop matching if match is found
      } 
    }
    replyMsg(failMsg);
  }
  
}
コード例 #7
0
void
HTGTimeLineView::savedSearchCreateSelf()
{
	/*Save search to twitter*/
	std::string query(::htmlFormatedString(Name()));
	twitCurl *saveObj = new twitCurl();
	saveObj->getOAuth() = twitObj->getOAuth().clone();
	saveObj->savedSearchCreate(query);
	std::string replyMsg(" ");
	saveObj->getLastWebResponse(replyMsg);

	/*Parse result*/
	size_t pos = 0;
	const char *idTag = "<id>";
	pos = replyMsg.find(idTag, pos);
	if(pos != std::string::npos) {
		int start = pos+strlen(idTag);
		int end = replyMsg.find("</id>", start);
		std::string searchID(replyMsg.substr(start, end-start));
		setSearchID(atoi(searchID.c_str()));
	}
	delete saveObj;
}
コード例 #8
0
ファイル: data_server.cpp プロジェクト: Tushar-Naik/hpcl
void
DataServer::on_data_received(
            const SocketPtr &in_socket, const MemInfo &in_msg ) {
    const DataServiceMessage *pMsg
            = reinterpret_cast<const DataServiceMessage *>(
                                    in_msg.get_data());
    DataServiceMessage reply( DATA_SERVICE_GENERAL_REPLY );
    bool status = false;
    switch( pMsg->m_header.m_type ) {
        case DataMessageType::DATA_SERVICE_REGISTER:
        {
            std::string buf = pMsg->m_data;
            std::istringstream ifs( buf );
            boost::archive::text_iarchive ia( ifs );
            ServiceRequestData data;
            ia & data;
            status = on_service_register_request(
                                        data.m_service_name,
                                        data.m_hostname, data.m_port );
            break;
        }
        case DataMessageType::DATA_SERVICE_UNREGISTER:
        {
            std::string buf = pMsg->m_data;
            std::istringstream ifs( buf );
            boost::archive::text_iarchive ia( ifs );
            ServiceRequestData data;
            ia & data;
            status = on_service_unregister_request(
                                        data.m_service_name,
                                        data.m_hostname, data.m_port );
            break;
        }
        case DataMessageType::DATA_SERVICE_INFO_REQUEST:
        {
            std::string buf = pMsg->m_data;
            std::istringstream ifs( buf );
            boost::archive::text_iarchive ia( ifs );
            ServiceRequestData data;
            ia & data;
            ServiceInfoPtr info;
            status = on_service_info_request( data.m_service_name, info );
            if( info ) {
                std::ostringstream sout;
                boost::archive::text_oarchive oa(sout);
                oa & info;
                std::strncpy( reply.m_data,
                                sout.str().c_str(), sout.str().size());
            }
            reply.m_header.m_type =  DATA_SERVICE_INFO_REPLY;
            break;
        }
        default:
        {
        }
    }
    reply.m_status = status;
    MemInfo replyMsg( reinterpret_cast<char *>( &reply ),
                        sizeof( DataServiceMessage ) );
    in_socket->send_data( replyMsg );
}
コード例 #9
0
ファイル: taskbar.c プロジェクト: doolse/wingsos
void main(int argc, char * argv[]) {
  void *appl;
  int type,rcvid,icocol;
  char * msg;
  void * but;

  rcvid = open("/sys/taskbar",O_PROC);
  if(rcvid != -1) {
    printf("Taskbar is already running!\n");
    exit(1);
  }

  appchannel = makeChan();
  appl = JAppInit(NULL,appchannel);

  //default position is at top of screen
  position = TSKM_ONTOP;
  if(argc > 1) {
    if(!strcmp(argv[1],"left"))
      position = TSKM_ONLEFT;
    else if(!strcmp(argv[1],"right"))
      position = TSKM_ONRIGHT;
    else if(!strcmp(argv[1],"top"))
      position = TSKM_ONTOP;
    else if(!strcmp(argv[1],"bottom"))
      position = TSKM_ONBOTTOM;
  }

  taskbar = JCntInit(NULL);
  if(position == TSKM_ONTOP || position == TSKM_ONBOTTOM) {
    ((JCnt*)taskbar)->Orient = JCntF_LeftRight;
    JWSetBounds(taskbar,0,0,0,16);
  } else {
    ((JCnt*)taskbar)->Orient = JCntF_TopBottom;
    JWSetBounds(taskbar,0,0,16,0);
  }

  JWndSetProp(taskbar);
  JAppSetMain(appl,taskbar);

  JWinShow(taskbar);
  newThread(makecbutton,STACK_DFL,NULL);
  retexit(0);

  newThread(listener,STACK_DFL,NULL);

  while(1) {
    rcvid = recvMsg(appchannel,(void *)&msg);
    type = *(int *)msg;

    //printf("got appchannel msg: #%d\n",type);

    switch(type) {
      case WIN_EventRecv:
        JAppDrain(appl);
      break;
      case REFRESH:
        JWinLayout(taskbar);
      break;
      case SETCOL:
        but    = *(void **)(msg+2);
        icocol = *(int *)(msg+6);

        memset(((JBmp*)but)->Cols,icocol,4);
        /*
        ((JBmp*)but)->Cols[0] = icocol;
        ((JBmp*)but)->Cols[1] = icocol;
        ((JBmp*)but)->Cols[2] = icocol;
        ((JBmp*)but)->Cols[3] = icocol;
        */
        JWReDraw(but);
      break;
    }
    replyMsg(rcvid,0);
  }
}
コード例 #10
0
void ChatManager::HandleChannelJoinMessage(MsgEntry *me, Client *client)
{
    psChannelJoinMessage msg(me);
    msg.channel.Trim();
    if(msg.channel.Length() == 0)
        return;
    if(msg.channel.Length() > 30)
        return;

    csString nocaseChannelName = msg.channel;
    nocaseChannelName.Downcase();
    // Search is case-insensitive
    uint32_t channelID = channelIDs.Get(nocaseChannelName, 0);
    if(channelID == 0)
    {
        uint32_t start = channelID = nextChannelID++;
        while(!channelSubscribers.GetAll(channelID).IsEmpty() && nextChannelID != start - 1)
        {
            channelID = nextChannelID++;
            if(nextChannelID == 0)
                nextChannelID++;
        }
        if(nextChannelID == start - 1)
        {
            psserver->SendSystemError(client->GetClientNum(), "Server channel limit reached!");
            return;
        }

        channelIDs.PutUnique(nocaseChannelName, channelID);
        channelNames.PutUnique(channelID, nocaseChannelName);
    }
    else
    {
        csArray<uint32_t> subscribed = channelSubscriptions.GetAll(client->GetClientNum());
        bool found = false;
        for(size_t i = 0; i < subscribed.GetSize(); i++)
        {
          if(subscribed[i] == channelID)
              found = true;
        }
        if(found)
        {
          psserver->SendSystemError(client->GetClientNum(), "You have already joined this channel.");
          return;
        }
    }
    if(channelSubscriptions.GetAll(client->GetClientNum()).GetSize() > 10)
    {
        psserver->SendSystemError(client->GetClientNum(), "You have joined more than 10 channels, please leave some channels first.");
        return;
    }
    csString reply;
    reply.Format("Welcome to the %s channel! %d players in this channel.", channelNames.Get(channelID, "").GetData(), (int)channelSubscribers.GetAll(channelID).GetSize());

    channelSubscriptions.Put(client->GetClientNum(), channelID);
    channelSubscribers.Put(channelID, client->GetClientNum());

    psserver->SendSystemInfo(client->GetClientNum(), reply);
    psChannelJoinedMessage replyMsg(client->GetClientNum(), channelNames.Get(channelID, "").GetData(), channelID);
    replyMsg.SendMessage();
}
コード例 #11
0
status_t
updateTimeLineThread(void *data)
{
	//Could not figure out how to update a BListItem with a child view (BTextView).
	//Could be a bug in Haiku APIs. After hours of investigation without any
	//result, I just don't care anymore. Reallocating all HTGTweetItem on update.
	HTGTimeLineView *super = (HTGTimeLineView*)data;
	
	HTGListView *listView = super->listView;
	bool saveTweets = super->saveTweets;
	
	int32 TYPE = super->TYPE;
	twitCurl *twitObj = super->twitObj;
	HTTimelineParser *timeLineParser;
	std::string replyMsg(" ");
	
	HTGTweetItem *mostRecentItem = NULL;
	HTTweet *mostRecentTweet = NULL;
	HTTweet *currentTweet = NULL;
	
	BList *newList = new BList();
	
	switch(TYPE) {
		case TIMELINE_HOME:
			twitObj->timelineHomeGet();
			break;
		case TIMELINE_FRIENDS:
			twitObj->timelineFriendsGet();
			break;
		case TIMELINE_MENTIONS:
			twitObj->mentionsGet();
			break;
		case TIMELINE_PUBLIC:
			twitObj->timelinePublicGet();
			break;
		case TIMELINE_USER:
			twitObj->timelineUserGet(true, true, 25); // TODO: is this correct?
			break;
		case TIMELINE_SEARCH:
			twitObj->search(htmlFormatedString(super->Name()));
			break;
		case TIMELINE_HDD:
			return B_OK;
			break;
		default:
			twitObj->timelinePublicGet();
	}
	
	twitObj->getLastWebResponse(replyMsg);
	
	#ifdef DEBUG_ENABLED
		std::cout << "HTGTimelineView: web response:" << std::endl;
	 	std::cout << replyMsg << std::endl;
	 #endif

	if(replyMsg.length() < 10) {
		super->errorCount++;
		if(super->errorCount < kMaximumRetries) {
			super->waitingForUpdate = true;
			#ifdef DEBUG_ENABLED
			std::cout << "No connection. Retry " << super->errorCount << "/" << kMaximumRetries << std::endl;
			std::string error; twitObj->getLastCurlError(error);
			std::cout << "Curl error: " << error << std::endl;
			#endif
			usleep(5000 * pow(super->errorCount,2));
			return updateTimeLineThread(super);
		}
		else
			replyMsg= string("error");
	}
	else
		super->errorCount = 0;
	
	if(TYPE == TIMELINE_SEARCH)
		timeLineParser = new HTSearchParser();
	else
		timeLineParser = new HTTimelineParser();

	try {
		timeLineParser->Parse(replyMsg);
	}
	catch( ... ) {
		std::cout << super->Name() << ": Error while parsing data." << std::endl;
		delete timeLineParser;
		timeLineParser = NULL;
		return B_OK;
	}
	
	if(timeLineParser->Tweets()->CountItems() < 1) {//timeLineParser failed, return!
		std::cout << super->Name() << ": Parser didn't find any tweets." << std::endl;
		delete timeLineParser;
		timeLineParser = NULL;
		return B_OK;
	}
	
	bool initialLoad = (listView->FirstItem() == NULL && super->unhandledList->FirstItem() == NULL);
	
	if(!initialLoad && listView->FirstItem() != NULL) {
		mostRecentItem = (HTGTweetItem *)listView->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
		currentTweet = (HTTweet *)timeLineParser->Tweets()->ItemAt(0);
	
		/*If we are up to date: redraw, clean up and return - Note this should not be done here,
		rather as a result of some BPulse I guess...*/
		if(!(*mostRecentTweet < *currentTweet)) {
			if(listView->LockLooper()) {
				for(int i = 0; i < listView->CountItems(); i++)
					listView->InvalidateItem(i); //Update date
				listView->UnlockLooper();
			}	
			delete timeLineParser;
			timeLineParser = NULL;
			return B_OK;
		}
	}
	
	/*Check to see if there is some unhandled tweets*/
	if(!super->unhandledList->IsEmpty()) {
		mostRecentItem = (HTGTweetItem *)super->unhandledList->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
	}
	
	for (int i = 0; i < timeLineParser->Tweets()->CountItems(); i++) {
		currentTweet = (HTTweet *)timeLineParser->Tweets()->ItemAt(i);
		bool addItem = initialLoad;
		if(!initialLoad) {
			if(mostRecentTweet != NULL)
				addItem = (*mostRecentTweet < *currentTweet);
			else
				addItem = true;
		}
		if(addItem) {
			/*Make a copy, download bitmap and add it to newList*/
			HTTweet *copiedTweet = new HTTweet(currentTweet);
			copiedTweet->downloadBitmap();
			newList->AddItem(new HTGTweetItem(copiedTweet));
			
			if(!initialLoad && super->wantsNotifications) { //New tweet arrived, send notification
				super->sendNotificationFor(copiedTweet);
			}
			if(saveTweets)
				HTStorage::saveTweet(copiedTweet);
		}
		else
			break;
	}
	
	super->unhandledList->AddList(newList, 0);
	
	/*Try to lock listView*/
	if(!listView->LockLooper()) {
		/*Not active view: return*/
		super->waitingForUpdate = true;
		delete timeLineParser;
		timeLineParser = NULL;
		delete newList;
		
		return B_OK;
	}
	
	/*Add the tweets to timeline*/
	super->addUnhandledTweets();
			
	/*Cleanup*/
	super->waitingForUpdate = false;
	listView->UnlockLooper();
	delete timeLineParser;
	timeLineParser = NULL;
	delete newList;

	return B_OK;
}
コード例 #12
0
ファイル: MainWidget.cpp プロジェクト: SvOlli/SLART
void MainWidget::request( QTcpSocket *id,
                          const QHttpRequestHeader &header )
{
   mpMessageBuffer->addItem( header.toString() );
   while( mpMessageBuffer->count() > 200 )
   {
      QListWidgetItem *item = mpMessageBuffer->takeItem( 0 );
      if( item )
      {
         delete item;
      }
   }
   mpMessageBuffer->scrollToBottom();

#if 0
   if( header.path() == "/favicon.ico" )
   {
      QFile file( ":/favicon.ico" );
      file.open( QIODevice::ReadOnly | QIODevice::Text );
      emit response( id,
                     QHttpResponseHeader( 200, "OK" ),
                     file.readAll() );
      file.close();
      return;
   }
#endif
   if( header.path() == "/wait" )
   {
      mDelayList.append( id );
      return;
   }
   if( header.path() == "/get" )
   {
      QString reply( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
                     "<response>\n"
                     " <reply>%1</reply>\n"
                     " <artist>%2</artist>\n"
                     " <title>%3</title>\n"
                     " <album>%4</album>\n"
                     " <track>%5</track>\n"
                     "</response>\n" );
      QByteArray replyMsg( reply.arg( Qt::escape( QString::fromUtf8(mMsg.constData()) ),
                                      Qt::escape( mTrackInfo.mArtist ),
                                      Qt::escape( mTrackInfo.mTitle ),
                                      Qt::escape( mTrackInfo.mAlbum ),
                                      QString::number(mTrackInfo.mTrackNr) ).toUtf8() );
      emit response( id,
                     QHttpResponseHeader( 200, "OK XML" ),
                     replyMsg );
      return;
   }
   QString html("<html>\n<head>\n<title>%1</title>\n"
         "<meta http-equiv='content-type' content='text/html; charset=UTF-8'>\n"
         "<link rel='shortcut icon' href='/favicon.ico' type='image/x-icon'>\n"
         "<script src='ajax.js' type='text/javascript'>\n"
         "</script>\n"
         "</head>\n<body>\n"
         "<h1>%2</h1>\n"
         "<p>HTTP Request: %3 %4</p>\n"
         "<table border='1'>\n"
         "<tr valign='top'><td>Artist:</td><td><textarea cols='80' rows='1' name='artist' wrap='off' readonly></textarea></td></tr>\n"
         "<tr valign='top'><td>Title:</td><td><textarea cols='80' rows='1' name='title' wrap='off' readonly></textarea></td></tr>\n"
         "<tr valign='top'><td>Album:</td><td><textarea cols='80' rows='1' name='album' wrap='off' readonly></textarea></td></tr>\n"
         "<tr valign='top'><td>Track:</td><td><textarea cols='80' rows='1' name='track' wrap='off' readonly></textarea></td></tr>\n"
         "<tr valign='top'><td>Reply:</td><td><textarea cols='80' rows='5' name='reply' wrap='off' readonly></textarea></td></tr>\n"
         "<tr valign='top'><td>Status:</td><td><input name='status' size='12' readonly>"
         "<input type='button' value='refresh' onclick='loadFields();'></td></tr>\n"
         "</table></body></html>\n"
         );
   html = html.arg( QApplication::organizationName() + ": " + QApplication::applicationName(),
                    QApplication::organizationName() + ": " + QApplication::applicationName(),
                    header.method(),
                    header.path() );

   emit response( id,
                  QHttpResponseHeader( 200, "OK" ),
                  html.toUtf8() );
}
コード例 #13
0
ファイル: MsgCore.c プロジェクト: sssemil/cjdns
static Iface_DEFUN incoming(struct Message* msg, struct Iface* interRouterIf)
{
    struct MsgCore_pvt* mcp =
        Identity_containerOf(interRouterIf, struct MsgCore_pvt, pub.interRouterIf);

    struct Address addr = { .padding = 0 };
    struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
    Message_shift(msg, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
    Bits_memcpy(addr.ip6.bytes, hdr->ip6, 16);
    Bits_memcpy(addr.key, hdr->publicKey, 32);
    addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
    addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);

    Dict* content = NULL;
    uint8_t* msgBytes = msg->bytes;
    int length = msg->length;
    //Log_debug(mcp->log, "Receive msg [%s] from [%s]",
    //    Escape_getEscaped(msg->bytes, msg->length, msg->alloc),
    //    Address_toString(&addr, msg->alloc)->bytes);
    //
    BencMessageReader_readNoExcept(msg, msg->alloc, &content);
    if (!content) {
        char* esc = Escape_getEscaped(msgBytes, length, msg->alloc);
        Log_debug(mcp->log, "DROP Malformed message [%s]", esc);
        return NULL;
    }

    int64_t* verP = Dict_getIntC(content, "p");
    if (!verP) {
        Log_debug(mcp->log, "DROP Message without version");
        return NULL;
    }
    addr.protocolVersion = *verP;

    String* q = Dict_getStringC(content, "q");

    if (!Defined(SUBNODE)) {
        String* txid = Dict_getStringC(content, "txid");
        Assert_true(txid);
        if (q) {
            if (txid->bytes[0] == '0') {
                Log_debug(mcp->log, "DROP query which begins with 0 and is for old pathfinder");
                return NULL;
            }
        } else {
            if (txid->bytes[0] != '1') {
                Log_debug(mcp->log, "DROP reply which does not begin with 1");
                return NULL;
            }
            String* newTxid = String_newBinary(NULL, txid->len - 1, msg->alloc);
            Bits_memcpy(newTxid->bytes, &txid->bytes[1], txid->len - 1);
            Dict_putStringC(content, "txid", newTxid, msg->alloc);
            txid = newTxid;
        }
    }

    if (q) {
        return queryMsg(mcp, content, &addr, msg);
    } else {
        return replyMsg(mcp, content, &addr, msg);
    }
}

struct MsgCore* MsgCore_new(struct EventBase* base,
                            struct Random* rand,
                            struct Allocator* allocator,
                            struct Log* log,
                            struct EncodingScheme* scheme)
{
    struct Allocator* alloc = Allocator_child(allocator);
    struct MsgCore_pvt* mcp = Allocator_calloc(alloc, sizeof(struct MsgCore_pvt), 1);
    Identity_set(mcp);
    mcp->pub.interRouterIf.send = incoming;
    mcp->qh = ArrayList_OfQueryHandlers_new(alloc);
    mcp->pinger = Pinger_new(base, rand, log, alloc);
    mcp->log = log;

    mcp->scheme = scheme;
    mcp->schemeDefinition = EncodingScheme_serialize(scheme, alloc);

    return &mcp->pub;
}
コード例 #14
0
ファイル: jpeg.c プロジェクト: doolse/wingsos
int main(int argc, char *argv[]) {
	int RcvId, xsize,ysize,minxsize,minysize;
	void *msg;
	void *App, *window, *bmp, *scr, *view;
	int seg=0,done=0,ch;
	uint32 temp,len;
        JMeta * metadata = malloc(sizeof(JMeta));	

	while ((ch = getopt(argc, argv, "g:b:c:")) != EOF) {
		switch(ch) {
		case 'g': 
			gamma = atoi(optarg);
			break;
		case 'b':
			bright = atoi(optarg);
			break;
		case 'c':
			contrast = atoi(optarg);
			break;
		}
			
	}
	if (argc-optind < 1)
		exit(1);
	filefd = open(argv[optind], O_READ);
	if (filefd == -1) {
		perror(argv[optind]);
		exit(1);
	}
	maketab();
	chan = makeChan();
	seg = loadseg();
	if (seg == 0xd8) {
		printf("It's a jpeg!\n");
	} else abort("Not a jpeg!\n");
	while(seg != 0xda) {
		seg = loadseg();
/*		printf("It's %2x, size %4x\n", seg, seglen); */
		switch(seg) {
			case 0xdb:
				segDQT();
				break;
			case 0xc4:
				segDHT();
				break;
			case 0xda:
				segSOS();
				break;
			case 0xc0:
				segSOF();
				break;
			case 0xdd:
				segDRI();
				break;
			default:
				printf("Unknown segment %d\n", seg);
				break;
		}
	}
	bmpwidth = round8(width);
	bmpheight = round8(height);

        metadata->launchpath = strdup(fpathname(argv[0],getappdir(),1));
        metadata->title = "Jpeg viewer";
        metadata->icon = app_icon;
        metadata->showicon = 1;
        metadata->parentreg = -1;

	App = JAppInit(NULL, chan);
	window = JWndInit(NULL, "Jpeg viewer by J. Maginnis and S. Judd", JWndF_Resizable,metadata);
        ((JCnt *)window)->Orient = JCntF_TopBottom;

        xsize = bmpwidth;
        ysize = bmpheight;

        if(xsize > 296)
          xsize = 296;
        else if(xsize < 64)
          xsize = 64;

        if(ysize > 160)
          ysize = 160;
        else if(ysize < 24)
          ysize = 24;

        if(xsize > 64)
          minxsize = 64;
        else
          minxsize = xsize;

        minysize = 24;

        JWSetBounds(window,0,0,xsize,ysize+16);
        JWSetMin(window,minxsize,minysize);
        JWSetMax(window,xsize+8,ysize+24);
        JAppSetMain(App,window);

	width8 = bmpwidth/8;
	temp = (uint32) width8 * bmpheight;
	len = temp/8+temp;
	bmpup = bmploc = calloc(len, 1);
	colloc = bmploc+temp;
	//printf("%dx%d, %lx bytes, %lx,%lx,%lx\n", bmpwidth, bmpheight, len, bmpup, colloc, bmpup+len);

	bmp = JBmpInit(NULL, bmpwidth, bmpheight, bmploc);
	view = JViewWinInit(NULL, bmp);
	scr = JScrInit(NULL, view, JScrF_VNotEnd|JScrF_HNotEnd);
        JWSetMin(scr,8,8);

	JCntAdd(window, scr);
       
        JWndSetProp(window);
	JWinShow(window);

    retexit(1);

	while(1) {
		while (!done && !chkRecv(chan)) {
			imagedata();
			render();
			JWReDraw(bmp);
			yup += heightDU;
			if (yup >= height) {
				FILE *fp;
				done=1;
				printf("Finished render\n");
/*				fp = fopen("bmpout","wb");
				if (fp) {
					fwrite(bmploc, 320*25+1000, 1, fp);
					fclose(fp);
				} */
			}
		}
		RcvId = recvMsg(chan, &msg);
		switch (* (int *)msg) {
		case WIN_EventRecv:
			JAppDrain(App);
			break;			
		}
		replyMsg(RcvId,0);
	}

	return 1;
}