From abebfd51a7b5077f420eaaed9d12a4f534895205 Mon Sep 17 00:00:00 2001
From: Ramin Yaghoubzadeh <ryaghoub@techfak.uni-bielefeld.de>
Date: Tue, 13 Mar 2012 01:05:59 +0100
Subject: [PATCH] updated the typing example. pygtk needed for wordsender.py
 ATTENTION: ipaaca.py disabled revision checks at the moment using an OMIT_...
 var (look on the first page of the file)

---
 java/src/ipaacademo/TextPrinter.java |  35 ++++---
 python/src/ipaaca.py                 |   8 +-
 python/test/src/textsender.py        |   4 +-
 python/test/src/wordsender.py        | 133 ++++++++++++++++++++++++++-
 4 files changed, 159 insertions(+), 21 deletions(-)

diff --git a/java/src/ipaacademo/TextPrinter.java b/java/src/ipaacademo/TextPrinter.java
index 88ee186..61d820d 100644
--- a/java/src/ipaacademo/TextPrinter.java
+++ b/java/src/ipaacademo/TextPrinter.java
@@ -24,7 +24,7 @@ public class TextPrinter
         {
             switch(type)
             {
-            case ADDED:  System.out.println("IU added "+iu.getPayload());  break;
+            case ADDED:  System.out.println("IU added "+iu.getPayload().get("CONTENT"));  break;
             case COMMITTED: System.out.println("IU committed");  break;
             case UPDATED: System.out.println("IU updated "+iu.getPayload()); break;
             case LINKSUPDATED: System.out.println("IU links updated"); break;
@@ -103,21 +103,22 @@ public class TextPrinter
                     continue;
                 }
                 //int numChars = (int)(duration/RATE);
-
+                boolean first_new_element = true;
                 if (currentTime >= nextTime) {
                     AbstractIU iu = iuFirst;
                     String str = "";
-                    int i = 0;
-                    boolean first_new_element = true;
                     do {
-                        if (iu.getPayload().get("STATE") != null || first_new_element) {
+                        //System.out.println(iu.getPayload().get("CONTENT"));
+                        String st = iu.getPayload().get("STATE");
+                        System.out.println("State "+st);
+                        if ((st != null) || first_new_element) {
                             str += "<font color=\"#000000\">";
                             str += iu.getPayload().get("CONTENT");
                             str += "</font>";
-                            if (iu.getPayload().get("STATE") == null) {
+                            if (st == null) {
+                                System.out.println("Setting state to REALIZED");
                                 iu.getPayload().put("STATE", "REALIZED");
                                 first_new_element = false;
-                                nextTime = currentTime + (int)(1000.0*RATE);
                             }
                         } else {
                             str += "<font color=\"#909090\">";
@@ -129,18 +130,23 @@ public class TextPrinter
                         if(successor!=null && !successor.isEmpty())
                         {
                             iu = inBuffer.getIU(successor.iterator().next());
+                        } else {
                         }
-                        i++;
                     } while(! iu.getLinks("SUCCESSOR").isEmpty());
-                    if (iu.getPayload().get("STATE") != null || first_new_element) {
-                    //if (i<numChars) {
+                    String st = iu.getPayload().get("STATE");
+                    System.out.println("State "+st);
+                    if ((st != null) || first_new_element) {
                         str += "<font color=\"#000000\">";
                         str += iu.getPayload().get("CONTENT");
                         str += "</font>";
-                        if (iu.getPayload().get("STATE") == null) {
+                        //if (iu.getPayload().get("STATE") == null) {
+                        //    iu.getPayload().put("STATE", "REALIZED");
+                        //    new_elements = true;
+                        //}
+                        if (st == null) {
+                            System.out.println("Setting state to REALIZED");
                             iu.getPayload().put("STATE", "REALIZED");
                             first_new_element = false;
-                            nextTime = currentTime + (int)(RATE*1000.0);
                         }
                     } else {
                         str += "<font color=\"#909090\">";
@@ -148,12 +154,17 @@ public class TextPrinter
                         str += "</font>";
                         //lastNewLetterTime = System.currentTimeMillis();
                     }
+                    if (! first_new_element) {
+                        nextTime = currentTime + (int)(RATE*1000.0);
+                        System.out.println("New target time: "+nextTime+" (current "+currentTime+")");
+                    }
 
                     str = "<html>"+str+"</html>";
                     //System.out.println(str);
                     label.setText(str);
                 } else {
                     // just wait until we can print some more
+                    System.out.println("wait");
                 }
 
                 try
diff --git a/python/src/ipaaca.py b/python/src/ipaaca.py
index 32140e6..eccf93c 100755
--- a/python/src/ipaaca.py
+++ b/python/src/ipaaca.py
@@ -15,6 +15,8 @@ import rsb.converter
 
 import ipaaca_pb2
 
+OMIT_REVISION_CHECKS = True
+
 # IDEAS
 #  We should think about relaying the update event (or at least the
 #  affected keys in the payload / links) to the event handlers!
@@ -964,7 +966,7 @@ class OutputBuffer(Buffer):
 			return 0
 		iu = self._iu_store[update.uid]
 		with iu.revision_lock:
-			if (update.revision != 0) and (update.revision != iu.revision):
+			if not OMIT_REVISION_CHECKS and (update.revision != 0) and (update.revision != iu.revision):
 				# (0 means "do not pay attention to the revision number" -> "force update")
 				logger.warning("Remote write operation failed because request was out of date; IU "+str(update.uid))
 				return 0
@@ -982,7 +984,7 @@ class OutputBuffer(Buffer):
 			return 0
 		iu = self._iu_store[update.uid]
 		with iu.revision_lock:
-			if (update.revision != 0) and (update.revision != iu.revision):
+			if not OMIT_REVISION_CHECKS and (update.revision != 0) and (update.revision != iu.revision):
 				# (0 means "do not pay attention to the revision number" -> "force update")
 				logger.warning("Remote write operation failed because request was out of date; IU "+str(update.uid))
 				return 0
@@ -1004,7 +1006,7 @@ class OutputBuffer(Buffer):
 			return 0
 		iu = self._iu_store[iu_commission.uid]
 		with iu.revision_lock:
-			if (iu_commission.revision != 0) and (iu_commission.revision != iu.revision):
+			if not OMIT_REVISION_CHECKS and (iu_commission.revision != 0) and (iu_commission.revision != iu.revision):
 				# (0 means "do not pay attention to the revision number" -> "force update")
 				logger.warning("Remote write operation failed because request was out of date; IU "+str(iu_commission.uid))
 				return 0
diff --git a/python/test/src/textsender.py b/python/test/src/textsender.py
index 0d80433..69da5ed 100755
--- a/python/test/src/textsender.py
+++ b/python/test/src/textsender.py
@@ -46,7 +46,9 @@ class TextSender(object):
 
 	
 	def inbuffer_handle_iu_event(self, iu, event_type, local):
-		if event_type == "ADDED": # and iu.category == RECV_CATEGORY:
+		if event_type == "LINKSUPDATED":
+			print "links updated"
+		elif event_type == "ADDED": # and iu.category == RECV_CATEGORY:
 			print("Received new word: "+iu.payload['WORD'])
 			sender.publish_text_to_print(iu.payload['WORD'], parent_iu_uid=iu.uid)
 		elif event_type == "RETRACTED":
diff --git a/python/test/src/wordsender.py b/python/test/src/wordsender.py
index e68bb72..92e0943 100755
--- a/python/test/src/wordsender.py
+++ b/python/test/src/wordsender.py
@@ -8,15 +8,121 @@ import ipaaca
 
 SEND_CATEGORY = 'WORD'
 
+import gobject
+import gtk
+import cairo
+
+class WordWindow(gtk.Window):
+	
+	def __init__(self, component):
+		super(WordWindow, self).__init__()
+		self.running = True
+		self.set_title("Word Sender")
+		self.set_size_request(640, 200)
+		self.set_position(gtk.WIN_POS_CENTER)
+		self.connect("destroy", self.quit)
+		darea = gtk.DrawingArea()
+		darea.connect("expose-event", self.expose)
+		darea.set_flags(gtk.CAN_FOCUS)
+		darea.grab_focus()
+		self.drawing_area = darea
+		self.connect("key_press_event",self.key_press)
+		self.add(darea)
+		self.show_all()
+		self.words = []
+		self.current_letters = ""
+		self.component = component
+	
+	def quit(self):
+		self.running = False
+	
+	def rounded_rectangle(self, cr, x, y, w, h, r=10):
+		cr.move_to(x+r,y)
+		cr.line_to(x+w-r,y)
+		cr.curve_to(x+w,y,x+w,y,x+w,y+r)
+		cr.line_to(x+w,y+h-r)
+		cr.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h)
+		cr.line_to(x+r,y+h)
+		cr.curve_to(x,y+h,x,y+h,x,y+h-r)
+		cr.line_to(x,y+r)
+		cr.curve_to(x,y,x,y,x+r,y)
+
+	def new_word(self, word):
+		uid = self.component.publish_new_word(word)
+		self.words.append([uid, word, 'NEW'])
+	
+	def key_press(self, widget, event):
+		if event.keyval == gtk.keysyms.Escape:
+			self.quit()
+			return
+		elif event.keyval == gtk.keysyms.BackSpace:
+			if len(self.current_letters) > 0:
+				self.current_letters = ""
+		elif event.keyval > 32 and event.keyval < 127:
+			self.current_letters += chr(event.keyval)
+		elif event.keyval == 32 or event.keyval == gtk.keysyms.Return:
+			if len(self.current_letters) > 0:
+				self.new_word(self.current_letters)
+				self.current_letters = ""
+		else:
+			print event, event.keyval
+			pass
+		x, y, w, h = widget.get_allocation()
+		widget.queue_draw_area(x, y, w, h)
+	
+	def update_word_state(self, uid, state):
+		for t in self.words:
+			u, w, s = t
+			if u == uid:
+				print "new state for "+w+": "+state
+				t[2] = state
+		x, y, w, h = self.drawing_area.get_allocation()
+		self.drawing_area.queue_draw_area(x, y, w, h)
+
+	def render_words(self, cr, x=20, y=100):
+		for wp in self.words:
+			uid, word, state = wp
+			x_bearing, y_bearing, width, _ = cr.text_extents(word)[:4]
+			_, _, _, height = cr.text_extents("Wy")[:4]
+			self.rounded_rectangle(cr, x, y-height-4, width+10, height+10)
+			cr.set_line_width(1.0)
+			cr.set_source_rgb(0.0, 0.0, 0.0)
+			cr.stroke_preserve()
+			if state == 'NEW' or state == '':
+				cr.set_source_rgb(1.0, 1.0, 1.0)
+			elif state == 'STARTED':
+				cr.set_source_rgb(0.3, 0.3, 1.0)
+			elif state == 'REALIZED':
+				cr.set_source_rgb(0.7, 0.7, 0.7)
+			else:
+				cr.set_source_rgb(1.0, 0.5, 0.5)
+			cr.fill()
+			cr.move_to(x+5, y)
+			cr.set_source_rgb(0.0, 0.0, 0.0)
+			cr.show_text(word)
+			x += width + 10 + 3
+		cr.move_to(x+5, y)
+		cr.show_text(self.current_letters)
+	
+	def expose(self, widget, event):
+		cr = widget.window.cairo_create()
+		cr.set_source_rgb(0.0, 0.0, 0.0)
+		cr.set_font_size(13)
+		cr.move_to(20, 30)
+		cr.show_text("Type words. Space sends a word. Backspace deletes one.")
+		
+		self.render_words(cr)
 
 class WordSender(object):
 	def __init__(self):
 		self.ob = ipaaca.OutputBuffer('WordSenderOut')
 		self.ob.register_handler(self.outbuffer_handle_iu_event)
+		self.window = None
 	
 	def outbuffer_handle_iu_event(self, iu, event_type, local):
 		if event_type == "UPDATED":
 			print(iu.payload['WORD']+': '+iu.payload['STATE'])
+			self.window.update_word_state(iu.uid, iu.payload['STATE'])
 		else:
 			print('(own IU event '+event_type+' '+str(iu.uid)+')')
 	
@@ -26,6 +132,16 @@ class WordSender(object):
 				return iu
 		return None
 	
+	def publish_new_word(self, word):
+		previous_iu = self.find_last_iu()
+		iu = ipaaca.IU( SEND_CATEGORY )
+		iu.payload = { 'WORD': word }
+		self.ob.add(iu)
+		if previous_iu is not None:
+			previous_iu.add_links( 'SUCCESSOR', [iu.uid] )
+			iu.add_links( 'PREDECESSOR', [previous_iu.uid] )
+		return iu.uid
+
 	def publish_words(self, words):
 		previous_iu = self.find_last_iu()
 		for word in words:
@@ -39,10 +155,17 @@ class WordSender(object):
 
 if __name__ == '__main__':
 	sender = WordSender()
-	sender.publish_words(['this','is','a','demonstration','of','incremental','generation'])
-	print sender.ob.unique_name
+	window = WordWindow(sender)
+	sender.window = window
+	#sender.publish_words(['this','is','a','demonstration','of','incremental','generation'])
+	#print sender.ob.unique_name
 	print "Press Ctrl-C to cancel..."
-	while True:
-		time.sleep(0.1)
-	
+	#gtk.main()
+	lc = gobject.main_context_default()
+	while window.running:
+		lc.iteration(False)
+		time.sleep(0.01)
+	#while True:
+	#	time.sleep(0.1)
+	#
 
-- 
GitLab