Example #1
0
	def __init__(self, layer = "UI"):
		TextLine.__init__(self, layer)

		self.__currentCandidateWindowClass = None
		self.__currentCandidateWindow = None

		self.__imeMax = 0
		self.__imeUserMax = 0
		self.__imeUse = True

		self.__isNumberMode = False

		self.__wndReading = _ReadingWindow()
		self.__wndReading.Hide()

		self.AddEventListener(EditLine.Events.ON_SET_FOCUS, self._OnSetFocus)
		self.AddEventListener(EditLine.Events.ON_KILL_FOCUS, self._OnKillFocus)
		self.AddEventListener(EditLine.Events.ON_IME_CHANGE_CODE_PAGE, self._OnIMEChangeCodePage)
		self.AddEventListener(EditLine.Events.ON_IME_OPEN_CANDIDATE_LIST, self._OnIMEOpenCandidateList)
		self.AddEventListener(EditLine.Events.ON_IME_CLOSE_CANDIDATE_LIST, lambda : self.__currentCandidateWindow.Hide())
		self.AddEventListener(EditLine.Events.ON_IME_OPEN_READING_WND, self._OnIMEOpenReadingWindow())
		self.AddEventListener(EditLine.Events.ON_IME_CLOSE_READING_WND, lambda : self.__wndReading.Hide())
		self.AddEventListener(EditLine.Events.ON_IME_UPDATE, self._OnIMEUpdate)
		self.AddEventListener(EditLine.Events.ON_IME_RETURN, lambda : snd.PlaySound("sound/ui/click.wav"))
		self.AddEventListener(EditLine.Events.ON_KEY_DOWN, self._OnKeyDown)
		self.AddEventListener(EditLine.Events.ON_IME_KEY_DOWN, self._OnIMEKeyDown)
		self.AddEventListener(EditLine.Events.ON_MOUSE_LEFT_BUTTON_DOWN, self._OnMouseLeftButtonDown)

		self.SetCodePage(app.GetDefaultCodePage())
Example #2
0
    def __init__(self):
        Bar.__init__(self, "TOP_MOST")

        self.__txtText = TextLine()
        self.__txtText.SetParent(self)
        self.__txtText.SetPosition(4, 3)
        self.__txtText.Show()

        self.SetSize(80, 19)
        self.Show()
Example #3
0
	def SetTitle(self, title):
		if not self.__txtTitle:
			self.__txtTitle = TextLine()
			self.__txtTitle.SetParent(self)
			self.__txtTitle.SetPackedFontColor(0xFFCAA76F)
			self.__txtTitle.SetHorizontalAlignCenter()
			self.__txtTitle.Show()

		self.__txtTitle.SetText(title)
		self.UpdateTitle()
Example #4
0
    def SetTitle(self, title):
        if not self.__txtTitle:
            self.__txtTitle = TextLine()
            self.__txtTitle.SetParent(self)
            self.__txtTitle.SetPackedFontColor(0xFFE6D0A2)
            self.__txtTitle.SetHorizontalAlignCenter()
            self.__txtTitle.SetVerticalAlignBottom()
            self.__txtTitle.Show()

        self.__txtTitle.SetText(title)
        self.UpdateTitlePosition()
Example #5
0
	def SetText(self, text):
		if not self.__txtText:
			self.__txtText = TextLine()
			self.__txtText.SetParent(self)
			self.__txtText.AddFlag("not_pick")
			self.__txtText.SetVerticalAlignCenter()
			self.__txtText.SetPackedFontColor(0xFFE6D0A2)
			self.__txtText.Show()

			self.UpdateText()

		self.__txtText.SetText(text)
Example #6
0
	def SetTextInstance(self, allowEdit = True):
		if self.__txtInput:
			self.DeleteTextInstance()

		if allowEdit:
			self.__txtInput = EditLine()
		else:
			self.__txtInput = TextLine()
		self.__txtInput.SetParent(self)
		self.__txtInput.SetSize(self.GetWidth() - self.TEXT_PADDING[0] * 2, self.GetHeight() - self.TEXT_PADDING[1] * 2)
		self.__txtInput.SetPackedFontColor(self.TEXT_COLOR)
		self.__txtInput.Show()

		self.ArrangeText()
Example #7
0
    def __init__(self, pos, text, font, width, center=0):
        self.lines = []

        words = text.split(' ')
        start = 0
        stop = 0

        height = font.get_height()

        while start < len(words):
            while (get_item_width(' '.join(words[start:stop]), font) < width
                   and stop < len(words) + 1):
                stop += 1

            l = ' '.join(words[start:stop - 1])

            self.lines.append\
                (TextLine((pos[0], pos[1] + len(self.lines) * (height + 1)),
                          l,
                          font,
                          Borders(),
                          width,
                          center))

            start = stop - 1

        Widget.__init__(self, pos, (width, len(self.lines) * (height + 1)))
Example #8
0
    def __init__(self, pos, text, font, width = -1):
        font_height = font.get_height()

        text_line = TextLine((font_height + PAD, 0), 
                             text, 
                             font,
                             Borders(),
                             width - font_height - 2 * PAD,
                             0)

        text_line.activate()

        self.passive_surface = \
            pygame.Surface((font_height + text_line.dim[0] + 2 * PAD, 
                            font_height + PAD))
        self.passive_surface.fill(BG_COLOR)

        self.active_surface = \
            pygame.Surface((font_height + text_line.dim[0] + 2 * PAD, 
                            font_height + PAD))
        self.active_surface.fill(FOCUSED_COLOR)

        text_line.render(self.passive_surface, 1)
        text_line.set_focus((font_height + PAD + 1, 1), 0, 0, [])
        text_line.render(self.active_surface, 1)
     
        pygame.draw.circle(self.active_surface, 
                           BORDER_COLOR, 
                           (font_height / 2 + PAD/2, 
                            font_height / 2 + PAD/2),
                           font_height / 2)

        pygame.draw.circle(self.passive_surface, 
                           BORDER_COLOR, 
                           (font_height / 2 + PAD/2, 
                            font_height / 2 + PAD/2),
                           font_height / 2)

        self.font_height = font_height
        self.selected = 0

        Widget.__init__(self, pos, (font_height + text_line.dim[0], 
                                    font_height))

        self.surface = self.active_surface
        self.event = "Select: " + text
Example #9
0
    def __init__(self, pos, text, font, width=-1):
        font_height = font.get_height()

        text_line = TextLine((font_height + PAD, 0), text, font, Borders(),
                             width - font_height - 2 * PAD, 0)

        text_line.activate()

        self.passive_surface = \
            pygame.Surface((font_height + text_line.dim[0] + 2 * PAD,
                            font_height + PAD))
        self.passive_surface.fill(BG_COLOR)

        self.active_surface = \
            pygame.Surface((font_height + text_line.dim[0] + 2 * PAD,
                            font_height + PAD))
        self.active_surface.fill(FOCUSED_COLOR)

        text_line.render(self.passive_surface, 1)
        text_line.set_focus((font_height + PAD + 1, 1), 0, 0, [])
        text_line.render(self.active_surface, 1)

        pygame.draw.circle(
            self.active_surface, BORDER_COLOR,
            (font_height / 2 + PAD / 2, font_height / 2 + PAD / 2),
            font_height / 2)

        pygame.draw.circle(
            self.passive_surface, BORDER_COLOR,
            (font_height / 2 + PAD / 2, font_height / 2 + PAD / 2),
            font_height / 2)

        self.font_height = font_height
        self.selected = 0

        Widget.__init__(self, pos,
                        (font_height + text_line.dim[0], font_height))

        self.surface = self.active_surface
        self.event = "Select: " + text
Example #10
0
    def __init__(self, pos, title, items, font, width=-1):
        width = max(width, get_item_width(title, font))
        for item in items:
            width = max(width, get_item_width(item, font))

        closed_title_borders = Borders(1, 1, 1, 1)
        self.title_line = TextLine(pos, title, font, closed_title_borders,
                                   width)

        open_title_borders = Borders(1, 0, 1, 1)
        self.item_lines = [
            TextLine(pos, title, font, open_title_borders, width)
        ]

        item_borders = Borders(0, 0, 1, 1)
        last_item_borders = Borders(0, 1, 1, 1)

        for i in range(len(items)):
            if i + 1 == len(items):
                self.item_lines.append\
                    (TextLine((pos[0],
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              last_item_borders,
                              width))
            else:
                self.item_lines.append\
                    (TextLine((pos[0],
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              item_borders,
                              width))

        Widget.__init__(self, pos, (width, self.title_line.dim[1]))

        self.is_open = 1
        self.close()
Example #11
0
class _ReadingWindow(Bar):
    def __init__(self):
        Bar.__init__(self, "TOP_MOST")

        self.__txtText = TextLine()
        self.__txtText.SetParent(self)
        self.__txtText.SetPosition(4, 3)
        self.__txtText.Show()

        self.SetSize(80, 19)
        self.Show()

    def __del__(self):
        Bar.__del__(self)

    def SetText(self, text):
        self.__txtText.SetText(text)

    def SetReadingPosition(self, x, y):
        self.SetPosition(x + 2, y - self.GetHeight() - 2)

    def SetTextColor(self, color):
        self.__txtText.SetPackedFontColor(color)
Example #12
0
    def __init__(self, layer="UI"):
        TextLine.__init__(self, layer)

        self.__currentCandidateWindowClass = None
        self.__currentCandidateWindow = None

        self.__imeMax = 0
        self.__imeUserMax = 0
        self.__imeUse = True

        self.__isNumberMode = False

        self.__wndReading = _ReadingWindow()
        self.__wndReading.Hide()

        self.AddEventListener(EditLine.Events.ON_SET_FOCUS, self._OnSetFocus)
        self.AddEventListener(EditLine.Events.ON_KILL_FOCUS, self._OnKillFocus)
        self.AddEventListener(EditLine.Events.ON_IME_CHANGE_CODE_PAGE,
                              self._OnIMEChangeCodePage)
        self.AddEventListener(EditLine.Events.ON_IME_OPEN_CANDIDATE_LIST,
                              self._OnIMEOpenCandidateList)
        self.AddEventListener(EditLine.Events.ON_IME_CLOSE_CANDIDATE_LIST,
                              lambda: self.__currentCandidateWindow.Hide())
        self.AddEventListener(EditLine.Events.ON_IME_OPEN_READING_WND,
                              self._OnIMEOpenReadingWindow())
        self.AddEventListener(EditLine.Events.ON_IME_CLOSE_READING_WND,
                              lambda: self.__wndReading.Hide())
        self.AddEventListener(EditLine.Events.ON_IME_UPDATE, self._OnIMEUpdate)
        self.AddEventListener(EditLine.Events.ON_IME_RETURN,
                              lambda: snd.PlaySound("sound/ui/click.wav"))
        self.AddEventListener(EditLine.Events.ON_KEY_DOWN, self._OnKeyDown)
        self.AddEventListener(EditLine.Events.ON_IME_KEY_DOWN,
                              self._OnIMEKeyDown)
        self.AddEventListener(EditLine.Events.ON_MOUSE_LEFT_BUTTON_DOWN,
                              self._OnMouseLeftButtonDown)

        self.SetCodePage(app.GetDefaultCodePage())
Example #13
0
class HorizontalBar(ExpandedImageBox):
	BASE_PATH = "%s/controls/common/horizontal_bar/" % illumina.BASE_PATH
	
	WIDTH = 208
	HEIGHT = 32

	def __init__(self, layer = "UI"):
		ExpandedImageBox.__init__(self, layer)

		self.__width = 0

		self.__CreateUI()
		self.SetWidth(HorizontalBar.WIDTH)

	def __del__(self):
		ExpandedImageBox.__del__(self)

	def __CreateUI(self):
		self.__txtTitle = None

		self.LoadImage("%s/center.tga" % HorizontalBar.BASE_PATH)
		self.Show()

	def SetWidth(self, width):
		self.__width = width

		self.SetScale(float(width) / float(HorizontalBar.WIDTH), 1.0)

		self.UpdateTitle()

	## Title
	def SetTitle(self, title):
		if not self.__txtTitle:
			self.__txtTitle = TextLine()
			self.__txtTitle.SetParent(self)
			self.__txtTitle.SetPackedFontColor(0xFFCAA76F)
			self.__txtTitle.SetHorizontalAlignCenter()
			self.__txtTitle.Show()

		self.__txtTitle.SetText(title)
		self.UpdateTitle()

	def UpdateTitle(self):
		if not self.__txtTitle:
			return
		
		self.__txtTitle.SetPosition(self.__width / 2, 5)
Example #14
0
    def __init__(self, pos, title, items, font, width = -1):
        width = max(width, get_item_width(title, font))
        for item in items:
            width = max(width, get_item_width(item, font))

        closed_title_borders = Borders(1, 1, 1, 1)
        self.title_line = TextLine(pos, title, font, 
                                   closed_title_borders, width)
        
        open_title_borders = Borders(1, 0, 1, 1)
        self.item_lines = [TextLine(pos, title, font, 
                                    open_title_borders, width)]

        item_borders = Borders(0, 0, 1, 1)
        last_item_borders = Borders(0, 1, 1, 1)

        for i in range(len(items)):
            if i + 1 == len(items):
                self.item_lines.append\
                    (TextLine((pos[0], 
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              last_item_borders,
                              width))
            else:
                self.item_lines.append\
                    (TextLine((pos[0], 
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              item_borders,
                              width))

        Widget.__init__(self, pos, (width, self.title_line.dim[1]))

        self.is_open = 1
        self.close()
def loadTelegrams(sampleDataFileName):

    titles = {}  #for t1
    publishdates = {}  #for t6
    copyrights = {}  #for t8

    with open(sampleDataFileName) as csvfile:
        parsedCsv = csv.DictReader(csvfile)
        nTask1Parsed = 0
        nTask8Parsed = 0
        for recordIndex, record in enumerate(parsedCsv):
            done = False
            isTask1Exist = False
            isTask8Exist = False
            isTask6Exist = False

            # check the date that the classification was made
            if "metadata" in record:
                parsedMetadata = json.loads(record["metadata"])
                parsedDate = dateutil.parser.parse(
                    parsedMetadata['started_at'])
                # skip "testing" data before the site went live
                if parsedDate < liveDate:
                    continue

            # parse the annotations and the subject data
            parsedAnnotations = json.loads(record["annotations"])
            parsedSubjectData = json.loads(record["subject_data"])

            # initialize container for transcribed lines
            titlesLines = TelegramLines()
            copyrightLines = TelegramLines()
            publishdateLines = TelegramLines()

            # loop over tasks in the annotation
            for task in parsedAnnotations:
                # Check if the current record is for a telegram (tasks may be stored out of order, so
                # some tasks may be processed before non-telegrams are caught -
                # inefficient but unavoidable?)
                task_values = []
                if task['task'] == "T0" and len(task['value']) > 0:
                    task_values.append(task['value'])
                elif task['task'] == "T1" and len(task['value']) > 0:
                    isTask1Exist = True
                    # process the lines that were transcribed for this task
                    for taskValueItem in task['value']:
                        titleLine = TextLine(
                            taskValueItem['x1'], taskValueItem['y1'],
                            taskValueItem['x2'], taskValueItem['y2'],
                            taskValueItem['details'][0]['value'])
                        titlesLines.addLine(titleLine)

                elif task['task'] == "T6" and len(task['value']) > 0:
                    isTask6Exist = True
                    # process the lines that were transcribed for this task
                    for taskValueItem in task['value']:
                        publishdateLine = TextLine(
                            taskValueItem['x1'], taskValueItem['y1'],
                            taskValueItem['x2'], taskValueItem['y2'],
                            taskValueItem['details'][0]['value'])
                        publishdateLines.addLine(publishdateLine)

                elif task['task'] == "T8" and len(task['value']) > 0:
                    isTask8Exist = True
                    # process the lines that were transcribed for this task
                    for taskValueItem in task['value']:
                        copyrightLine = TextLine(
                            taskValueItem['x1'], taskValueItem['y1'],
                            taskValueItem['x2'], taskValueItem['y2'],
                            taskValueItem['details'][0]['value'])
                        copyrightLines.addLine(copyrightLine)

            # if the transcribed lines of a telegram have been processed then update the
            # list of independent transcriptions for this subject
            if isTask1Exist:
                nTask1Parsed += 1
                new_list = titles.get(int(record['subject_ids']), [])
                new_list.append((recordIndex, titlesLines))
                titles[int(record['subject_ids'])] = new_list

            if isTask6Exist:
                new_list = copyrights.get(int(record['subject_ids']), [])
                new_list.append((recordIndex, publishdateLines))
                publishdates[int(record['subject_ids'])] = new_list

            if isTask8Exist:
                nTask8Parsed += 1
                new_list = copyrights.get(int(record['subject_ids']), [])
                new_list.append((recordIndex, copyrightLines))
                copyrights[int(record['subject_ids'])] = new_list

    return titles, copyrights, publishdates, nTask1Parsed, nTask8Parsed
Example #16
0
class Menu(Widget):
    def __init__(self, pos, title, items, font, width = -1):
        width = max(width, get_item_width(title, font))
        for item in items:
            width = max(width, get_item_width(item, font))

        closed_title_borders = Borders(1, 1, 1, 1)
        self.title_line = TextLine(pos, title, font, 
                                   closed_title_borders, width)
        
        open_title_borders = Borders(1, 0, 1, 1)
        self.item_lines = [TextLine(pos, title, font, 
                                    open_title_borders, width)]

        item_borders = Borders(0, 0, 1, 1)
        last_item_borders = Borders(0, 1, 1, 1)

        for i in range(len(items)):
            if i + 1 == len(items):
                self.item_lines.append\
                    (TextLine((pos[0], 
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              last_item_borders,
                              width))
            else:
                self.item_lines.append\
                    (TextLine((pos[0], 
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              item_borders,
                              width))

        Widget.__init__(self, pos, (width, self.title_line.dim[1]))

        self.is_open = 1
        self.close()

    def open(self):
        if not self.is_open:
            self.schedule_render()    
            self.is_open = 1
            for item in self.item_lines:
                item.activate()
                item.schedule_render()
            self.dim = (self.dim[0], self.title_line.dim[1] * 
                        len(self.item_lines))

    def close(self):
        if self.is_open:
            self.schedule_render()
            self.is_open = 0
            self.title_line.activate()
            self.title_line.schedule_render()
            self.dim = self.title_line.dim
            for item in self.item_lines:
                item.unfocus()

    def render(self, super_surface, force = 0):
        if force or (self.need_render and self.active):
            Widget.render(self)

            if self.is_open:
                for item in self.item_lines:
                    item.render(super_surface, force)
            else:
                self.title_line.render(super_surface, force)

    def set_focus(self, mouse_pos, click, mouse_status, events):
        if Widget.set_focus(self, mouse_pos, click, mouse_status, events):
            self.open()
            
            for item in self.item_lines:
                focus = item.set_focus(mouse_pos, click, mouse_status, events)

                if mouse_status and focus:
                    self.close()

            return 1
        else:
            self.close()
            return 0
Example #17
0
class TitleBar(Window):
    BASE_PATH = "%s/controls/common/titlebar/" % illumina.BASE_PATH

    HEIGHT = 28
    MIN_WIDTH = 70

    def __init__(self, layer="UI"):
        Window.__init__(self, layer)

        self.__CreateUI()

        self.SetWidth(0)

    def __del__(self):
        Window.__del__(self)

    def __CreateUI(self):
        self.__dictImages = {
            'LEFT': ImageBox(),
            'CENTER': ExpandedImageBox(),
            'RIGHT': ImageBox()
        }

        self.__imgCloseButtonDecoration = None
        self.__btnClose = None
        self.__txtTitle = None

        for image in self.__dictImages.itervalues():
            image.SetParent(self)
            image.AddFlag("not_pick")
            image.Show()

        self.__dictImages['LEFT'].LoadImage("%s/left.tga" % TitleBar.BASE_PATH)
        self.__dictImages['CENTER'].LoadImage("%s/center.tga" %
                                              TitleBar.BASE_PATH)
        self.__dictImages['RIGHT'].LoadImage("%s/right.tga" %
                                             TitleBar.BASE_PATH)

    def UpdateGeneralUIPosition(self):
        self.__dictImages['LEFT'].SetPosition(
            0, TitleBar.HEIGHT - self.__dictImages['LEFT'].GetHeight())
        self.__dictImages['CENTER'].SetPosition(
            self.__dictImages['LEFT'].GetWidth(),
            TitleBar.HEIGHT - self.__dictImages['CENTER'].GetHeight())
        self.__dictImages['RIGHT'].SetPosition(
            self.GetWidth() - self.__dictImages['RIGHT'].GetWidth(),
            TitleBar.HEIGHT - self.__dictImages['RIGHT'].GetHeight())

        self.__dictImages['CENTER'].SetScale(
            float(self.GetWidth() - (self.__dictImages['LEFT'].GetWidth() +
                                     self.__dictImages['RIGHT'].GetWidth())) /
            float(self.__dictImages['CENTER'].GetWidth()), 1.0)

    def SetWidth(self, width):
        width = max(TitleBar.MIN_WIDTH, width)

        self.SetSize(width, TitleBar.HEIGHT)

        self.UpdateGeneralUIPosition()
        self.UpdateTitlePosition()
        self.UpdateCloseButtonAndDecorationPosition()

    ## TITLE
    def SetTitle(self, title):
        if not self.__txtTitle:
            self.__txtTitle = TextLine()
            self.__txtTitle.SetParent(self)
            self.__txtTitle.SetPackedFontColor(0xFFE6D0A2)
            self.__txtTitle.SetHorizontalAlignCenter()
            self.__txtTitle.SetVerticalAlignBottom()
            self.__txtTitle.Show()

        self.__txtTitle.SetText(title)
        self.UpdateTitlePosition()

    def UpdateTitlePosition(self):
        if not self.__txtTitle:
            return

        self.__txtTitle.SetPosition(self.GetWidth() / 2, 17)

    ## CLOSE BUTTON
    def AddCloseButton(self):
        self.__imgCloseButtonDecoration = ImageBox()
        self.__imgCloseButtonDecoration.SetParent(self)
        self.__imgCloseButtonDecoration.AddFlag("not_pick")
        self.__imgCloseButtonDecoration.LoadImage("%s/decoration_right.tga" %
                                                  TitleBar.BASE_PATH)
        self.__imgCloseButtonDecoration.SetHorizontalAlign(
            wndMgr.HORIZONTAL_ALIGN_RIGHT)
        self.__imgCloseButtonDecoration.Show()

        self.__btnClose = SimpleButton()
        self.__btnClose.SetParent(self)
        self.__btnClose.SetUpVisual(
            "%s/controls/common/button/board_close_01_normal.tga" %
            illumina.BASE_PATH)
        self.__btnClose.SetOverVisual(
            "%s/controls/common/button/board_close_02_hover.tga" %
            illumina.BASE_PATH)
        self.__btnClose.SetDownVisual(
            "%s/controls/common/button/board_close_03_active.tga" %
            illumina.BASE_PATH)
        self.__btnClose.SetHorizontalAlign(wndMgr.HORIZONTAL_ALIGN_RIGHT)
        self.__btnClose.Show()

        self.UpdateGeneralUIPosition()
        self.UpdateTitlePosition()
        self.UpdateCloseButtonAndDecorationPosition()

    def GetCloseButton(self):
        return self.__btnClose

    def HasCloseButton(self):
        return (self.__imgCloseButtonDecoration and self.__btnClose)

    def UpdateCloseButtonAndDecorationPosition(self):
        if not self.HasCloseButton():
            return

        self.__imgCloseButtonDecoration.SetPosition(
            self.__imgCloseButtonDecoration.GetWidth() - 13, -18)
        self.__btnClose.SetPosition(self.__btnClose.GetWidth() - 1, 0)
Example #18
0
class Menu(Widget):
    def __init__(self, pos, title, items, font, width=-1):
        width = max(width, get_item_width(title, font))
        for item in items:
            width = max(width, get_item_width(item, font))

        closed_title_borders = Borders(1, 1, 1, 1)
        self.title_line = TextLine(pos, title, font, closed_title_borders,
                                   width)

        open_title_borders = Borders(1, 0, 1, 1)
        self.item_lines = [
            TextLine(pos, title, font, open_title_borders, width)
        ]

        item_borders = Borders(0, 0, 1, 1)
        last_item_borders = Borders(0, 1, 1, 1)

        for i in range(len(items)):
            if i + 1 == len(items):
                self.item_lines.append\
                    (TextLine((pos[0],
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              last_item_borders,
                              width))
            else:
                self.item_lines.append\
                    (TextLine((pos[0],
                               pos[1] + (i + 1) * self.title_line.dim[1]),
                              items[i],
                              font,
                              item_borders,
                              width))

        Widget.__init__(self, pos, (width, self.title_line.dim[1]))

        self.is_open = 1
        self.close()

    def open(self):
        if not self.is_open:
            self.schedule_render()
            self.is_open = 1
            for item in self.item_lines:
                item.activate()
                item.schedule_render()
            self.dim = (self.dim[0],
                        self.title_line.dim[1] * len(self.item_lines))

    def close(self):
        if self.is_open:
            self.schedule_render()
            self.is_open = 0
            self.title_line.activate()
            self.title_line.schedule_render()
            self.dim = self.title_line.dim
            for item in self.item_lines:
                item.unfocus()

    def render(self, super_surface, force=0):
        if force or (self.need_render and self.active):
            Widget.render(self)

            if self.is_open:
                for item in self.item_lines:
                    item.render(super_surface, force)
            else:
                self.title_line.render(super_surface, force)

    def set_focus(self, mouse_pos, click, mouse_status, events):
        if Widget.set_focus(self, mouse_pos, click, mouse_status, events):
            self.open()

            for item in self.item_lines:
                focus = item.set_focus(mouse_pos, click, mouse_status, events)

                if mouse_status and focus:
                    self.close()

            return 1
        else:
            self.close()
            return 0
Example #19
0
 def __del__(self):
     TextLine.__del__(self)
Example #20
0
    def __init__(self, pos, text, font, width=-1):
        text_line = TextLine(pos, text, font, Borders(),
                             get_item_width(text, font) + BUTTON_PADDING, 1)

        width = max(width, text_line.dim[0])

        Widget.__init__(
            self, pos,
            (width + BUTTON_MARGINALS, text_line.dim[1] + BUTTON_MARGINALS))

        x_pos = BUTTON_MARGINALS / 2 + (width - text_line.dim[0]) / 2

        self.focused_surface = pygame.Surface(self.dim)
        self.focused_surface.fill(FOCUSED_COLOR)
        self.focused_surface.blit(text_line.focused_surface,
                                  (x_pos, BUTTON_MARGINALS / 2))

        self.unfocused_surface = pygame.Surface(self.dim)
        self.unfocused_surface.fill(BG_COLOR)
        self.unfocused_surface.blit(text_line.unfocused_surface,
                                    (x_pos, BUTTON_MARGINALS / 2))

        pygame.draw.line(self.focused_surface, BORDER_COLOR,
                         (0, BUTTON_MARGINALS / 4),
                         (width + BUTTON_MARGINALS, BUTTON_MARGINALS / 4),
                         BUTTON_MARGINALS / 2)

        pygame.draw.line(self.unfocused_surface, BORDER_COLOR,
                         (0, BUTTON_MARGINALS / 4),
                         (width + BUTTON_MARGINALS, BUTTON_MARGINALS / 4),
                         BUTTON_MARGINALS / 2)

        pygame.draw.line(
            self.focused_surface, BORDER_COLOR,
            (0, self.dim[1] - BUTTON_MARGINALS / 4 - 1),
            (width + BUTTON_MARGINALS, self.dim[1] - BUTTON_MARGINALS / 4 - 1),
            BUTTON_MARGINALS / 2)

        pygame.draw.line(
            self.unfocused_surface, BORDER_COLOR,
            (0, self.dim[1] - BUTTON_MARGINALS / 4 - 1),
            (width + BUTTON_MARGINALS, self.dim[1] - BUTTON_MARGINALS / 4 - 1),
            BUTTON_MARGINALS / 2)

        pygame.draw.line(self.unfocused_surface, BORDER_COLOR,
                         (BUTTON_MARGINALS / 4, 0),
                         (BUTTON_MARGINALS / 4, self.dim[1]),
                         BUTTON_MARGINALS / 2)

        pygame.draw.line(self.focused_surface, BORDER_COLOR,
                         (BUTTON_MARGINALS / 4, 0),
                         (BUTTON_MARGINALS / 4, self.dim[1]),
                         BUTTON_MARGINALS / 2)

        pygame.draw.line(self.unfocused_surface, BORDER_COLOR,
                         (self.dim[0] - BUTTON_MARGINALS / 4 - 1, 0),
                         (self.dim[0] - BUTTON_MARGINALS / 4 - 1, self.dim[1]),
                         BUTTON_MARGINALS / 2)

        pygame.draw.line(self.focused_surface, BORDER_COLOR,
                         (self.dim[0] - BUTTON_MARGINALS / 4 - 1, 0),
                         (self.dim[0] - BUTTON_MARGINALS / 4 - 1, self.dim[1]),
                         BUTTON_MARGINALS / 2)

        self.surface = self.unfocused_surface

        # FIXME
        self.event = text
Example #21
0
 def deal_msg(self, msg, address):
     msgbox = MsgBox()
     msgbox.umpack_message(msg)
     print(msgbox.make_message())
     try:
         if msgbox.opcode == 0x10:
             userid, password = msgbox.message.split('$')
             if userid in self.userlist.keys() and password == self.userlist[userid]:
                 # The user is on the server list and the password is correct
                 # Generate token
                 token = self.gen_token()
                 # Save token to online list
                 self.tokenlist[token] = userid
                 print(address)
                 self.userstatus[userid].online(token, address)
                 remsgbox = MsgBox(0x80, '', token, 0, '')
             else:
                 # failed to login
                 remsgbox = MsgBox(0x81, '', '', 0, '')
         else:
             # Verify user is online with token
             ctoken = msgbox.token
             if ctoken in self.tokenlist.keys():
                 # Get the client id of the sending request
                 clientid = self.tokenlist[ctoken]
                 if msgbox.opcode == 0x20:
                     userid = msgbox.message
                     if userid in self.userlist.keys() and userid not in self.userstatus[clientid].subscribe_list:
                         # subscribe successfully
                         self.userstatus[clientid].subscribe_list.append(userid)
                         remsgbox = MsgBox(0x90, '', '', 0, '')
                     else:
                         # subscribe failed
                         remsgbox = MsgBox(0x91, '', '', 0, '')
                 elif msgbox.opcode == 0x21:
                     userid = msgbox.message
                     if userid in self.userlist.keys() and userid in self.userstatus[clientid].subscribe_list:
                         # unsubscribe successfully
                         self.userstatus[clientid].subscribe_list.remove(userid)
                         remsgbox = MsgBox(0xA0, '', '', 0, '')
                     else:
                         # unsubscribe failed
                         remsgbox = MsgBox(0xA1, '', '', 0, '')
                 elif msgbox.opcode == 0x30:
                     text = msgbox.message
                     textline = TextLine(clientid, text)
                     # Adding messages to the server's storage, 
                     self.text_list.insert(0, textline)
                     # 转发消息
                     self.forward_text(clientid, textline)
                     remsgbox = MsgBox(0xB0, '', '', 0, '')
                 elif msgbox.opcode == 0x40:
                     n = int(msgbox.message)
                     i = 0
                     while n > 0 and i < len(self.text_list):
                         # 遍历用户发送的消息队列,按时间倒序排列,从中检索出n条消息
                         if self.text_list[i].userid in self.userstatus[clientid].subscribe_list:
                             remsg = {'sourceid': self.text_list[i].userid, 'text': self.text_list[i].text}
                             remsgbox = MsgBox(0xC0, '', '', self.get_msgid(), remsg)
                             self.udp_socket.sendto(remsgbox.pack_message(), address)
                             n -= 1
                         i += 1
                     remsgbox = MsgBox(0xC1, '', '', self.get_msgid(), '')
                 elif msgbox.opcode == 0x1F:
                     # The user logs out and then puts the status offline
                     del self.tokenlist[ctoken]
                     self.userstatus[clientid].offline()
                     remsgbox = MsgBox(0x8F, '', '', 0, '')
                 elif msgbox.opcode == 0x50:
                     # User requests photo upload
                     picname = msgbox.message
                     last_index = picname.rfind('/')
                     picname = picname[last_index + 1:]
                     self.pic_list[picname] = clientid
                     # Returns the local tcp server address to the user, and confirms the picture to be uploaded
                     remsgbox = MsgBox(0xD0, '', '', 0, {'tcpip':self.ip, 'tcpport': self.tcp_port, 'picname':picname})
                 elif msgbox.opcode == 0x51:
                     # 用户请求下载照片
                     picname = msgbox.message
                     if picname in self.pic_list.keys():
                         # 向用户返回本地tcp服务器地址,并且确认要接受的图片
                         remsgbox = MsgBox(0xD1, '', '', 0, {'tcpip':self.ip, 'tcpport': self.tcp_port, 'picname':picname, 'clientid':clientid})
                     else:
                         remsgbox = MsgBox(0xD2, '', '', 0, '')
                 elif msgbox.opcode == 0x00:
                     # The client actively requests a session reset
                     del self.tokenlist[ctoken]
                     self.userstatus[clientid].offline()
                     return
                 elif msgbox.opcode == 0x31:
                     #  Receive the packet and confirm the ack
                     ack_id = msgbox.messageid
                     if ack_id in self._ack_list.keys():
                         del self._ack_list[ack_id]
                         print('get info')
                     return
                 else:
                     return
             else:
                 # User is not logged in to perform these operations
                 remsgbox = MsgBox(0xF0, '', '', 0, '')
         
         self.udp_socket.sendto(remsgbox.pack_message(), address)
     except:
         pass
Example #22
0
	def __del__(self):
		TextLine.__del__(self)
Example #23
0
class Expander(Window):
	BASE_PATH = "%s/controls/common/expander/" % illumina.BASE_PATH

	IMAGES = {
		'LEFT' : {
			ExpanderState.COLLAPSED : "left_01_normal.tga",
			ExpanderState.EXPANDED : "left_02_hover.tga"
		},
		'CENTER' : {
			ExpanderState.COLLAPSED : "center_01_normal.tga",
			ExpanderState.EXPANDED : "center_02_hover.tga"
		},
		'RIGHT' : {
			ExpanderState.COLLAPSED : "right_01_normal.tga",
			ExpanderState.EXPANDED : "right_02_hover.tga"
		}
	}

	MIN_WIDTH = 30
	HEIGHT = 30

	def __init__(self, layer = "UI"):
		Window.__init__(self, layer)

		self.__state = ExpanderState.COLLAPSED
		self.__arrowRotation = 0.0
		
		self.__CreateUI()
		self.__SetEventListeners()

		self.SetWidth(0)
		self.SetState(ExpanderState.COLLAPSED)

	def __del__(self):
		Window.__del__(self)

	def __CreateUI(self):
		self.__dictImages = {
			'LEFT' : {
				ExpanderState.EXPANDED : ImageBox(),
				ExpanderState.COLLAPSED : ImageBox()
			},
			'CENTER' : {
				ExpanderState.EXPANDED : ExpandedImageBox(),
				ExpanderState.COLLAPSED : ExpandedImageBox()
			},
			'RIGHT' : {
				ExpanderState.EXPANDED : ImageBox(),
				ExpanderState.COLLAPSED : ImageBox()
			}
		}

		self.__txtText = None

		for position, imageDictByState in self.__dictImages.iteritems():
			for state, image in imageDictByState.iteritems():
				image.SetParent(self)
				image.AddFlag("not_pick")
				image.LoadImage("%s/%s" % (Expander.BASE_PATH, Expander.IMAGES[position][state]))
				image.Hide()

		self.__imgArrowBackground = ImageBox()
		self.__imgArrowBackground.SetParent(self)
		self.__imgArrowBackground.AddFlag("not_pick")
		self.__imgArrowBackground.SetPosition(0, 0)
		self.__imgArrowBackground.LoadImage("%s/arrow_bg.tga" % Expander.BASE_PATH)
		self.__imgArrowBackground.Show()

		self.__imgArrow = ExpandedImageBox()
		self.__imgArrow.SetParent(self.__imgArrowBackground)
		self.__imgArrow.AddFlag("not_pick")
		self.__imgArrow.SetPosition(0, 0)
		self.__imgArrow.LoadImage("%s/arrow.tga" % Expander.BASE_PATH)
		self.__imgArrow.SetHorizontalAlign(wndMgr.HORIZONTAL_ALIGN_CENTER)
		self.__imgArrow.SetVerticalAlign(wndMgr.VERTICAL_ALIGN_CENTER)
		self.__imgArrow.Show()

	
	def __SetEventListeners(self):
		self.AddEventListener(Expander.Events.ON_MOUSE_OVER_IN, lambda : self.__RefreshButton(ExpanderState.EXPANDED))
		self.AddEventListener(Expander.Events.ON_MOUSE_OVER_OUT, lambda : self.__RefreshButton(ExpanderState.COLLAPSED))
		self.AddEventListener(Expander.Events.ON_MOUSE_LEFT_BUTTON_UP, lambda : self.SetState(ExpanderState.EXPANDED if self.GetState() == ExpanderState.COLLAPSED else ExpanderState.COLLAPSED))

	def __RefreshButton(self, expandingState):
		for position, imageDictByState in self.__dictImages.iteritems():
			for state, image in imageDictByState.iteritems():
				if state != expandingState:
					image.Hide()
				else:
					image.Show()

		if self.GetState() == ExpanderState.COLLAPSED:
			self.__imgArrow.SetRotation(self.__arrowRotation)
		else:
			self.__imgArrow.SetRotation(180.0 + self.__arrowRotation)
	
	def GetState(self):
		return self.__state

	def SetState(self, state):
		self.__state = state
		self.__RefreshButton(self.__state)

	def SetWidth(self, width):
		width = max(Expander.MIN_WIDTH, width)

		self.SetSize(width, Expander.HEIGHT)

		for image in self.__dictImages['CENTER'].itervalues():
			image.SetPosition(5, 0)
			image.SetScale(float(width - 10), 1.0)

		for image in self.__dictImages['RIGHT'].itervalues():
			image.SetPosition(width - 5, 0)

		self.UpdateText()

	def SetArrowRotation(self, rotation):
		self.__arrowRotation = rotation
		self.__imgArrow.SetRotation(rotation)
	
	## Text
	def SetText(self, text):
		if not self.__txtText:
			self.__txtText = TextLine()
			self.__txtText.SetParent(self)
			self.__txtText.AddFlag("not_pick")
			self.__txtText.SetVerticalAlignCenter()
			self.__txtText.SetPackedFontColor(0xFFE6D0A2)
			self.__txtText.Show()

			self.UpdateText()

		self.__txtText.SetText(text)

	def GetText(self):
		if not self.__txtText:
			return ""
		
		return self.__txtText.GetText()

	def UpdateText(self):
		if not self.__txtText:
			return

		self.__txtText.SetPosition(35, self.GetHeight() / 2 - 2)

	##################################################
	## EVENTS

	class Events(Window.Events):
		ON_EXPAND = EventEnum()
		ON_COLLAPSE = EventEnum()
Example #24
0
class _BaseInput(Window):
	BASE_PATH = "%s/controls/common/input/" % illumina.BASE_PATH

	FILE_NAME_PREFIX = ""

	MIN_WIDTH = 0
	HEIGHT = 0

	TEXT_PADDING = (3, 3)
	TEXT_COLOR = 0xffffffff

	def __init__(self, layer = "UI"):
		Window.__init__(self, layer)

		self.__CreateUI()

		self.AddEventListener(Window.Events.ON_SET_FOCUS, self.__OnSetFocus)

	def __del__(self):
		Window.__del__(self)

	def __CreateUI(self):
		self.__dictImages = {
			'LEFT' : ImageBox(),
			'CENTER' : ExpandedImageBox(),
			'RIGHT' : ImageBox()
		}

		for position, image in self.__dictImages.iteritems():
			image.SetParent(self)
			image.AddFlag("not_pick")
			image.LoadImage("%s/%s_%s.tga" % (self.BASE_PATH, self.FILE_NAME_PREFIX, position.lower()))
			image.Show()

		self.__dictImages['CENTER'].SetPosition(self.__dictImages['LEFT'].GetWidth(), 0)

		self.__txtInput = None
		self.__textAlign = _BaseInput.TextAlign.LEFT

	def SetWidth(self, width):
		width = max(self.__dictImages['LEFT'].GetWidth() + self.__dictImages['RIGHT'].GetWidth(), width)

		Window.SetSize(self, width, self.HEIGHT)

		self.__dictImages['CENTER'].SetScale((width - (self.__dictImages['LEFT'].GetWidth() + self.__dictImages['RIGHT'].GetWidth())) / self.__dictImages['CENTER'].GetWidth(), 1.0)
		self.__dictImages['RIGHT'].SetPosition(width - self.__dictImages['RIGHT'].GetWidth(), 0)

		if self.__txtInput:
			self.__txtInput.SetSize(self.GetWidth() - self.TEXT_PADDING[0], self.GetHeight() - self.TEXT_PADDING[1])
			self.ArrangeText()

	def __OnSetFocus(self):
		if not self.__txtInput:
			return
		
		self.__txtInput.SetFocus()

	## TEXT
	def SetTextInstance(self, allowEdit = True):
		if self.__txtInput:
			self.DeleteTextInstance()

		if allowEdit:
			self.__txtInput = EditLine()
		else:
			self.__txtInput = TextLine()
		self.__txtInput.SetParent(self)
		self.__txtInput.SetSize(self.GetWidth() - self.TEXT_PADDING[0] * 2, self.GetHeight() - self.TEXT_PADDING[1] * 2)
		self.__txtInput.SetPackedFontColor(self.TEXT_COLOR)
		self.__txtInput.Show()

		self.ArrangeText()

	def DeleteTextInstance(self):
		if not self.__txtInput:
			return
		
		self.__txtInput.Hide()
		del self.__txtInput

	def GetTextInstance(self):
		return self.__txtInput
	
	class TextAlign:
		LEFT = 0
		CENTER = 1
		RIGHT = 2

	def SetTextAlign(self, align):
		self.__textAlign = align

		self.ArrangeText()

	def ArrangeText(self):
		if not self.__txtInput:
			return

		if self.__textAlign == _BaseInput.TextAlign.LEFT:
			self.__txtInput.SetPosition(self.TEXT_PADDING[0], self.TEXT_PADDING[1])
			self.__txtInput.SetHorizontalAlignLeft()
		elif self.__textAlign == _BaseInput.TextAlign.CENTER:
			self.__txtInput.SetPosition(self.GetWidth() / 2, self.TEXT_PADDING[1])
			self.__txtInput.SetHorizontalAlignCenter()
		elif self.__textAlign == _BaseInput.TextAlign.RIGHT:
			self.__txtInput.SetPosition(self.GetWidth() - self.TEXT_PADDING[0], self.TEXT_PADDING[1])
			self.__txtInput.SetHorizontalAlignRight()
Example #25
0
class _BaseButton(Window):
    class WidthType(object):
        STRETCH = 0
        REPEAT = 1

    BASE_PATH = "%s/controls/common/button/" % illumina.BASE_PATH

    IMAGES = None

    OPACITY = {
        _ButtonState.NORMAL: 1.0,
        _ButtonState.HOVER: 1.0,
        _ButtonState.ACTIVE: 1.0,
        _ButtonState.DISABLED: 1.0
    }

    WIDTH = None
    HEIGHT = None

    WIDTH_TYPE = None

    TEXT_COLOR = None

    def __init__(self, layer="UI"):
        Window.__init__(self, layer)

        self.__state = _ButtonState.NORMAL

        self.__CreateUI()
        self._SetEventListeners()

        self.SetWidth(0)
        self.SetState(_ButtonState.NORMAL)

    def __del__(self):
        Window.__del__(self)

    def __CreateUI(self):
        self.__dictImages = {
            'LEFT': {
                _ButtonState.NORMAL: ImageBox(),
                _ButtonState.HOVER: ImageBox(),
                _ButtonState.ACTIVE: ImageBox(),
                _ButtonState.DISABLED: ImageBox()
            },
            'CENTER': {
                _ButtonState.NORMAL: ExpandedImageBox(),
                _ButtonState.HOVER: ExpandedImageBox(),
                _ButtonState.ACTIVE: ExpandedImageBox(),
                _ButtonState.DISABLED: ExpandedImageBox()
            },
            'RIGHT': {
                _ButtonState.NORMAL: ImageBox(),
                _ButtonState.HOVER: ImageBox(),
                _ButtonState.ACTIVE: ImageBox(),
                _ButtonState.DISABLED: ImageBox()
            }
        }

        self.__txtText = None

        for position, imageDictByState in self.__dictImages.iteritems():
            for state, image in imageDictByState.iteritems():
                image.SetParent(self)
                image.AddFlag("not_pick")
                image.LoadImage(self.IMAGES[position][state])
                image.Hide()

    def _SetEventListeners(self):
        self.AddEventListener(
            _BaseButton.Events.ON_MOUSE_OVER_IN,
            lambda state=_ButtonState.HOVER: self.SetState(state, True))
        self.AddEventListener(
            _BaseButton.Events.ON_MOUSE_OVER_OUT,
            lambda state=_ButtonState.NORMAL: self.SetState(state, True))
        self.AddEventListener(
            _BaseButton.Events.ON_MOUSE_LEFT_BUTTON_DOWN,
            lambda state=_ButtonState.ACTIVE: self.SetState(state, True))
        self.AddEventListener(_BaseButton.Events.ON_MOUSE_LEFT_BUTTON_UP,
                              self.OnClick)
        self.AddEventListener(_BaseButton.Events.ON_CLICK,
                              lambda state=-1: self.SetState(state, True))

    def __RefreshButton(self):
        for position, imageDictByState in self.__dictImages.iteritems():
            for state, image in imageDictByState.iteritems():
                if state != self.GetState():
                    image.Hide()
                else:
                    image.SetAlpha(self.OPACITY[self.GetState()])
                    image.Show()

        self.UpdateTextColor()

    def GetState(self):
        return self.__state

    def SetState(self, state, byEvent=False):
        if byEvent and self.IsDisabled():
            return

        callEnableEvent = self.GetState() == _ButtonState.DISABLED

        self.__state = state
        if self.GetState() < _ButtonState.NORMAL or self.GetState(
        ) > _ButtonState.DISABLED:
            if self.IsIn():
                self.__state = _ButtonState.HOVER
            else:
                self.__state = _ButtonState.NORMAL

        self.__RefreshButton()

        if callEnableEvent:
            self.CallEventListener(_BaseButton.Events.ON_ENABLE)
        elif self.IsDisabled():
            self.CallEventListener(_BaseButton.Events.ON_DISABLE)

    def SetEnabled(self, enabled=True):
        if enabled and self.IsDisabled():
            self.SetState(_ButtonState.NORMAL)
        elif not enabled and not self.IsDisabled():
            self.SetState(_ButtonState.DISABLED)

    def IsDisabled(self):
        return self.GetState() == _ButtonState.DISABLED

    def SetWidth(self, width):
        width = max(self.WIDTH['LEFT'] + self.WIDTH['RIGHT'], width)

        self.SetSize(width, self.HEIGHT)

        for image in self.__dictImages['CENTER'].itervalues():
            image.SetPosition(self.WIDTH['LEFT'], 0)
            rect = float(width -
                         (self.WIDTH['LEFT'] + self.WIDTH['RIGHT'])) / float(
                             self.WIDTH['CENTER'])
            if self.WIDTH_TYPE == _BaseButton.WidthType.STRETCH:
                image.SetScale(rect, 1.0)
            else:
                image.SetRenderingRect(0.0, 0.0, -1.0 + rect, 0.0)

        for image in self.__dictImages['RIGHT'].itervalues():
            image.SetPosition(width - self.WIDTH['RIGHT'], 0)

        self.UpdateText()

    ## Text
    def SetText(self, text):
        if not self.__txtText:
            self.__txtText = TextLine()
            self.__txtText.SetParent(self)
            self.__txtText.AddFlag("not_pick")
            self.__txtText.SetHorizontalAlignCenter()
            self.__txtText.SetVerticalAlignCenter()
            self.__txtText.Show()

            self.UpdateText()
            self.UpdateTextColor()

        self.__txtText.SetText(text)

    def GetText(self):
        if not self.__txtText:
            return ""

        return self.__txtText.GetText()

    def UpdateText(self):
        if not self.__txtText:
            return

        self.__txtText.SetPosition(self.GetWidth() / 2,
                                   self.GetHeight() / 2 - 2)

    def UpdateTextColor(self):
        if not self.__txtText:
            return

        self.__txtText.SetPackedFontColor(self.TEXT_COLOR[self.GetState()])

    ##################################################
    ## EVENTS

    class Events(Window.Events):
        ON_CLICK = EventEnum()

        ON_DISABLE = EventEnum()
        ON_ENABLE = EventEnum()

    def OnClick(self):
        if self.IsDisabled():
            return

        self.CallEventListener(_BaseButton.Events.ON_CLICK)
Example #26
0
def loadTelegrams(sampleDataFileName):

    telegrams = {}

    with open(sampleDataFileName) as csvfile:
        parsedCsv = csv.DictReader(csvfile)
        nTelegramsParsed = 0
        for recordIndex, record in enumerate(parsedCsv):
            done = False
            recordIsTelegram = True

            # check the date that the classification was made
            if "metadata" in record:
                parsedMetadata = json.loads(record["metadata"])
                parsedDate = dateutil.parser.parse(
                    parsedMetadata['started_at'])
                # skip "testing" data before the site went live
                if parsedDate < liveDate:
                    continue

            # parse the annotations and the subject data
            parsedAnnotations = json.loads(record["annotations"])
            parsedSubjectData = json.loads(record["subject_data"])

            # initialize container for transcribed lines
            transcribedLines = TelegramLines()

            # loop over tasks in the annotation
            for task in parsedAnnotations:
                # Check if the current record is for a telegram (tasks may be stored out of order, so
                # some tasks may be processed before non-telegrams are caught -
                # inefficient but unavoidable?)
                if task['task'] == "T1" and (
                        task['value'] is None
                        or not task['value'].startswith("Telegram")):
                    recordIsTelegram = False
                    break

                # Process transcriptions of text lines
                if task['task'].startswith("T12") and len(task['value']) > 0:
                    # process the lines that were transcribed for this task
                    for taskValueItem in task['value']:
                        transcribedLine = TextLine(
                            taskValueItem['x1'], taskValueItem['y1'],
                            taskValueItem['x2'], taskValueItem['y2'],
                            taskValueItem['details'][0]['value'])
                        transcribedLines.addLine(transcribedLine)

            # if the transcribed lines of a telegram have been processed then update the
            # list of independent transcriptions for this subject
            if recordIsTelegram:
                nTelegramsParsed += 1
                if int(record['subject_ids']) in telegrams:
                    telegrams[int(record['subject_ids'])].append(
                        (recordIndex, transcribedLines))
                else:
                    telegrams.update({
                        int(record['subject_ids']): [(recordIndex,
                                                      transcribedLines)]
                    })

    return telegrams, nTelegramsParsed