Esempio n. 1
0
def main_manager():
    """Show and start availables options"""
    while "User don't use 0 to exit":

        # Clear then show main application options
        os.system('cls' if os.name=='nt' else 'clear')
        print(Color.cyan("\t<<< Menu Principal >>>"))
        print("{} - {}".format(Color.green("1"), "Trouver un produit (Catégorie > Produit)"))
        print("{} - {}".format(Color.green("2"), "Afficher les produits substitué"))
        print("{} - {}".format(Color.green("3"), "Mettre à jour les catégories"))
        uinput = input(Color.cyan("(Entrez: Un numéro pour choisir un menu | 0 pour quitter)\n"))

        # Exit substitute manager
        if uinput is '0':
            break

        # Open categorie manager
        if uinput is '1':
            categorie_manager()
            continue

        # Open db substitute manager
        if uinput is '2':
            db_substitute_manager()
            continue

        # Update categorie in database
        if uinput is '3':
            print("Mise à jour des catégories en cours...")
            update_categories()
            continue
Esempio n. 2
0
 def item(self, name, pos, hpr0=HPR(0, 0, 0), size=0.2, action=None):
     if action == "bounce":
         item = rectangle(pos,
                          pos + P3(0, size, 0),
                          pos + P3(0, 0, size),
                          texture=name,
                          color=Color(0, 0, 0, 0),
                          hpr=hpr0)
     elif action == "spin":
         item = rectangle(pos,
                          pos + P3(0, size, 0),
                          pos + P3(0, 0, size),
                          texture=name,
                          color=Color(0, 0, 0, 0))
     elif action == "both":
         item = rectangle(pos,
                          pos + P3(0, size, 0),
                          pos + P3(0, 0, size),
                          texture=name,
                          color=Color(0, 0, 0, 0))
     else:
         item = rectangle(pos,
                          pos + P3(0, size, 0),
                          pos + P3(0, 0, size),
                          texture=name,
                          color=Color(0, 0, 0, 0))
     items.append(item)
     return items[-1]
Esempio n. 3
0
    def _add_command(self, cmd_type, generic_params, **kwargs):
        # Set defaults
        Cmd = {'linewidth': 1.0, 'color': Color.Color("red")}

        # TBD - Check generic parameters against known params

        # Override
        for k in generic_params:
            if generic_params[k] is None:
                continue
            if k == 'color':
                Cmd[k] = Color.Color(generic_params[k])
            else:
                Cmd[k] = generic_params[k]

        # Set type
        Cmd['type'] = cmd_type

        # Set specific params
        for k in kwargs:
            if kwargs[k] is None:
                continue
            Cmd[k] = kwargs[k]

        self.display_list.append(Cmd)
Esempio n. 4
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        cp1 = Color.ColorPicker(self)
        cc = ChosenColor(self,(50,50))

        ss = Color.StylePicker(self)


        panel = wx.Panel(self)
        tt = ImageTile(panel,scale=2)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(tt, 1, wx.ALL|wx.ALIGN_CENTER, 0)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(hbox, 1, wx.ALL|wx.ALIGN_CENTER, 0)
        panel.SetSizer(vbox)


        vbox = wx.FlexGridSizer(rows=4,cols=1, hgap=5, vgap=5)
        vbox.Add(cc, 0, wx.ALL|wx.ALIGN_CENTER)
        vbox.Add(cp1, 0, wx.ALL|wx.ALIGN_CENTER)
        vbox.Add(ss, 0, wx.ALL|wx.ALIGN_CENTER)
        vbox.Add(panel, 0, wx.ALL|wx.ALIGN_CENTER)

        hbox = wx.BoxSizer(wx.VERTICAL)
        hbox.Add(vbox, 0, wx.ALL|wx.ALIGN_CENTER, 0)

        self.SetSizer(hbox)
Esempio n. 5
0
def substitute_manager(product):
    """Show and interact with selected product's list"""
    substitutes = get_substitutes(product)
    substitute_page = 0

    while "User don't use 0 to exit":

        # Clear then show products
        os.system('cls' if os.name=='nt' else 'clear')
        print(Color.cyan("Substitue du produit \"{}").format(Color.yellow(product.name)) + Color.cyan("\""))
        for i in range(min(20,(len(substitutes)-substitute_page*20))):
            print("{} - {} {}".format(Color.green(i+1), substitutes[i-substitute_page*20].name, substitutes[i-substitute_page*20].brands))
        uinput = input(Color.cyan("(Entrez: Numéro - selectionner un produit | S - page suivante | P - page précedente | 0 - revenir au produit {})\n").format(product.name))

        # Exit substitute manager
        if uinput is '0':
            break

        # Select product
        if uinput.isdigit():
            product_manager(substitutes[int(uinput)-1-substitute_page*20], "Substitution de {}".format(product.name))
            continue

        # Change page
        if uinput.isalpha():
            if uinput.lower() == 's':
                substitute_page += 1
            if uinput.lower() == 'p':
                if substitute_page > 0:
                    substitute_page -= 1
Esempio n. 6
0
def get_token(url):
    global session, site_key, api_key, gui

    s = requests.Session()

    try:
        captcha_id = s.post(
            "http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}&invisible=1"
            .format(api_key, site_key, url)).text.split('|')[1]

        recaptcha_answer = s.get(
            "http://2captcha.com/res.php?key={}&action=get&id={}".format(
                api_key, captcha_id)).text

        while 'CAPCHA_NOT_READY' in recaptcha_answer:
            sleep(5)
            recaptcha_answer = s.get(
                "http://2captcha.com/res.php?key={}&action=get&id={}".format(
                    api_key, captcha_id)).text

        recaptcha_answer = recaptcha_answer.split('|')[1]

        # print("[Recaptcha answer] : {",recaptcha_answer,"}")
        return recaptcha_answer

    except Exception:
        Color.printer("ERROR", 'Failed to solve ReCaptcha!', gui)
        return None
Esempio n. 7
0
def categorie_product_manager(categorie_id):
    """Show and interact with categorie's product"""
    categorie_page = 1
    categorie_products = get_categorie_products(categories[categorie_id].url, categorie_page)
    while "User don't use 0 to exit":
        # Clear then show products
        os.system('cls' if os.name=='nt' else 'clear')
        print(Color.cyan("Categorie \"{}").format(Color.yellow(categories[categorie_id].name)) + Color.cyan("\" Page {}").format(categorie_page))
        for i in range(min(20,len(categorie_products))):
            print("{} - {} {}".format(Color.green(i+1), categorie_products[i].name, categorie_products[i].brands))
        uinput = input(Color.cyan("(Entrez: Numéro - selectionner un produit | S - page suivante | P - page précedente | 0 - revenir aux catégories)\n"))

        # Exit catagorie product manager
        if uinput is '0':
            break

        # Select product
        if uinput.isdigit():
            product_manager(categorie_products[int(uinput)-1], categories[categorie_id].name)
            continue

        # Change page
        if uinput.isalpha():
            if uinput.lower() == 's':
                categorie_page += 1
            if uinput.lower() == 'p':
                categorie_page -= 1
            categorie_products = get_categorie_products(categories[categorie_id].url, categorie_page)
Esempio n. 8
0
def extract_download_urls():
    global session, gui
    down_base = "https://9anime.to/ajax/episode/info?"

    Color.printer("INFO", "Extracting download URLs...", gui)
    for episode in episodes:
        if (episode.id is None):
            episode.download_url = None
            continue

        url = down_base + "ts=" + ts_no + "&id=" + episode.id + "&server=" + server_id
        target = session.get(url).json()["target"]

        episode.page_url = target

        video_page = session.get(target).content

        string = video_page.decode("utf-8")

        www_base = re.search("false\|(.*)\|devicePixelRatio", string).group(1)
        url_id = re.search("video\|(.*)\|282", string).group(1)

        download_url = "https://" + www_base + ".mp4upload.com:282/d/" + url_id + "/video.mp4"

        episode.download_url = download_url
Esempio n. 9
0
    def Process_ResultsContainer(self):

        NRes = self.update_DataResults()
        self.ColorList = Color.GetHeatColorList(NRes, True)
        self.PymolColorList = Color.GetHeatColorList(NRes, False)

        self.Show_Results()
        self.update_DataList()
Esempio n. 10
0
    def __init__(self,
                 left=0,
                 top=0,
                 width=0,
                 height=0,
                 bg_color=None,
                 fg_color=None):
        self.left = left or 0
        self.top = top or 0
        self.width = width or 0
        self.height = height or 0
        try:
            self.rect = Rect(self.left, self.top, self.width, self.height)
        except TypeError:
            logger.debug('Invalid Rect: left=%r, top=%r, width=%r, height=%r',
                         left, top, width, height)

        self.osd = osd.get_singleton()

        self.label = None
        self.icon = None
        self.surface = None
        self.bg_surface = None
        self.bg_image = None

        self.parent = None

        self.children = []
        self.enabled = 1
        self.visible = 1
        self.selected = 0

        self.rect = pygame.Rect(0, 0, 0, 0)

        self.refresh_abs_position()

        self.rect.width = self.width
        self.rect.height = self.height
        self.bg_color = bg_color
        self.fg_color = fg_color

        self.event_context = None

        style = skin.get_singleton().get_popupbox_style(self)
        self.content_layout, self.background_layout = style

        self.skin_info_widget = self.content_layout.types['widget']
        self.skin_info_font = self.skin_info_widget.font

        self.h_margin = self.content_layout.spacing
        self.v_margin = self.content_layout.spacing

        ci = self.content_layout.types['widget'].rectangle
        self.bg_color = self.bg_color or Color(ci.bgcolor)
        self.fg_color = self.fg_color or Color(ci.color)

        self.set_v_align(Align.NONE)
        self.set_h_align(Align.NONE)
Esempio n. 11
0
def writeData():
    global episodes, gui

    Color.printer("INFO", "Writing results to results.csv file...", gui)
    data_file = open("results.csv", "w")
    for episode in episodes:
        data_file.write(episode.episode + "," + episode.download_url + "\n")

    data_file.close()
Esempio n. 12
0
    def SetColorList(self):

        nColor = self.TempBindingSite.Count_Cleft()

        if nColor > Color.NBCOLOR:
            nColor = Color.NBCOLOR

        self.ColorList = Color.GetHeatColorList(nColor, False)
        self.ColorHex = Color.GetHeatColorList(nColor, True)
Esempio n. 13
0
    def __init__(self, name):
        super(RandomMaterial, self).__init__(name)

        color = (random.random(), random.random(), random.random(), 1.0)
        rgb = Color.HSL_to_RGB(random.random(), 0.6, 0.6)

        rgb2 = Color.HSL_to_RGB(random.random(), 0.9, 0.5)
        color = (rgb[0], rgb[1], rgb[2], 1.0)
        color2 = (rgb2[0], rgb2[1], rgb2[2], 1.0)
        print(color)
        kind = random.randint(0, 9)
        state = State.instance
        if kind <= 3:
            node = None
            if kind == 0:
                node = self.createMetalNode(color)
                state.material_name = "metal"
            elif kind == 1:
                pure = random.randint(0, 1)
                if pure == 0:
                    node = self.createGlassNode(color, 0, 1.45)
                else:
                    node = self.createGlassNode(color,
                                                random.uniform(0.1, 0.5), 1.45)
                state.material_name = "glass"
            elif kind == 2:
                node = self.createDiffuseNode(color)
                state.material_name = "diffuse"
            elif kind == 3:
                node = self.createSubsurfaceNode(color, 1)
                state.material_name = "subsurface"
            state.color = color
            self.baseMaterial.node_tree.links.new(
                node.outputs[0],
                self.getOutputNode().inputs[0])
        else:
            mat = None
            if kind == 4:
                mat = CarPaintMaterial(color2)
                state.material_name = "car paint"
            elif kind == 5:
                mat = GalvanizedMetalMaterial(random.uniform(0.0, 1.0))
                state.material_name = "galvanized metal"
            elif kind == 6:
                mat = PianoPaintMaterial(color2)
                state.material_name = "paino paint"
            elif kind == 7:
                mat = LollipopMaterial(color2)
                state.material_name = "lollipop"
            elif kind == 8:
                mat = LegoPlasticMaterial(color2)
                state.material_name = "lego plastic"
            elif kind == 9:
                mat = LedMaterial(color2)
                state.material_name = "led"
            self.baseMaterial = mat.baseMaterial
            state.color = color2
Esempio n. 14
0
def categorie_manager():
    """Show and interact with categorie"""
    global categories
    categories = get_categories()
    filter_categories = list()

    while "User don't use 0 to exit":
        # Clear then show catagorie
        os.system('cls' if os.name == 'nt' else 'clear')
        if len(filter_categories):
            print(
                Color.cyan("Sélectionnez une catégorie (filté par \"{}\"):").
                format(uinput))
            for i in range(min(20, len(filter_categories))):
                print("{} - {} ({} produits)".format(
                    Color.green(filter_categories[i].id),
                    filter_categories[i].name, filter_categories[i].products))
        else:
            print(Color.cyan("Sélectionnez une catégorie:"))
            for i in range(min(20, len(categories))):
                print("{} - {} ({} produits)".format(
                    Color.green(categories[i].id), categories[i].name,
                    categories[i].products))

        # User input
        uinput = input(
            Color.cyan(
                "(Entrez: Numéro - selectionner la catégorie | Lettre(s) - filtrer | 0 - revenir au menu principal)\n"
            ))

        # Exit
        if uinput is '0':
            break

        # Select Categorie
        if uinput.isdigit():
            categorie_product_manager(int(uinput) - 1)
            continue

        # Filter Categorie
        if uinput.isalpha():
            if len(uinput) == 1:
                filter_categories = [
                    elem for elem in categories
                    if elem.name[:1] == uinput[:1].upper()
                ]
            else:
                filter_categories = [
                    elem for elem in categories
                    if uinput.lower() in elem.name.lower()
                ]
            continue

        # Reset Filter
        if not uinput:
            filter_categories.clear()
            continue
 def run(self):
     while True:
         func, arg, kargs = self.tasks.get()
         try:
             func(*arg, **kargs)
         except Exception as ex:
             # print(ex)
             Color.printer("ERROR", ex)
         finally:
             self.tasks.task_done()
Esempio n. 16
0
    def __init__(self,
                 region_surface=None,
                 left=None,
                 top=None,
                 width=300,
                 height=160,
                 bg_color=None,
                 fg_color=None,
                 border=None,
                 bd_color=None,
                 bd_width=None,
                 show_h_scrollbar=None,
                 show_v_scrollbar=None):

        self.show_h_scrollbar = show_h_scrollbar
        self.show_v_scrollbar = show_v_scrollbar

        Container.__init__(self,
                           'widget',
                           left,
                           top,
                           width,
                           height,
                           bg_color,
                           fg_color,
                           border=border,
                           bd_color=bd_color,
                           bd_width=bd_width)

        self.internal_h_align = Align.NONE
        self.internal_v_align = Align.NONE

        if self.show_h_scrollbar != 0 and not self.show_h_scrollbar:
            self.show_h_scrollbar = 1
        if self.show_v_scrollbar != 0 and not self.show_v_scrollbar:
            self.show_v_scrollbar = 1

        self.set_surface(region_surface)
        self.x_scroll_interval = 25
        self.y_scroll_interval = 25
        self.h_margin = 2
        self.v_margin = 2

        self.v_scrollbar = Scrollbar(self, 'vertical')
        self.add_child(self.v_scrollbar)
        self.h_scrollbar = Scrollbar(self, 'horizontal')
        self.add_child(self.h_scrollbar)

        self.filler = self.osd.Surface(
            (self.v_scrollbar.thickness, self.h_scrollbar.thickness), 0, 32)
        filler_c = Color((0, 0, 0, 255))
        fc_c = filler_c.get_color_sdl()
        fc_a = filler_c.get_alpha()
        self.filler.fill(fc_c)
        self.filler.set_alpha(fc_a)
Esempio n. 17
0
    def __init__(self, name, color):
        super(CarPaintMaterial, self).__init__(name, "20-car-paint",
                                               "BMD_CarPaint_0020")
        node = self.getNodeByType("BMD_CarPaintShader")
        node.inputs[0].default_value = color
        node.inputs[2].default_value = color

        rgb = (color[0], color[1], color[2])
        hsl = Color.RGB_to_HSL(color[0], color[1], color[2])
        rgb = Color.HSL_to_RGB(hsl[0], hsl[1], hsl[2] / 2)

        node.inputs[1].default_value = (color[0], color[1], color[2], 1.0)
Esempio n. 18
0
    def render(self, graph):
        ''' this function renders the mandelbrot into the graph, using the
        parameters specified in the data boxes. If the input value is wrong
        the box will turn red
        '''

        # gather the user inputs and check validity
        minx = self.data_boxes.get("x min")
        maxx = self.data_boxes.get("x max")
        miny = self.data_boxes.get("y min")
        maxy = self.data_boxes.get("y max")
        it = self.data_boxes.get("max iterations")

        # this user inputs are strings so they will always be in a valid
        # format.
        # yet they are keys into dictonaries, so if the key is missng
        # the error handling is inside the next body
        mode = self.data_boxes.data_boxes["mode"].entry.get()
        colormap = self.data_boxes.data_boxes["colormap"].entry.get()

        print("start rendering...")
        print("max iteration: " + str(it))

        # run the render
        correct_format = [
            True if v is not None else False
            for v in [minx, maxx, miny, maxy, it]
        ]

        if any(correct_format):
            color_matrix = None
            # this will try to render the mandelbrot, if the mode or the
            # colormaps are wrong it will turn the boxes red
            try:
                bounds = Mandelbrot.Boundaries(graph.width, graph.height, minx,
                                               maxx, miny, maxy)
                self.mandelbrot = Mandelbrot.Mandelbrot(
                    bounds, it, mode, colormap)
                color_matrix = self.mandelbrot.get_color_matrix()

            except Mandelbrot.KeyErrorMode:
                self.data_boxes.data_boxes["mode"].set_color(
                    Color.Color(255, 0, 0))

            except Mandelbrot.KeyErrorColormap:
                self.data_boxes.data_boxes["colormap"].set_color(
                    Color.Color(255, 0, 0))

            if color_matrix is not None:
                graph.update_image(color_matrix)
                graph.draw()
                print("rendering done")
Esempio n. 19
0
 def _interp(t):
     a = start.a * (1 - t) + end.a * t
     if (a < 1e-5): a = 0
     if start.a == 0:
         return Color.rgb(end.r,end.g,end.b,a)
     elif end.a == 0:
         return Color.rgb(start.r,start.g,start.b,a)
     else:
         return Color.rgb(
                           round(start.r * (1 - t) + end.r * t),
                           round(start.g * (1 - t) + end.g * t),
                           round(start.b * (1 - t) + end.b * t),
                           a)
Esempio n. 20
0
    def ShowRandomEarth(self):
        self.ShowObjects([
            'Planet_Procedural', 'Planet_ATMOS', 'Planet_Clouds',
            'Planet_Clouds.Outer', 'Planet_LightsMask'
        ])
        nodes = self.GetMaterialNodes('Planet_Procedural')

        #land
        color2 = Color.HSL_to_RGB(self.main_h, 0.7, 0.7)
        nodes["Mix.016"].inputs[2].default_value = Color.RGB_to_RGBA(color2)
        #ocean
        color = Color.HSL_to_RGB(self.second_h, 1.0, 0.5)
        nodes["Mix.017"].inputs[2].default_value = Color.RGB_to_RGBA(color)

        nodes = self.GetMaterialNodes('Planet_ATMOS')
        color3 = Color.HSL_to_RGB(
            self.second_h + (random.random() - 0.5) * 0.01, 0.6, 0.25)
        nodes["Emission"].inputs[0].default_value = Color.RGB_to_RGBA(color3)

        has_cloud = random.random() > 0.3
        if has_cloud:
            nodes = self.GetMaterialNodes('Planet_Clouds')
            color4 = Color.HSL_to_RGB(
                self.main_h + (random.random() - 0.5) * 0.05, 0.3,
                random.random() * 0.7)
            nodes["ColorRamp.002"].color_ramp.elements[
                1].color = Color.RGB_to_RGBA(color4)

        self.RandomNoise()
Esempio n. 21
0
def Recolor(bitmap, newstyle):
    if not Color.STYLE == newstyle:
        dc = wx.MemoryDC()
        dc.SelectObject(bitmap)
        Color.GetStyles()
        for y in range(0, bitmap.GetHeight()):
            for x in range(0, bitmap.GetWidth()):

                pixel = dc.GetPixel(x, y).GetAsString(flags=wx.C2S_HTML_SYNTAX)
                dc.SetBrush(wx.Brush(Color.Convert(pixel, newstyle)))
                dc.SetPen(wx.Pen(Color.Convert(pixel, newstyle)))
                dc.DrawPoint(x, y)

        dc.SelectObject(wx.NullBitmap)
        Color.ChangeStyle(newstyle)
Esempio n. 22
0
    def __init__(self,
                 parent,
                 orientation,
                 thickness=10,
                 left=None,
                 top=None,
                 width=None,
                 height=None,
                 bg_color=None,
                 fg_color=None,
                 border=None,
                 bd_color=None,
                 bd_width=1):

        if orientation != "vertical" and orientation != "horizontal":
            raise TypeError, 'orientation'

        GUIObject.__init__(self, left, top, width, height)

        self.orientation = orientation
        self.bg_color = bg_color
        self.fg_color = fg_color
        self.thickness = thickness
        self.border = border
        self.bd_color = bd_color
        self.bd_width = bd_width

        if not self.bg_color:
            if self.skin_info_widget.rectangle.bgcolor:
                self.bg_color = Color(self.skin_info_widget.rectangle.bgcolor)
            else:
                self.bg_color = Color(self.osd.default_bg_color)

        if not self.fg_color:
            if self.skin_info_widget.font.color:
                self.fg_color = Color(self.skin_info_widget.font.color)
            else:
                self.fg_color = Color(self.osd.default_fg_color)

        if not self.bd_color:
            if self.skin_info_widget.rectangle.color:
                self.bd_color = Color(self.skin_info_widget.rectangle.color)
            else:
                self.bd_color = Color(self.osd.default_fg_color)

        if not self.border:
            self.border = Border(self, Border.BORDER_FLAT, self.bd_color,
                                 self.bd_width)
Esempio n. 23
0
    def read_csv(self):
        # method reads the colors.csv file into local variables

        # delete current color data
        del self.__colors[:]
        del self.__color_names[:]

        # open colors.csv
        csv_file = self.__def_name
        file = open(csv_file, "r")

        # read color label, exclusivity, hsv min, and hsv max values from color
        # file and store data in local vars
        for line in file:
            line = line.strip()
            csv_line = line.split(",")
            name = csv_line[0]
            hsv_min = [int(csv_line[1]), int(csv_line[2]), int(csv_line[3])]
            hsv_max = [int(csv_line[4]), int(csv_line[5]), int(csv_line[6])]

            exclusive = None
            if csv_line[7] == "FALSE":
                exclusive = False

            elif csv_line[7] == "TRUE":
                exclusive = True

            self.__color_names.append(name)
            new_Obj = color.Color(name, hsv_min, hsv_max, exclusive)
            self.__colors.append(new_Obj)

        file.close()
Esempio n. 24
0
    def do(self, action, step, rainbow):
        if len(action) > 1:
            p = action[1]
        else:
            p = 1.0

        self.timebuff += step
        cmd = action[0].lower()
        if cmd == "draw":
            if rainbow:
                self.incColor()
                if self.incThickYN:
                    self.incThick(self.reverseThick, False)
            elif self.incThickYN:
                self.incThick(self.reverseThick, True)
            if self.timebuff > 1.0:
                truncate = int(self.timebuff)
                self.after(truncate, self.draw(float(p), True))
                self.timebuff -= truncate
            else:
                self.draw(float(p))
        elif cmd == "turn":
            Draw.turn(float(p))
        elif cmd == "skip":
            Draw.skip(float(p))
        elif cmd == "back":
            Draw.back(float(p))
        elif cmd == "color":
            if not rainbow:
                self.color = Color.getHexString(p)
        elif cmd == "thick":
            self.thick = int(p)
        else:
            print("Unknown command " + cmd)
Esempio n. 25
0
  def start(self):

    # GCompris initialisation
    self.gcomprisBoard.level=1
    self.gcomprisBoard.maxlevel=1
    self.gcomprisBoard.sublevel=0
    self.gcomprisBoard.number_of_sublevel=0

    gcompris.set_default_background(self.gcomprisBoard.canvas.get_root_item())

    # Create our rootitem. We put each canvas item in it so at the end we
    # only have to kill it. The canvas deletes all the items it contains automaticaly.
    self.rootitem = goocanvas.Group(
      parent =  self.gcomprisBoard.canvas.get_root_item())

    self.doc = Document(self)

    # initialisation
    self.draw_tools()
    self.draw_animtools()

    self.doc.timeline.draw()
    if self.gcomprisBoard.mode == 'draw':
      self.doc.timeline.hide()

    self.color_rootitem = goocanvas.Group(
      parent =  self.gcomprisBoard.canvas.get_root_item())
    self.color = Color(self.color_rootitem, self.drawing_area)
    self.color.draw()

    self.draw_drawing_area()
    self.draw_playing_area()

    gcompris.bar_set(0)
    gcompris.bar_location(10, -1, 0.6)
Esempio n. 26
0
    def __init__(self,
                 path,
                 radius=10,
                 center_x=0,
                 center_y=0,
                 center_z=0,
                 is_hide=False):
        self.vertexes = []
        self.triangles = []

        self.center = Vector3(0, 0, 0)
        self.set_center(center_x, center_y, center_z)
        self.proceed_vector = Vector3(0, 0, 0)

        self.face_color = Color(0.0, 0.0, 0.0, 1.0)
        self.is_hide = is_hide

        # objファイル読み込み
        lines = read_file_line(path)
        vertexes = vertex_list(lines)
        triangles = triangle_list(lines)

        # 頂点座標
        for vertex in vertexes:
            x = vertex[0]
            y = vertex[1]
            z = vertex[2]
            self.add_vertex(Vertex(x, y, z))

        # 三角形を生成する
        for triangle in triangles:
            # 頂点x,y,z座標の配列を格納する
            self.add_triangle(Triangle(triangle))
Esempio n. 27
0
 def _add_fix(self, node):  # восстановление свойств красно-черного дерева
     c = Color.Color()
     while node.parent.color:
         u = self._uncle(node)
         if u.color:
             node.parent._color = c.BLACK
             u._color = c.BLACK
             self._grandfather(node)._color = c.RED
             node = self._grandfather(node)
         else:
             if node.parent == node.parent.parent.leftChild:
                 if node == node.parent.rightChild:
                     node = node.parent
                     self._turn_left(node)
                 node.parent._color = c.BLACK
                 self._grandfather(node)._color = c.RED
                 self._turn_right(self._grandfather(node))
             else:
                 if node == node.parent.leftChild:
                     node = node.parent
                     self._turn_right(node)
                 node.parent._color = c.BLACK
                 self._grandfather(node)._color = c.RED
                 self._turn_left(self._grandfather(node))
     self.root._color = c.BLACK
Esempio n. 28
0
 def delete_node(self, node):
     c = Color.Color()
     if not node or node == self.nil:
         return
     if node.leftChild == self.nil or node.rightChild == self.nil:
         y_node = node
     else:
         y_node = node.rightChild
         while y_node.leftChild != self.nil:
             y_node = y_node.leftChild
     if y_node.leftChild != self.nil:
         x = y_node.leftChild
     else:
         x = y_node.rightChild
     x._parent = y_node.parent
     if y_node.parent:
         if y_node == y_node.parent.leftChild:
             y_node.parent._leftChild = x
         else:
             y_node.parent._rightChild = x
     else:
         self._root = x
     if y_node != node:
         node._data = y_node.data
     if y_node.color == c.BLACK:
         self._delete_fix(x)
Esempio n. 29
0
    def __init__(self,
                 left=0,
                 top=0,
                 width=0,
                 height=0,
                 bg_color=None,
                 fg_color=None):

        self.osd = osd.get_singleton()

        self.label = None
        self.icon = None
        self.surface = None
        self.bg_surface = None
        self.bg_image = None

        self.parent = None

        self.children = []
        self.enabled = 1
        self.visible = 1
        self.selected = 0

        self.left = left
        self.top = top
        self.width = width
        self.height = height
        self.bg_color = bg_color
        self.fg_color = fg_color

        self.event_context = None

        style = skin.get_singleton().get_popupbox_style(self)
        self.content_layout, self.background_layout = style

        self.skin_info_widget = self.content_layout.types['widget']
        self.skin_info_font = self.skin_info_widget.font

        self.h_margin = self.content_layout.spacing
        self.v_margin = self.content_layout.spacing

        ci = self.content_layout.types['widget'].rectangle
        self.bg_color = self.bg_color or Color(ci.bgcolor)
        self.fg_color = self.fg_color or Color(ci.color)

        self.set_v_align(Align.NONE)
        self.set_h_align(Align.NONE)
 def __init__(self):
     self.selected = False
     self.highlighted = False
     self.copyOf = None
     self.deltaCenter = None
     self.graphicsItemsList = []
     self._name = ""
     self._parentItem = None
     self.mouseMoveDelta = None
     self._color = Color(0, 0, 200)
     self.defaultPen = QPen(self._color, 2, Qt.SolidLine, Qt.RoundCap)
     self.normalPen = self.defaultPen
     self.selectedPen = QPen(Qt.magenta, 3, Qt.SolidLine, Qt.RoundCap)
     self.highLightPen = QPen(Qt.blue, 4, Qt.SolidLine, Qt.RoundCap)
     self._currentPen = self.normalPen
     self._zIndex = 1
     self._id = 0
Esempio n. 31
0
def create_color(data):
    # print("Color_funtion")
    # Now Add Color in Piture
    global color_img
    sequence = 1
    color_data = []
    for img in data:
        if sequence % 3 == 0:
            color_img = Color.color_change(img, "front")
        elif sequence % 3 == 1:
            color_img = Color.color_change(img, "back")
        elif sequence % 3 == 2:
            color_img = Color.color_change(img, "f&b")
        color_data.append(color_img)
        sequence += 1

    return color_data
Esempio n. 32
0
    def write(window):

        id = write_text(window = window,
                        line='hello    world',
                        color=Color.white(),
                        coord=(200, 200),
                        transition=True)
        return id
Esempio n. 33
0
 def __init__(self, data):  # инициализация узла
     c = Color.Color()
     """setters"""
     self._data = data  # Некие данные, хранимые в узле. В данной реализации - целые числа
     self._color = c.BLACK  # Цвет узла: False = BLACK, True = RED
     self._leftChild = None
     self._rightChild = None
     self._parent = None  # Родитель узла
def press_start_blink(window):

    text_id = Graphics.write_text(window=window,
                                  line='PRESS START',
                                  coord=(230, 270),
                                  color=Color.white(),
                                  font = 'ArcadeClassic 20',
                                  transition=True)
def download_episode(episode):
    global titles

    Color.printer("INFO", "Downloading " + episode.episode + "...")

    if system() == "Windows":
        episode.title = clean_file_name(episode.title)

    if titles:
        file_name = directory + episode.episode + " - " + episode.title + ".mp4"
    else:
        file_name = directory + episode.episode + ".mp4"

    with requests.get(episode.download_url, stream=True, verify=False) as r:
        with open(file_name, 'wb') as f:
            shutil.copyfileobj(r.raw, f, length=16 * 1024 * 1024)

    Color.printer("INFO", episode.episode + " finished downloading...")
Esempio n. 36
0
	def setColors(self, r, g, b, a=1.0):
		"""
		Method for children who have special color values like, for example, tinting (see L{Sprite} and L{TintTo}).

		@param r: C{float}.
		@param g: C{float}.
		@param b: C{float}.
		@param a: C{float}.
		"""
		self._color = Color(r, g, b, a)
Esempio n. 37
0
def categorie_manager():
    """Show and interact with categorie"""
    global categories
    categories = get_categories()
    filter_categories = list()

    while "User don't use 0 to exit":
        # Clear then show catagorie
        os.system('cls' if os.name=='nt' else 'clear')
        if len(filter_categories):
            print(Color.cyan("Sélectionnez une catégorie (filté par \"{}\"):").format(uinput))
            for i in range(min(20,len(filter_categories))):
                print("{} - {} ({} produits)".format(Color.green(filter_categories[i].id), filter_categories[i].name, filter_categories[i].products))
        else:
            print(Color.cyan("Sélectionnez une catégorie:"))
            for i in range(min(20,len(categories))):
                print("{} - {} ({} produits)".format(Color.green(categories[i].id), categories[i].name, categories[i].products))

        # User input
        uinput = input(Color.cyan("(Entrez: Numéro - selectionner la catégorie | Lettre(s) - filtrer | 0 - revenir au menu principal)\n"))

        # Exit      
        if uinput is '0':
            break
    
        # Select Categorie
        if uinput.isdigit():
            categorie_product_manager(int(uinput)-1)
            continue
    
        # Filter Categorie
        if uinput.isalpha():
            if len(uinput) == 1:
                filter_categories = [elem for elem in categories if elem.name[:1] == uinput[:1].upper()]
            else:
                filter_categories = [elem for elem in categories if uinput.lower() in elem.name.lower() ]
            continue

        # Reset Filter
        if not uinput:
            filter_categories.clear()
            continue
Esempio n. 38
0
def db_substitute_manager():
    """Show and interact with selected product's list"""
    products = get_db_products()
    while "User don't use 0 to exit":

        # Clear then show products
        os.system('cls' if os.name=='nt' else 'clear')
        print(Color.cyan("Produit enregistré:"))
        for i in range(min(20,len(products))):
            print("{} - {} {}".format(Color.green(i+1), products[i].name, products[i].brands))
        uinput = input(Color.cyan("(Entrez: Numéro - selectionner un produit | S - page suivante | P - page précedente | 0 - revenir au menu principal)\n"))

        # Exit substitute manager
        if uinput is '0':
            break

        # Select product
        if uinput.isdigit():
            product_manager(products[int(uinput)-1], "menu principal")
            continue
Esempio n. 39
0
 def search(self):
     query = raw_input("请输入查询内容:".decode('utf-8').encode('gbk'))
     url = "http://www.douban.com/search?source=suggest&q="+query
     ans = urllib2.urlopen(url)
     result = ans.read()
     f = open('search.html','wb')
     f.write(result)
  
     match = re.findall(r'<span>\[(.*?)\]</span>.*? >(.*?)</a>.*?<span class="rating_nums">(.*?)</span>.*?<span>(.*?)</span>.*?<span class="subject-cast">(.*?)</span>.*?<p>(.*?)</p>',result,re.S)
     print len(match)
     for submatch in match:
         content = OrderedDict()
         content[u"类别"]=submatch[0].decode('utf-8')
         content[u"名称"]=submatch[1].decode('utf-8')
         content[u"评分"]=submatch[2].decode('utf-8')
         content[u"评价人数"]=submatch[3].decode('utf-8')
         content[u"说明"]=submatch[4].decode('utf-8')
         content[u"简介"]=submatch[5].decode('utf-8')
         for i in content:
             Color.setTextColor(Color.FOREGROUND_PINK)
             print i,
             Color.setTextColor(Color.FOREGROUND_BLUE)
             print content[i].encode('GB18030')
             Color.resetColor()
         print ''
Esempio n. 40
0
    def __init__(self, region_surface=None, left=None, top=None, width=300,
                 height=160, bg_color=None, fg_color=None, border=None,
                 bd_color=None, bd_width=None, show_h_scrollbar=None,
                 show_v_scrollbar=None):

        self.show_h_scrollbar = show_h_scrollbar
        self.show_v_scrollbar = show_v_scrollbar

        Container.__init__(self, 'widget', left, top, width, height, bg_color,
                           fg_color, border=border, bd_color=bd_color,
                           bd_width=bd_width)

        self.internal_h_align = Align.NONE
        self.internal_v_align = Align.NONE

        if self.show_h_scrollbar != 0 and not self.show_h_scrollbar:
            self.show_h_scrollbar = 1
        if self.show_v_scrollbar != 0 and not self.show_v_scrollbar:
            self.show_v_scrollbar = 1


        self.set_surface(region_surface)
        self.x_scroll_interval = 25
        self.y_scroll_interval = 25
        self.h_margin = 2
        self.v_margin = 2


        self.v_scrollbar = Scrollbar(self, 'vertical')
        self.add_child(self.v_scrollbar)
        self.h_scrollbar = Scrollbar(self, 'horizontal')
        self.add_child(self.h_scrollbar)

        self.filler = self.osd.Surface((self.v_scrollbar.thickness,
                                        self.h_scrollbar.thickness), 0, 32)
        filler_c = Color((0,0,0,255))
        fc_c = filler_c.get_color_sdl()
        fc_a = filler_c.get_alpha()
        self.filler.fill(fc_c)
        self.filler.set_alpha(fc_a)
Esempio n. 41
0
 def interpolator(self,start,end):
     """Returns fn that interpolates between given values"""
     if isinstance(start,numbers.Number):
         return lambda t: t * (end - start) + start
     
     # otherwise, assume color
     start = Color.color(start)
     end = Color.color(end)
     def _interp(t):
         a = start.a * (1 - t) + end.a * t
         if (a < 1e-5): a = 0
         if start.a == 0:
             return Color.rgb(end.r,end.g,end.b,a)
         elif end.a == 0:
             return Color.rgb(start.r,start.g,start.b,a)
         else:
             return Color.rgb(
                               round(start.r * (1 - t) + end.r * t),
                               round(start.g * (1 - t) + end.g * t),
                               round(start.b * (1 - t) + end.b * t),
                               a)
     return _interp
Esempio n. 42
0
    def __init__(self, parent, orientation, thickness=10, left=None, top=None,
                 width=None, height=None, bg_color=None, fg_color=None,
                 border=None, bd_color=None, bd_width=1):

        if orientation != "vertical" and orientation != "horizontal":
            raise TypeError, 'orientation'

        GUIObject.__init__(self, left, top, width, height)

        self.orientation = orientation
        self.bg_color    = bg_color
        self.fg_color    = fg_color
        self.thickness   = thickness
        self.border      = border
        self.bd_color    = bd_color
        self.bd_width    = bd_width

        if not self.bg_color:
            if self.skin_info_widget.rectangle.bgcolor:
                self.bg_color = Color(self.skin_info_widget.rectangle.bgcolor)
            else:
                self.bg_color = Color(self.osd.default_bg_color)

        if not self.fg_color:
            if self.skin_info_widget.font.color:
                self.fg_color = Color(self.skin_info_widget.font.color)
            else:
                self.fg_color = Color(self.osd.default_fg_color)

        if not self.bd_color:
            if self.skin_info_widget.rectangle.color:
                self.bd_color = Color(self.skin_info_widget.rectangle.color)
            else:
                self.bd_color = Color(self.osd.default_fg_color)

        if not self.border:
            self.border = Border(self, Border.BORDER_FLAT,
                                 self.bd_color, self.bd_width)
Esempio n. 43
0
 def drawAll(self, newWindow= True):
     if self.generated == True:
         self.butt_print.config(state= 'disabled')
         self.timebuff = 0.0
         self.color = Color.white()
         self.thick = 2
         l = float(self.slid_linesize.get())
         a = float(self.slid_angle.get())
         Draw.init(self.startingPoint, l, a)
         if self.fullScreen.get() == 1:
             if newWindow:
                 self.curr_canvas = dc.BigCanvas(self).canvas
             self.canvas.delete("all")
         else:
             self.curr_canvas = self.canvas
         self.curr_canvas.delete("all")
         self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get()))
         rainbow = self.rainbowCheck.get() == 1
         if rainbow or self.incThickYN:
             self.incStep = 1.0/float(self.getDrawCount(self.output))
             self.percent = 0.0
         for c in self.output:
             if c == '[':
                 Draw.push()
             elif c == ']':
                 Draw.pop()
             else:
                 for r in Rule.getDrawings():
                     if c == r[0]:
                         if len(r) > 2:
                             params = (r[1], r[2])
                         else:
                             params = (r[1],)
                         s = float(self.slid_timer.get())
                         self.do(params, s, rainbow)
                         break
         self.butt_print.config(state= 'normal')
Esempio n. 44
0
	def __init__(self, rect=None):
		"""
		Initialization method.

		@param rect: The bounding box for the Node. By default, the bounding box is L{RectZero}.
		@type rect: L{Rect} (or C{None})
		"""
		self._transformAnchor = PointZero()
		self._anchorPoint = PointZero()
		self._isAnchorPointRelative = True	# Scenes and Layers should be set to False

		self._position = PointZero()
		self._size = SizeZero()
		if rect is not None:
			self.setRect(rect)

		self._zOrder = 0
		self._isVisible = True
		self._backgroundColor = ClearColor()

		self._rotation = 0.0
		self._scaleX = 1.0
		self._scaleY = 1.0
		self._userData = None
		self._tag = ""

		self._children = []
		self._parent = None
		self._director = None
		self._isRunning = False
		self._controller = None
		self._color = ClearColor()	# convenience color for subclasses that use foreground coloring
		self._opacity = 1.0		# used by subclasses that support opacity
		self._scheduledTimers = {}

		self._gestureListeners = []
		self._controllers = []	# there may be GestureListeners that are not Controllers
Esempio n. 45
0
  def getLightingFromSecondaryRay(self, ray, lights, generation, strength,
                                  materialStack, ignore=None, inside=None):
#    debug_print("In getLightingFromSecondaryRay(%d)" % generation)
    insideMaterial = materialStack[-1]
    hit = self.world.intersect(ray, ignore=ignore, inside=inside,
                               insideMaterial=insideMaterial)
    color = Color.BLACK
    if hit.hit:
#      add_debug_ray(Ray(ray.origin, ray.offset.scale(hit.distance)), "red")
      if insideMaterial.attenuation_distances:
        # Here we lower strength due to absorbtion in insideMaterial in the
        # hit.distance traveled.  We attenuate by 50% for each unit of distance,
        # where the unit length is a property of the material.  So
        #   strength *= pow(0.5, (distance / attenuation_distance))
        # We compute a custom attenuator per component.
        attenuators = []
        for d in insideMaterial.attenuation_distances.toList():
          if d:
            p = math.pow(0.5, hit.distance / d)
          else:
            p = 1.0
          attenuators.append(p)
#        debug_print("attenuators is " + repr(attenuators))
#        debug_print("strength was " + repr(strength))
        strength *= Color.fromList(attenuators)
#        debug_print("strength is " + repr(strength))
        # Too dim to matter after attenuation?
        if sum(strength.toList()) < 0.01:
#          debug_print("Out early getLightingFromSecondaryRay(%d)" % generation)
          return color
      color = self.getLighting(ray, hit, lights,
                               generation=generation+1,
                               strength=strength,
                               materialStack=materialStack)
#    debug_print("returning color " + repr(color))
#    debug_print("Out getLightingFromSecondaryRay(%d)" % generation)
    return color
Esempio n. 46
0
'''
Created on 14/07/2013

@author: voval
'''

from Color import *

c = Color("#fff000", "rojo brillante")
print(c.get_nombre())
c.set_nombre('rojo')
print(c.get_nombre())
Esempio n. 47
0
 def visual(self):
     Color.green()
     glRotate(90 + self.vector[0],0,1,0)
     glRotate(-self.vector[1],1,0,0)
     glutSolidCone(0.2,1,10,10)
Esempio n. 48
0
 def visual(self):
     Color.green()
     glutSolidSphere(self.colornum,10,10)
Esempio n. 49
0
def product_manager(product, from_categorie):
    """Show and interact with a product"""
    while "User don't use 0 to exit":
        # Clear then show product
        os.system('cls' if os.name=='nt' else 'clear')
        print(Color.cyan("\t<<< Fiche Produit >>>\n"))
        print(Color.yellow("Nom du produit: ") + product.name)
        print(Color.yellow("Marque: ") + product.brands)
        print(Color.yellow("Nutri-score: ") + product.nutrition_grade.upper())
        print(Color.green("Repères nutritionnels pour 100g:"))
        print(Color.yellow("\tLipides: ") + str(product.fat))
        print(Color.yellow("\tAcides gras saturés: ") + str(product.saturated_fat))
        print(Color.yellow("\tSucres: ") + str(product.sugars))
        print(Color.yellow("\tSel: ") + str(product.salt))
        print(Color.magenta("URL: ") + product.url)

        uinput = input(Color.cyan("(Entrez: S - Substituer | E - Enregistrer | N - Ouvrir | 0 - Revenir aux produits de {})\n").format(from_categorie))

        # Exit product manager
        if uinput is '0':
            break

        # Faire Save

        # Substitute this product
        if uinput.lower() == 's':
            substitute_manager(product)

        # Save this product in DB
        if uinput.lower() == 'e':
            save_product(product)

        # Open url in web browser
        if uinput.lower() == 'n':
            webbrowser.open(product.url, new=0, autoraise=True)
Esempio n. 50
0
    def makeInputFrame(self):
        self.inp_seed         = String()
        self.bgColor          = String()
        self.gen_value        = Int()
        self.rainbowCheck     = Int()
        self.fram_input       = Frame(self,              bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height)
        self.fram_seed        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_prod        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_draw        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_drawParams  = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_gen         = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_output      = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.menu_gen         = DropDown(self.fram_gen,  textvariable= self.gen_value, state= 'readonly')
        self.entr_seed        = Input(self.fram_seed,    textvariable= self.inp_seed)
        self.text_output      = Output(self.fram_output, width= 35, height= 10)
        self.scrl_output      = Scrollbar(self.fram_output)
        self.list_prod        = List(self.fram_prod,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.list_draw        = List(self.fram_draw,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.slid_linesize    = Slider(self.fram_drawParams,  from_= 0.1, to= 10.0,     orient= HORIZONTAL, resolution= 0.1, length= 180)
        self.slid_timer       = Slider(self.fram_drawParams,  from_= 0, to= 2,          orient= HORIZONTAL, resolution= 0.02, length= 180)
        self.slid_angle       = Slider(self.fram_drawParams,  from_= 0, to= 359,        orient= HORIZONTAL, length= 180)
        self.entr_bgcolor     = Input (self.fram_drawParams, textvariable= self.bgColor)
        self.butt_prodAdd     = Button(self.fram_prod,   text= "Add",    width=8, command= self.AddProductionRule)
        self.butt_prodEdit    = Button(self.fram_prod,   text= "Edit",   width=8, command= self.EditProductionRule)
        self.butt_prodDelete  = Button(self.fram_prod,   text= "Delete", width=8, command= self.DeleteProductionRule)
        self.butt_drawAdd     = Button(self.fram_draw,   text= "Add",    width=8, command= self.AddDrawingRule)
        self.butt_drawEdit    = Button(self.fram_draw,   text= "Edit",   width=8, command= self.EditDrawingRule)
        self.butt_drawDelete  = Button(self.fram_draw,   text= "Delete", width=8, command= self.DeleteDrawingRule)
        self.chek_incColor    = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck)
        Label(self.fram_seed,       text= "Axiom:", width=8).grid             (row=0, column=0)
        Label(self.fram_prod,       text= "Production\nRules:", width=8).grid (row=0, column=0)
        Label(self.fram_draw,       text= "Drawing\nRules:", width=8).grid    (row=0, column=0)
        Label(self.fram_drawParams, text= "Line Size:").grid                  (row=0, column=0)
        Label(self.fram_drawParams, text= "Delay (ms):").grid                 (row=1, column=0)
        Label(self.fram_drawParams, text= "Starting Angle:").grid             (row=2, column=0)
        Label(self.fram_drawParams, text= "Background Color:").grid           (row=3, column=0)
        Label(self.fram_output,     text= "Output:").grid                     (row=0, column=0)
        Label(self.fram_gen,        text= "Generations:").grid                (row=0, column=0)

        self.gen_value.set(1)
        self.menu_gen['values'] = tuple(range(1, 13))
        self.slid_linesize.set(1.0)
        self.bgColor.set( Color.default() )
        self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set)
        self.scrl_output.config(command=self.text_output.yview)

        self.fram_input.grid      (row=0, column=0)
        self.fram_seed.grid       (row=1, column=0, sticky= 'ew')
        self.fram_prod.grid       (row=2, column=0, sticky= 'ew')
        self.fram_draw.grid       (row=3, column=0, sticky= 'ew')
        self.fram_drawParams.grid (row=4, column=0, sticky= 'ew')
        self.fram_gen.grid        (row=5, column=0, sticky= 'ew')
        self.fram_output.grid     (row=6, column=0, sticky= 'ew')
        self.entr_seed.grid       (row=0, column=1, sticky= 'ew')
        self.list_prod.grid       (row=0, column=1, sticky= 'ew')
        self.butt_prodAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_prodEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew')
        self.list_draw.grid       (row=0, column=1)
        self.butt_drawAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_drawEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew')
        self.chek_incColor.grid   (row=0, column=2)
        self.slid_linesize.grid   (row=0, column=1, sticky= 'ew')
        self.slid_timer.grid      (row=1, column=1, sticky= 'ew')
        self.slid_angle.grid      (row=2, column=1, sticky= 'ew')
        self.entr_bgcolor.grid    (row=3, column=1, sticky= 'ew')
        self.menu_gen.grid        (row=0, column=1, sticky= 'ew')
        self.text_output.grid     (row=1, column=0)
        self.scrl_output.grid     (row=1, column=1, sticky= 'ns')
Esempio n. 51
0
 def test_equality(self):
     b1 = Color("B")
     b2 = b1.copy()
     
     # self.assertNotEqual(b1, b2)
     self.assertTrue(b1.equals(b2))
Esempio n. 52
0
    def test_inequality(self):
        b = Color("B")
        v = Color("V")

        self.assertTrue(not b.equals(v))
Esempio n. 53
0
 def incColor(self):
     self.color    = Color.getValueByPercent(self.percent)
     self.percent += self.incStep
Esempio n. 54
0
class Gcompris_anim:
  """The cartoon activity"""

  def __init__(self, gcomprisBoard):

    self.gcomprisBoard = gcomprisBoard
    self.timeout = 0

    self.doc = None

    if self.gcomprisBoard.mode == 'draw':
      # DRAW
      #
      # draw is adapted to little kids : big anchors
      self.DEFAULT_ANCHOR_SIZE	= 14

      # draw specific UI
      self.selector_section = "draw3"
    else:
      # Anim
      #
      # Normal anchors
      self.DEFAULT_ANCHOR_SIZE	= 10

      # anim specific UI
      self.selector_section = "anim3"

    # Initialisation. Should not change in draw.
    self.running = False

    # global parameter to access object structures from global fonctions
    global fles
    fles=self

    self.file_type = ".gcanim"

    # Part of UI : tools buttons
    # TOOL SELECTION
    self.tools = [
      [ "SAVE",
        "anim/tool-save.png",
        "anim/tool-save.png",
        gcompris.CURSOR_SELECT,
        _("Save...")
      ],
      [ "LOAD",
        "anim/tool-load.png",
        "anim/tool-load.png",
        gcompris.CURSOR_SELECT,
        _("Load...")
      ],
      [ "MOVIE",
        "anim/tool-movie.png",
        "anim/tool-movie_on.png",
        gcompris.CURSOR_SELECT,
        _("Run the animation")
      ],
      [ "SELECT",
        "anim/tool-select.png",
        "anim/tool-select_on.png",
        gcompris.CURSOR_SELECT,
        _("Select")
      ],
      [ "RECT",
        "anim/tool-rectangle.png",
        "anim/tool-rectangle_on.png",
        gcompris.CURSOR_RECT,
        _("Rectangle")
      ],
      [ "FILL_RECT",
        "anim/tool-filledrectangle.png",
        "anim/tool-filledrectangle_on.png",
        gcompris.CURSOR_FILLRECT,
        _("Filled rectangle")
      ],
      [ "CIRCLE",
        "anim/tool-circle.png",
        "anim/tool-circle_on.png",
        gcompris.CURSOR_CIRCLE,
        _("Circle")
      ],
      [ "FILL_CIRCLE",
        "anim/tool-filledcircle.png",
        "anim/tool-filledcircle_on.png",
        gcompris.CURSOR_FILLCIRCLE,
        _("Filled circle")
      ],
      [ "LINE",
        "anim/tool-line.png",
        "anim/tool-line_on.png",
        gcompris.CURSOR_LINE,
        _("Line")
      ],
      [ "TEXT",
        "anim/tool-text.png",
        "anim/tool-text_on.png",
        gcompris.CURSOR_LINE,
        _("Text")
      ],
      [ "IMAGE",
        "anim/tool-image.png",
        "anim/tool-image_on.png",
        gcompris.CURSOR_DEFAULT,
        _("Image...")
      ],
      [ "FILL",
        "anim/tool-fill.png",
        "anim/tool-fill_on.png",
        gcompris.CURSOR_FILL,
        _("Fill")
      ],
      [ "DEL",
        "anim/tool-del.png",
        "anim/tool-del_on.png",
        gcompris.CURSOR_DEL,
        _("Delete")
      ],
      [ "FLIP",
        "anim/tool-flip.png",
        "anim/tool-flip_on.png",
        gcompris.CURSOR_DEFAULT,
        _("Flip")
      ],
      [ "RAISE",
        "anim/tool-up.png",
        "anim/tool-up_on.png",
        gcompris.CURSOR_DEFAULT,
        _("Raise")
      ],
      [ "LOWER",
        "anim/tool-down.png",
        "anim/tool-down_on.png",
        gcompris.CURSOR_DEFAULT,
        _("Lower")
      ],
# FIXME NEED A CLEAN IMPLEMENTATION OF THE ROTATION
#      [ "CCW",
#        "anim/tool-rotation-ccw.png",
#        "anim/tool-rotation-ccw_on.png",
#        gcompris.CURSOR_DEFAULT],
#        _("Rotation left")
#      [ "CW",
#        "anim/tool-rotation-cw.png",
#        "anim/tool-rotation-cw_on.png",
#        gcompris.CURSOR_DEFAULT],
#        _("Rotation right")
       ]

    # keep the tool selected
    self.current_tool=0

    # selected object
    self.selected = None

    # Part of UI : drawing_area is the drawing zone
    # when anim is played, it's masked and playing_area is displayed
    #
    # Drawing area is editing image area
    # Palying area is playing map
    self.drawing_area = [124.0, 20.0, gcompris.BOARD_WIDTH - 15, gcompris.BOARD_HEIGHT - 40]
    self.playing_area = [124.0, 20.0, gcompris.BOARD_WIDTH - 15, gcompris.BOARD_HEIGHT - 40]

    # Part of UI
    # The root items
    self.root_toolitem  = []

    # used to handle draw creation of object
    self.created_object = None

  def start(self):

    # GCompris initialisation
    self.gcomprisBoard.level=1
    self.gcomprisBoard.maxlevel=1
    self.gcomprisBoard.sublevel=0
    self.gcomprisBoard.number_of_sublevel=0

    gcompris.set_default_background(self.gcomprisBoard.canvas.get_root_item())

    # Create our rootitem. We put each canvas item in it so at the end we
    # only have to kill it. The canvas deletes all the items it contains automaticaly.
    self.rootitem = goocanvas.Group(
      parent =  self.gcomprisBoard.canvas.get_root_item())

    self.doc = Document(self)

    # initialisation
    self.draw_tools()
    self.draw_animtools()

    self.doc.timeline.draw()
    if self.gcomprisBoard.mode == 'draw':
      self.doc.timeline.hide()

    self.color_rootitem = goocanvas.Group(
      parent =  self.gcomprisBoard.canvas.get_root_item())
    self.color = Color(self.color_rootitem, self.drawing_area)
    self.color.draw()

    self.draw_drawing_area()
    self.draw_playing_area()

    gcompris.bar_set(gcompris.BAR_JOURNAL)
    gcompris.bar_location(10, -1, 0.6)

    if gcompris.sugar_detected():
      journal_file = gcompris.sugar_load()
      if journal_file:
        fles.doc.file_to_anim(journal_file)

  def end(self):
    # stop the animation
    if self.running:
      self.playing_stop()

    if self.timeout:
      gobject.source_remove(self.timeout)
    self.timeout = 0

    if gcompris.sugar_detected():
      fd, tmp_file = tempfile.mkstemp(dir='/tmp')
      os.close(fd)
      os.chmod(tmp_file, 0644)
      fles.doc.anim_to_file(tmp_file)
      gcompris.sugar_save(tmp_file)

    # Remove the root item removes all the others inside it
    gcompris.set_cursor(gcompris.CURSOR_DEFAULT);
    self.rootitem.remove()
    self.color_rootitem.remove()

    del self.doc

  def pause(self, pause):
    return

  def repeat(self):
    pass

  def config(self):
    pass

  def key_press(self, keyval, commit_str, preedit_str):
    #
    # I suppose codec is the stdin one.
    #
    codec = sys.stdin.encoding

    # keyboard shortcuts
    if ( ((keyval == gtk.keysyms.F1)
         or (keyval == gtk.keysyms.l)) and not gcompris.sugar_detected() ):
      gcompris.file_selector_save( self.gcomprisBoard,
                                   self.selector_section, self.file_type,
                                   general_save, self)
    elif ( ((keyval == gtk.keysyms.F2)
           or (keyval == gtk.keysyms.s)) and not gcompris.sugar_detected() ):
      gcompris.file_selector_load( self.gcomprisBoard,
                                   self.selector_section, self.file_type,
                                   general_restore, self)
    elif (keyval == gtk.keysyms.Left):
      self.doc.timeline.previous()
      return True
    elif (keyval == gtk.keysyms.Right):
      self.doc.timeline.next()
      return True

    # Printing
    # Bruno we need a print button !
    #
    # was in anim1, but not print an animation is not interesting.
    elif (keyval == gtk.keysyms.F3):
      pass

    if (not self.selected):
      return False

    if (self.selected.type_name() == "GooCanvasText"):
      self.selected.key_press(keyval, commit_str, preedit_str)
      return True

    # Process shortcuts on non text items
    if ((keyval == gtk.keysyms.BackSpace) or
        (keyval == gtk.keysyms.Delete)):
      self.selected.delete()
      return True

    return False

  # Display the tools
  def draw_tools(self):

    self.root_toolitem = \
      goocanvas.Group(
        parent = self.rootitem,
      )

    goocanvas.Image(
      parent = self.root_toolitem,
      pixbuf = gcompris.utils.load_pixmap("anim/tool-selector.png"),
      x = 5,
      y = 5.0,
      width = 107.0,
      height = 517.0,
      )

    x1 = 11.0
    x2 = 56.0
    y = 11.0
    stepy = 45
    start_tool = 0

    if gcompris.sugar_detected():
        start_tool = 2

    # Display the tools
    for i in range(start_tool,len(self.tools)):

      # Exclude the anim specific buttons
      if self.gcomprisBoard.mode == 'draw':
        if self.tools[i][0]=="MOVIE" or self.tools[i][0]=="PICTURE":
          continue

      if(i%2):
        theX = x2
      else:
        theX = x1

      item = \
        goocanvas.Image(
          parent = self.root_toolitem,
          pixbuf = gcompris.utils.load_pixmap(self.tools[i][1]),
          tooltip = self.tools[i][4],
          x=theX,
          y=y
        )
      gcompris.utils.item_focus_init(item, None)
      item.connect("button_press_event", self.tool_item_event, i)
      if i%2:
        y += stepy

      if(self.tools[i][0]=="SELECT"):
        self.select_tool = item
        self.select_tool_number = i
        # Always select the SELECT item by default
        self.current_tool = i
        self.old_tool_item = item
        self.old_tool_item.props.pixbuf = \
            gcompris.utils.load_pixmap(self.tools[i][2])
        gcompris.set_cursor(self.tools[i][3]);


  # Event when a tool is selected
  # Perform instant action or swich the tool selection
  def tool_item_event(self, item, target, event, tool):

    if event.type == gtk.gdk.BUTTON_PRESS:
      if event.button == 1:
        gcompris.sound.play_ogg("sounds/bleep.wav")
        # Some button have instant effects
        if (self.tools[tool][0] == "SAVE"):
          gcompris.file_selector_save( self.gcomprisBoard,
                                       self.selector_section, self.file_type,
                                       general_save, self)
          return False

        elif (self.tools[tool][0] == "LOAD"):
          gcompris.file_selector_load( self.gcomprisBoard,
                                       self.selector_section, self.file_type,
                                       general_restore, self)
          return False

        elif (self.tools[tool][0] == "IMAGE"):
          self.pos_x = gcompris.BOARD_WIDTH/2
          self.pos_y = gcompris.BOARD_HEIGHT/2

          gcompris.images_selector_start(self.gcomprisBoard,
                                         "dataset",
                                         image_selected,
                                         self);
          return False

        elif (self.tools[tool][0] == "MOVIE"):
          if not self.running:
            self.deselect()

            self.playing_start()
            return False

        elif (self.tools[tool][0] != "SELECT"):
          self.deselect()

        #
        # Normal case, tool button switch
        # -------------------------------

        # Deactivate old button
        self.old_tool_item.props.pixbuf = \
            gcompris.utils.load_pixmap(self.tools[self.current_tool][1])

        # Activate new button
        self.current_tool = tool
        self.old_tool_item = item
        self.old_tool_item.props.pixbuf = \
            gcompris.utils.load_pixmap(self.tools[self.current_tool][2])
        gcompris.set_cursor(self.tools[self.current_tool][3]);


  # Display the drawing area
  def draw_drawing_area(self):

    x1 = self.drawing_area[0]
    y1 = self.drawing_area[1]
    x2 = self.drawing_area[2]
    y2 = self.drawing_area[3]

    item = \
        goocanvas.Rect(
          parent = self.rootitem,
          x = x1,
          y = y1,
          width = x2 - x1,
          height = y2 - y1,
          line_width=2.0,
          fill_color_rgba=0xFFFFFFFFL,
          stroke_color_rgba=0x111199FFL,
          radius_x=5.0,
          radius_y=5.0)
    item.connect("button_press_event", self.item_event)
    item.connect("button_release_event", self.item_event)
    item.connect("motion_notify_event", self.item_event)

    # The CanvasGroup for the edit space.
    self.root_drawingitem = \
      goocanvas.Group(
        parent = self.rootitem,
      )

    # Create the root_anim group which contains all the drawings.
    # At root_anim root, there is a group for each drawings.
    self.root_anim = \
      goocanvas.Group(
        parent = self.rootitem,
      )

    gcompris.utils.item_absolute_move(self.root_anim,
                                      int(self.playing_area[0]-self.drawing_area[0]),
                                      int(self.playing_area[1]-self.drawing_area[1])
                                      )


  # Display the drawing area
  def draw_playing_area(self):

    x1=self.playing_area[0]
    y1=self.playing_area[1]
    x2=self.playing_area[2]
    y2=self.playing_area[3]


    # The CanvasGroup for the playing area.
    self.root_playingitem = \
      goocanvas.Group(
        parent = self.rootitem,
      )
    self.root_playingitem.props.visibility = goocanvas.ITEM_INVISIBLE

    # intervall = 1000 / anim_speed
    self.anim_speed=5

    run = \
      goocanvas.Image(
        parent = self.root_playingitem,
      pixbuf = gcompris.utils.load_pixmap("anim/down.png"),
      x = 15,
      y = 410,
      width = 20,
      height = 20,
      )
    run.connect("button_press_event", self.speed_event,False)

    self.speed_item = \
      goocanvas.Text(
        parent = self.root_playingitem,
      text=self.anim_speed,
      font = gcompris.skin.get_font("gcompris/board/medium"),
      x=52,
      y=420,
      anchor=gtk.ANCHOR_CENTER,
      )


    run = \
      goocanvas.Image(
        parent = self.root_playingitem,
      pixbuf = gcompris.utils.load_pixmap("anim/up.png"),
      x = 70,
      y = 410,
      width = 20,
      height = 20,
      )
    run.connect("button_press_event", self.speed_event,True)

    # And finaly a STOP icon
    run = \
      goocanvas.Image(
        parent = self.root_playingitem,
      pixbuf = gcompris.utils.load_pixmap("anim/draw.svg"),
      x = 16,
      y = 110,
      )
    run.connect("button_press_event", self.stop_event, True)


  def stop_event(self, item, target, event, up):
    if event.type == gtk.gdk.BUTTON_PRESS:
      gcompris.sound.play_ogg("sounds/bleep.wav")
      self.playing_stop()

  def playing_stop(self):
    self.running = False
    gobject.source_remove(self.timeout)
    self.root_toolitem.props.visibility = goocanvas.ITEM_VISIBLE
    self.root_playingitem.props.visibility = goocanvas.ITEM_INVISIBLE
    self.color.show()

  def speed_event(self, item, target, event, up):

    if event.type == gtk.gdk.BUTTON_PRESS:
      gcompris.sound.play_ogg("sounds/bleep.wav")
      if up:
        if self.anim_speed==25:
          return
        else:
          self.anim_speed=self.anim_speed+1
      else:
        if self.anim_speed==1:
          return
        else:
          self.anim_speed=self.anim_speed-1

      gobject.source_remove(self.timeout)
      self.timeout = gobject.timeout_add(1000/self.anim_speed,
                                         self.refresh_loop)
      self.speed_item.set_properties(text = self.anim_speed)

  def deselect(self):
    if self.selected:
      self.selected.deselect()
      self.selected = None

  # Delete the item from the unique list
  # This is called by animitem itself when the object
  # is no more displayed on any time lines.
  def deleteItem(self, item):
    self.doc.animlist.remove(item)

  # Main callback on item comes here first
  # And are then dispatched to the proper functions
  def item_event(self, item, target, event):
    if(event.type == gtk.gdk.BUTTON_PRESS and self.running==True):
      self.playing_stop()
      return False

    if event.type == gtk.gdk.BUTTON_PRESS:

      if event.button == 1:
        gcompris.sound.play_ogg("sounds/bleep.wav")

        animItem = item.get_data("AnimItem")
        if not animItem:
          self.deselect()
        else:
          if self.tools[self.current_tool][0] == "FILL":
            animItem.fill(self.color.fill,
                          self.color.stroke)
          elif self.tools[self.current_tool][0] == "DEL":
            animItem.delete()
          elif self.tools[self.current_tool][0] == "SELECT":
            if self.selected:
              self.selected.deselect()
            animItem.select()
            self.selected = animItem
            self.selected.move_item_event(item,
                                          target,
                                          event)
          elif self.tools[self.current_tool][0] == "RAISE":
            animItem.raise_()
          elif self.tools[self.current_tool][0] == "LOWER":
            animItem.lower()
          elif self.tools[self.current_tool][0] == "CCW":
            animItem.rotate(-10)
          elif self.tools[self.current_tool][0] == "CW":
            animItem.rotate(10)
          elif self.tools[self.current_tool][0] == "FLIP":
            animItem.flip()

        self.created_object = None
        if self.tools[self.current_tool][0] == "FILL_RECT":
          self.created_object = AnimItemRect(self,
                                             event.x, event.y,
                                             self.color.fill, self.color.stroke, 2)
        elif self.tools[self.current_tool][0] == "RECT":
          self.created_object = AnimItemRect(self,
                                             event.x, event.y,
                                             None, self.color.stroke, 7)
        elif self.tools[self.current_tool][0] == "FILL_CIRCLE":
          self.created_object = AnimItemEllipse(self,
                                                event.x, event.y,
                                                self.color.fill, self.color.stroke, 2)
        elif self.tools[self.current_tool][0] == "CIRCLE":
          self.created_object = AnimItemEllipse(self,
                                                event.x, event.y,
                                                None, self.color.stroke, 7)
        elif self.tools[self.current_tool][0] == "LINE":
          self.created_object = AnimItemLine(self,
                                             event.x, event.y,
                                             None, self.color.stroke, 7)
        elif self.tools[self.current_tool][0] == "TEXT":
          self.created_object = AnimItemText(self,
                                             event.x, event.y,
                                             self.color.stroke)

        if self.created_object:
          self.created_object.create_item_event(item,
                                                target)

          # We keep all object in a unique list
          self.doc.animlist.append(self.created_object)

          # Mark it as selected so we can write in it without
          # having to make a real selection and keys shortcuts
          # works
          self.selected = self.created_object

    #
    # MOTION EVENT
    # ------------
    elif (event.type == gtk.gdk.MOTION_NOTIFY
          and event.state & gtk.gdk.BUTTON1_MASK
          and self.created_object):
        self.created_object.create_item_drag_event(item,
                                                   target,
                                                   event)

    elif (event.type == gtk.gdk.MOTION_NOTIFY
          and event.state & gtk.gdk.BUTTON1_MASK
          and self.tools[self.current_tool][0] == "SELECT"
          and self.selected):
        self.selected.move_item_event(item,
                                      target,
                                      event)

    #
    # MOUSE DRAG STOP
    # ---------------
    elif (event.type == gtk.gdk.BUTTON_RELEASE):
      if self.created_object:
        self.created_object.create_item_drag_event(item,
                                                   target,
                                                   event)
        self.created_object = None
        return True
      else:
        if self.selected:
          self.selected.move_item_event(item,
                                        target,
                                        event)

    return False

  def refresh_loop(self):
    self.doc.timeline.next()
    return True

  def playing_start(self):
    if not self.running:
      self.running = True
      self.root_toolitem.props.visibility = goocanvas.ITEM_INVISIBLE
      self.root_playingitem.props.visibility = goocanvas.ITEM_VISIBLE
      self.timeout = gobject.timeout_add(1000/self.anim_speed,
                                         self.refresh_loop)
      self.color.hide()

  def playing_event(self, item, target, event, state):
    if event.type == gtk.gdk.BUTTON_PRESS:
      if state:
        self.playing_start()
      else:
        self.playing_stop()

  # Display the animation tools
  def draw_animtools(self):
    x_left = 8
    y_top  = 472
    minibutton_width = 32
    minibutton_height = 20

    if self.gcomprisBoard.mode == 'draw':
      return

    # Draw the background area

    goocanvas.Image(
      parent = self.rootitem,
      pixbuf = gcompris.utils.load_pixmap("anim/counter.png"),
      x=x_left - -11,
      y=y_top - 20,
      width=70.0,
      height=34.0,
      tooltip = _("Current frame")
      )
Esempio n. 55
0
    def test_matches(self):
        b1 = Color("B")
        b2 = Color("B")

        self.assertTrue(b1.matches(b2))
Esempio n. 56
0
class Scrollbar(GUIObject):
    """
    left      x coordinate. Integer
    top       y coordinate. Integer
    width     Integer
    height    Integer
    bg_color  Background color (Color)
    fg_color  Foreground color (Color)
    """


    def __init__(self, parent, orientation, thickness=10, left=None, top=None,
                 width=None, height=None, bg_color=None, fg_color=None,
                 border=None, bd_color=None, bd_width=1):

        if orientation != "vertical" and orientation != "horizontal":
            raise TypeError, 'orientation'

        GUIObject.__init__(self, left, top, width, height)

        self.orientation = orientation
        self.bg_color    = bg_color
        self.fg_color    = fg_color
        self.thickness   = thickness
        self.border      = border
        self.bd_color    = bd_color
        self.bd_width    = bd_width

        if not self.bg_color:
            if self.skin_info_widget.rectangle.bgcolor:
                self.bg_color = Color(self.skin_info_widget.rectangle.bgcolor)
            else:
                self.bg_color = Color(self.osd.default_bg_color)

        if not self.fg_color:
            if self.skin_info_widget.font.color:
                self.fg_color = Color(self.skin_info_widget.font.color)
            else:
                self.fg_color = Color(self.osd.default_fg_color)

        if not self.bd_color:
            if self.skin_info_widget.rectangle.color:
                self.bd_color = Color(self.skin_info_widget.rectangle.color)
            else:
                self.bd_color = Color(self.osd.default_fg_color)

        if not self.border:
            self.border = Border(self, Border.BORDER_FLAT,
                                 self.bd_color, self.bd_width)


    def set_handle_position(self, pos):
        self.handle_position = pos


    def get_handle_rect(self):
        (a, b, c) = self.parent.get_view_percent(self.orientation)

        logger.log( 9, 'SB: a,b,c = %s,%s,%s', a, b, c)

        if a == 100 or b == 100 or c == 100:
            return self.get_rect()

        if self.orientation == 'vertical':
            fg_width = self.width
            fg_height = b * self.height / 100
            # fg_x = self.left
            fg_x = 0
            # fg_y = self.top + (a * self.height / 100)
            fg_y = (a * self.height / 100)
        else:
            fg_width = b * self.width / 100
            fg_height = self.height
            # fg_x = self.left + (a * self.width / 100)
            fg_x = (a * self.width / 100)
            # fg_y = self.top
            fg_y = 0

        logger.log( 9, 'SB: handle_rect = %s,%s,%s,%s', fg_x, fg_y, fg_width, fg_height)
        return (fg_x, fg_y, fg_width, fg_height)


    def get_handle_size(self):
        (a, b, c, d) = self.get_handle_rect()
        # print 'SB: get_handle_size: c,d="%s,%s"' % (c, d)
        return (c, d)


    def get_handle_coords(self):
        (a, b, c, d) = self.get_handle_rect()
        # print 'SB: get_handle_coords: a,b="%s,%s"' % (a, b)
        return (a, b)


    def calculate_position(self):

        if self.orientation == 'vertical':
            self.width = self.thickness
            self.height = self.parent.height
            if self.parent.show_h_scrollbar:
                self.height = self.height - self.parent.h_scrollbar.thickness
            self.left = self.parent.width - self.width
            # self.top = self.parent.top
            self.top = 0
        else:
            self.width = self.parent.width
            if self.parent.show_v_scrollbar:
                self.width = self.width - self.parent.v_scrollbar.thickness
            self.height = self.thickness
            # self.left = self.parent.left
            self.left = 0
            self.top = self.parent.height - self.height

        if isinstance(self.border, Border):
            # self.border.set_position(self.left, self.top)
            self.border.set_position(0, 0)
            self.border.width = self.width
            self.border.height = self.height

        if config.DEBUG > 1:
            print 'SB: parent_rect = %s,%s,%s,%s' % (self.parent.left, self.parent.top,
                                                     self.parent.width, self.parent.height)
            print 'SB: self_rect = %s,%s,%s,%s' % (self.left, self.top, self.width,
                                                   self.height)


    def _draw(self):
        """
        The actual internal draw function.

        """
        # if not self.width or not self.height:
        #     raise TypeError, 'Not all needed variables set.'

        self.calculate_position()

        bg_c = self.bg_color.get_color_sdl()
        bg_a = self.bg_color.get_alpha()

        self.surface = self.osd.Surface(self.get_size(), 0, 32)
        self.surface.fill(bg_c)
        self.surface.set_alpha(bg_a)

        fg_c = self.fg_color.get_color_sdl()
        logger.log( 9, 'SB: fg_c = %s,%s,%s,%s', fg_c)
        fg_a = self.fg_color.get_alpha()

        fg_box = self.osd.Surface(self.get_handle_size(), 0, 32)
        fg_box.fill(fg_c)
        fg_box.set_alpha(fg_a)

        self.surface.blit(fg_box, self.get_handle_coords())
        if self.border:
            self.border.draw()

        logger.log( 9, 'SB::_draw: pos=%s,%s', self.left, self.top)
        self.blit_parent()
Esempio n. 57
0
class Node(object, ModelListener):
	"""
	The base class for rendering items to the screen.

	Note that the position is set relative to the Node's parent. If the Node's parent is the L{Director}, the position is relative to the top-left corner of the screen (in general, this should only apply to L{Scene}C{s}).
	"""
	def __init__(self, rect=None):
		"""
		Initialization method.

		@param rect: The bounding box for the Node. By default, the bounding box is L{RectZero}.
		@type rect: L{Rect} (or C{None})
		"""
		self._transformAnchor = PointZero()
		self._anchorPoint = PointZero()
		self._isAnchorPointRelative = True	# Scenes and Layers should be set to False

		self._position = PointZero()
		self._size = SizeZero()
		if rect is not None:
			self.setRect(rect)

		self._zOrder = 0
		self._isVisible = True
		self._backgroundColor = ClearColor()

		self._rotation = 0.0
		self._scaleX = 1.0
		self._scaleY = 1.0
		self._userData = None
		self._tag = ""

		self._children = []
		self._parent = None
		self._director = None
		self._isRunning = False
		self._controller = None
		self._color = ClearColor()	# convenience color for subclasses that use foreground coloring
		self._opacity = 1.0		# used by subclasses that support opacity
		self._scheduledTimers = {}

		self._gestureListeners = []
		self._controllers = []	# there may be GestureListeners that are not Controllers

#{ Appearance methods.
	def getOpacity(self):
		"""
		Returns the opacity for Node subclasses that use it. Default is C{1.0}.

		@return: The opacity.
		@rtype: C{float}
		"""
		return self._opacity

	def setOpacity(self, opacity):
		"""
		Sets the opacity for Node subclasses that use it. This should be set between C{0.0} (fully transparent) and C{1.0} (fully opaque).

		@param opacity: The opacity.
		@type opacity: C{float}
		"""
		self._opacity = opacity

	opacity = property(getOpacity, setOpacity, doc="The opacity for Node subclasses that use it.")

	def getZOrder(self):
		"""
		The z-order of this current Node in relation to other Nodes.

		@return: The z-order.
		@rtype: C{int} (or possibly C{float})
		"""
		return self._zOrder

	def setZOrder(self, zOrder):
		"""
		Sets the z-order of this current Node in relation to other Nodes. Children are drawn in order relative to this z-order. Default is C{0}.

		@param zOrder: The z-order.
		@type zOrder: C{int} (or C{float})
		"""
		self._zOrder = zOrder

	zOrder = property(getZOrder, setZOrder, doc="The z-order of this current Node in relation to other Nodes.")

	def isVisible(self):
		"""
		Whether or not this Node and its children are visible. Default is C{True}.

		@return: Whether or not this Node and its children are visible.
		@rtype: C{bool}
		"""
		return self._isVisible

	def setVisible(self, isVisible):
		"""
		Whether or not this node and its children are visible. Default is C{True}.

		@param isVisible: Whether or not this node and its children are visible.
		@type isVisible: C{bool}
		"""
		self._isVisible = isVisible

	visible = property(isVisible, setVisible, doc="Whether or not this node and its children are visible.")

	def getBackgroundColor(self):
		"""
		The background color of this Node. Default is L{ClearColor}.

		@return: The background color.
		@rtype: L{Color}
		"""
		return self._backgroundColor

	def setBackgroundColor(self, backgroundColor):
		"""
		Background color for the Node. Default is C{Color(0,0,0,0)} (i.e. the background is fully transparent). Any child with a zOrder less than the node's zOrder will appear behind the background.

		@param backgroundColor: The background color.
		@type backgroundColor: L{Color}
		"""
		self._backgroundColor = backgroundColor.copy()

	backgroundColor = property(getBackgroundColor, setBackgroundColor, doc="Background color for the Node.")

	def getRotation(self):
		"""
		The current angle at which this Node is rotated. Default is C{0.0}.

		@return: The current rotation angle in radians.
		@rtype: C{float}
		"""
		return self._rotation

	def setRotation(self, rotation):
		"""
		The rotation angle in radians. Default is C{0.0}.

		@param rotation: The rotation angle in radians.
		@type rotation: C{float}
		"""
		self._rotation = rotation

	rotation = property(getRotation, setRotation, doc="The rotation angle of the Node in radians.")

	def getScaleX(self):
		"""
		The scale factor for the x-axis. Default is C{1.0}.

		@return: Scale factor.
		@rtype: C{float}
		"""
		return self._scaleX

	def setScaleX(self, scaleX):
		"""
		Scale factor for the x-axis. Default is C{1.0}.

		@param scaleX: Scale factor for the x-axis.
		@type scaleX: C{float}
		"""
		self._scaleX = scaleX

	scaleX = property(getScaleX, setScaleX, doc="Scale factor for the y-axis.")

	def getScaleY(self):
		"""
		The scale factor for the y-axis. Default is C{1.0}.

		@return: Scale factor.
		@rtype: C{float}
		"""
		return self._scaleY

	def setScaleY(self, scaleY):
		"""
		Scale factor for the y-axis. Default is C{1.0}.

		@param scaleY: Scale factor for the y-axis.
		@type scaleY: C{float}
		"""
		self._scaleY = scaleY

	scaleY = property(getScaleY, setScaleY, doc="Scale factor for the y-axis.")

	def getColor(self):
		"""
		Returns the foreground color for Node subclasses that use it. Default is L{ClearColor}.

		@return: The foreground color.
		@rtype: L{Color}
		"""
		return self._color.copy()

	def setColor(self, color):
		"""
		Method for children who have special color values like, for example, tinting (see L{Sprite} and L{TintTo}).

		@param color: L{Color}.
		"""
		self._color = color.copy()

	color = property(getColor, setColor, doc="Foreground color for Node subclasses that use it.")

	def setColors(self, r, g, b, a=1.0):
		"""
		Method for children who have special color values like, for example, tinting (see L{Sprite} and L{TintTo}).

		@param r: C{float}.
		@param g: C{float}.
		@param b: C{float}.
		@param a: C{float}.
		"""
		self._color = Color(r, g, b, a)

	colors = property(fset=setColors, doc="Foreground color for Node subclasses that use it.")

	def getScale(self):
		"""
		Returns the scale amount if both scaleX and scaleY are equal. If they are not equal, it will raise a warning and only return scaleX.

		@return: Scale amount.
		@rtype: C{float}
		"""
		if self._scaleX != self._scaleY:
			warnings.warn("scaleX and scaleY have different values. Returning scaleX.")
		return self._scaleX

	def setScale(self, scale):
		"""
		Set the scale amount for both the x-axis and y-axis.

		@param scale: How much to scale this node.
		@type scale: C{float}
		"""
		self._scaleX = scale
		self._scaleY = scale

	scale = property(getScale, setScale, doc="The scale amount for both the x-axis and y-axis.")
#}


#{ Information methods.
	def getUserData(self):
		"""
		Any peripheral data the user wishes to attach. Default is C{None}.

		@return: User data.
		@rtype: C{User defined}
		"""
		return self._userData

	def setUserData(self, userData):
		"""
		Any peripheral data the user wishes to attach. Default is C{None}.

		@param userData: Peripheral data.
		@type userData: C{User defined}.
		"""
		self._userData = userData

	userData = property(getUserData, setUserData, doc="Peripheral data which the developer wishes to attach.")

	def getTag(self):
		"""
		A convenience string with which to identify this Node. Default is the empty string.

		@return: Convenience string.
		@rtype: C{string}
		"""
		return self._tag

	def setTag(self, tag):
		"""
		A convenience string with which to identify this Node.

		@param tag: The tag with which to identify this Node.
		@type tag: C{string}.
		"""
		self._tag = tag

	tag = property(getTag, setTag, doc="A convenience string with which to identify this Node.")
#}


#{ Director methods.
	def getDirector(self):
		"""
		A convenience method to get the L{Director} of the application. If this Node has not yet been parented to a running L{Scene}, this will return C{None}.

		@return: The Director of the application.
		@rtype: L{Director} (or C{None})
		"""
		return self._director

	director = property(getDirector, doc="Read-only access to the Director.")

	def _setDirector(self, director):
		"""
		Sets the L{Director} of the application. This method is used automatically and should not normally be called manually.

		@param director: The Director of the application.
		@type director: L{Director}
		"""
		self._director = director
		for child in self.getChildren():
			child._setDirector(director)
#}


#{ Geometry methods.
	def getPosition(self):
		'''
		Get the current position of the Node relative to its parent.

		@return: Current position.
		@rtype: L{Point}
		'''
		return self._position.copy()

	def setPosition(self, position):
		'''
		Sets the current position of the Node relative to its parent.

		@param position: L{Point}.
		'''
		self._position = position.copy()

	position = property(getPosition, setPosition, doc="The current position of the Node relative to its parent.")

	def getAbsolutePosition(self):
		"""
		Returns the absolute position of this Node.

		@return: The absolute position of this Node.
		@rtype: L{Point}
		"""
		position = self.getPosition()
		node = self
		while node.getParent() is not None:
			node = node.getParent()
			position = pointAdd(position, node.getPosition())
		return position

	absolutePosition = property(getAbsolutePosition, doc="Read-only access to the Node's absolute position.")

	def getSize(self):
		'''
		Returns the size of this Node.

		@return: Size.
		@rtype: L{Size}
		'''
		return self._size.copy()

	def setSize(self, size):
		"""
		Sets the size of the Node.

		@param size: L{Size}.
		"""
		self._size = size.copy()
		anchorPoint = self._anchorPoint
		transformAnchor = Point(self._size.width*anchorPoint.x, self._size.height*anchorPoint.y)
		self.setTransformAnchorPoint(transformAnchor)

	size = property(getSize, setSize, doc="The size of the Node.")

	def getRect(self):
		"""
		Returns the bounding box for the Node.

		@return: The bounding box.
		@rtype: L{Rect}
		"""
		x = self._position.x - self._size.width*self.getAnchorPoint().x
		y = self._position.y - self._size.height*self.getAnchorPoint().y
		return MakeRect(x, y, self._size.width, self._size.height)

	def setRect(self, rect):
		"""
		Sets the rectangle for the Node. Note that the node or its children may be drawn outside this rectangle (i.e. they will not be clipped).

		@param rect: L{Rect}.
		"""
		self.setPosition(rect.point)
		self.setSize(rect.size)

	rect = property(getRect, setRect, doc="The bounding box of the Node.")

	def getAnchorPoint(self):
		"""
		How the Node is displayed relative to its position. See L{setAnchorPoint} for a description.

		@return: Anchor point.
		@rtype: L{Point}
		"""
		return self._anchorPoint.copy()

	def setAnchorPoint(self, anchorPoint):
		"""
		Sets how the Node is displayed on the screen relative to its position. E.g. C{Point(0,0)} means that the Node will be drawn with its top left-most corner at the position, C{Point(1,1)} means that the Node will be drawn with its bottom right-most corner at the position, and C{Point(0.5, 0.5)} means that the Node will be drawn with its center at the position.

		@param anchorPoint: L{Point}, with both C{0 <= x <= 1} and C{0 <= y <= 1}.
		"""
		self._anchorPoint = anchorPoint.copy()
		transformAnchor = Point(self._size.width*self._anchorPoint.x, self._size.height*self._anchorPoint.y)
		self.setTransformAnchorPoint(transformAnchor)

	anchorPoint = property(getAnchorPoint, setAnchorPoint, doc="How the Node is displayed relative to its children.")

	def getTransformAnchorPoint(self):
		"""
		Returns how the Node is transformed relative to its position.

		@return: Transform anchor.
		@rtype: L{Point}
		"""
		return self._transformAnchor.copy()

	def setTransformAnchorPoint(self, anchorPoint):
		"""
		Sets how the Node is transformed relative to its position.

		@param anchorPoint: L{Point}, with both C{0 <= x <= 1} and C{0 <= y <= 1}.
		"""
		self._transformAnchor = anchorPoint.copy()

	transformAnchorPoint = property(getTransformAnchorPoint, setTransformAnchorPoint, doc="How the Node is transformed relative to its position.")
#}


#{ Parenting methods.
	def getParent(self):
		"""
		Returns the parent Node of this Node.
		
		@return: The parent of this node or None if there is no parent.
		@rtype: C{Node} (or C{None})
		"""
		return self._parent

	parent = property(getParent, doc="Read-only access to the parent Node.")

	def getChildren(self):
		"""
		Returns a list of children.

		@return: List of children.
		@rtype: C{List}
		"""
		return self._children

	children = property(getChildren, doc="Read-only access to the list of all children.")

	def getChildByTag(self, tag):
		"""
		Returns a child C{Node} whose tag matches the given C{string}. If the child is not found, this will return C{None}.

		@param tag: The child's tag.
		@type tag: C{string}
		@return: A child C{Node} if the child is found, C{None} otherwise.
		@rtype: C{Node} (or C{None})
		"""
		for child in self.getChildren():
			if child.getTag() == tag:
				return child
		return None

	def addChild(self, child, zOrder=None, tag=None):
		"""
		Adds a child C{Node} to this node.

		@param child: The child to add.
		@type child: C{Node}
		@param zOrder: The zOrder at which the child will be added. Default is the child's current zOrder.
		@type zOrder: C{int}
		@param tag: A tag ID by which to reference the child. Default is the child's current tag.
		@type tag: C{str}
		"""
		if child._parent != None:
			warnings.warn("Failed to add child. Child must not have a parent.")
			return

		if zOrder is None:
			zOrder = child.getZOrder()
		if tag is None:
			tag = child.getTag()
		self._insertChild(child, zOrder)
		child.setTag(tag)
		child._parent = self
		child._setDirector(self.getDirector())
		if self._isRunning:
			child.onEnter()

	def reorderChild(self, child, zOrder):
		"""
		Changes the zOrder of a child of this node.

		@param child: The child to add.
		@type child: C{Node}
		@param zOrder: The zOrder at which the child will be added.
		@type zOrder: C{int}
		"""
		if child in self._children:
			self._children.remove(child)
		self._insertChild(child, zOrder)

	def _insertChild(self, child, zOrder):
		"""
		Private method. Inserts a child into the Node's child list, which is sorted by the children's zOrders.

		@param child: The Node to add.
		@type child: C{Node}
		@param zOrder: The zOrder at which the child will be added.
		@type zOrder: C{int}
		"""
		def comparator(child1, child2):
			if child1.getZOrder() > child2.getZOrder():
				return 1
			elif child1.getZOrder() == child2.getZOrder():
				return 0
			else:
				return -1
		child.setZOrder(zOrder)
		self._children.append(child)
		self._children.sort(comparator)

	def removeChild(self, child, shouldCleanup=True):
		"""
		Removes a child C{Node} from this node.
		
		@param child: The child to add.
		@type child: C{Node}
		@param shouldCleanup: Whether or not the child and its children should be cleaned up, i.e. stopping actions and removing all Timer callbacks. Default is True.
		@type shouldCleanup: C{bool}
		"""
		if child in self._children:
			self._detachChild(child, shouldCleanup)

	def removeChildByTag(self, tag, shouldCleanup=True):
		"""
		Removes a child C{Node} from this node as identified by its tag.
		
		@param tag: The child's unique identifier.
		@type tag: C{str}
		@param shouldCleanup: Whether or not the child and its children should be cleaned up, i.e. stopping actions and removing all Timer callbacks. Default is True.
		@type shouldCleanup: C{bool}
		"""
		child = self.getChildByTag(tag)
		if child:
			self.removeChild(child, tag)

	def removeAllChildren(self, shouldCleanup=True):
		"""
		Removes all children from this node.

		@param shouldCleanup: Whether or not the child and its children should be cleaned up, i.e. stopping actions and removing all Timer callbacks. Default is True.
		@type shouldCleanup: C{bool}
		"""
		for child in self._children:
			self._detachChild(child, shouldCleanup)

	def _detachChild(self, child, shouldCleanup):
		if self._isRunning:
			child.onExit()
		if shouldCleanup:
			child._cleanup()
		child._parent = None
		child._setDirector(None)
		self._children.remove(child)
#}


#{ Controller methods.
	def getController(self):
		"""
		Returns the controller of this Node. Default is C{None} if it is not defined.

		@return: The controller of this Node.
		@rtype: L{AbstractController} (or C{None})
		"""
		return self._controller

	controller = property(getController, doc="Read-only access to the Node's current controller.")

	def addController(self, controller):
		"""
		Adds an L{AbstractController} to the Node. This method will parent the controller's Node to this Node as well as automatically register it as a listener.

		@param controller: The controller to add.
		@type controller: L{AbstractController}
		"""
		if controller not in self._controllers:
			node = controller.getNode()
			if node is not None:
				self.addChild(node)
			controller._parent = self
			self._controllers.append(controller)
		self.addGestureListener(controller)

	def removeController(self, controller):
		"""
		Removes a Controller from the Node. This method will deparent the controller's Node from this Node as well as automatically unregister it as a listener.

		@param controller: The controller to remove.
		@type controller: L{AbstractController}
		"""
		if controller in self._controllers:
			node = controller.getNode()
			if node is not None:
				self.removeChild(node)
			controller._parent = None
			self._controllers.remove(controller)
		self.removeGestureListener(controller)

	def addGestureListener(self, listener):
		"""
		Adds a L{GestureListener} to the Scene, which will be registered to the L{GestureDispatch} when the Scene is entered.

		@param listener: A new listener.
		@type listener: L{GestureListener}
		"""
		if listener not in self._gestureListeners:
			self._gestureListeners.append(listener)
			if self.getDirector() is not None:
				self.getDirector().getGestureDispatch().addListener(listener)

	def removeGestureListener(self, listener):
		"""
		Removes a L{GestureListener} to the Scene, which will be unregistered from the L{GestureDispatch} when the Scene is exited.

		@param listener: The listener to be removed.
		@type listener: L{GestureListener}
		"""
		if listener in self._gestureListeners:
			self._gestureListeners.remove(listener)
			if self.getDirector() is not None:
				self.getDirector().getGestureDispatch().removeListener(listener)
#}


#{ Drawing methods.
	def draw(self, context):
		"""
		Draws the Node's contents to be displayed on the screen. Subclass and do your drawing in here. The context will already be translated to the node's current position, so drawing to C{Point(0,0)} will actually render to L{getPosition}.
		
		@param context: A Cairo context clipped to the dirtied rectangle.
		"""
		pass

	def _visit(self, context):
		"""
		Private method that is called by its parent whenever the node (and its children) need to be redrawn. Do not call this method directly as the L{Director} and L{GTKInterface} handle the redrawing.

		@param context: The Cairo context.
		"""
		# if this node is not visible, then don't draw this node or any of its children
		if not self.isVisible():
			return

		# push a new context onto the stack to transform
		context.save()

		# do any transformations here
		self._transform(context)

		# first draw any children that are behind this node
		for child in self._children:
			if child.getZOrder() < 0:
				child._visit(context)

		# then draw this node
		color = self._backgroundColor
		context.set_source_rgba(color.r, color.g, color.b, color.a)
		context.rectangle(0, 0, self._size.width, self._size.height)
		context.fill()	# first draw the background color
		self.draw(context)	# then do any user-defined drawing

		# finally, draw any children parallel or in front of this node
		for child in self._children:
			if child.getZOrder() >= 0:
				child._visit(context)

		# pop the new context off the stack before continuing.
		context.restore()


	def _transform(self, context):
		"""
		Private method that is called by C{_visit}. Performs transforms onto the current context (e.g. rotation, scaling).

		@param context: The Cairo context.
		"""

		transformAnchor = self.getTransformAnchorPoint()
		position = self.getPosition()

		# translate to the new position in which to scale and rotate.
		offset = self._getTransformOffset()
		context.translate(offset.x, offset.y)

		# rotate
		if (self._rotation != 0.0):
			context.rotate(self._rotation)

		# scale
		if (self._scaleX != 1.0 or self._scaleY != 1.0):
			context.scale(self._scaleX, self._scaleY)

		# translate back to original point before moving on
		if transformAnchor.x != 0.0 or transformAnchor.y != 0.0:
			context.translate(-transformAnchor.x, -transformAnchor.y)
		#if transformAnchor.x != 0.0 or transformAnchor.y != 0.0:
		#	context.translate(-position.x-transformAnchor.x, -position.y-transformAnchor.y)
		#elif position.x != 0.0 or position.y != 0.0:
		#	context.translate(-position.x, -position.y)

	def _getTransformOffset(self):
		"""
		Private method for performing a translation on the current context.
		"""
		transformAnchor = self.getTransformAnchorPoint()
		position = self.getPosition()
		offsetX = 0
		offsetY = 0
		if self._isAnchorPointRelative and (transformAnchor.x != 0.0 or transformAnchor.y != 0.0):
			offsetX -= transformAnchor.x
			offsetY -= transformAnchor.y
		if transformAnchor.x != 0.0 or transformAnchor.y != 0.0:
			offsetX += position.x + transformAnchor.x
			offsetY += position.y + transformAnchor.y
		elif position.x != 0.0 or position.y != 0.0:
			offsetX += position.x
			offsetY += position.y
		return Point(offsetX, offsetY)
#}


#{ Scene management.
	def onEnter(self):
		"""
		Called when this node will first be displayed. Override to have custom behaviors.
		"""
		gestureDispatch = self.getDirector().getGestureDispatch()
		for listener in self._gestureListeners:
			gestureDispatch.addListener(listener)
		for child in self._children:
			child.onEnter()
		self.activateTimers()
		self._isRunning = True

	def onEnterFromFinishedTransition(self):
		"""
		Called if there was a L{Transition}. Override to have custom behaviors.
		"""
		for child in self._children:
			child.onEnterFromFinishedTransition()

	def onExit(self):
		"""
		Called when this node will no longer be displayed. Override to have custom behaviors.
		"""
		gestureDispatch = self.getDirector().getGestureDispatch()
		for listener in self._gestureListeners:
			gestureDispatch.removeListener(listener)
		self.deactivateTimers()
		self._isRunning = False
		for child in self._children:
			child.onExit()
#}


#{ Timer methods.
	def activateTimers(self):
		"""
		Activates any L{Timer}C{s} that this Node has.
		"""
		for callback in self._scheduledTimers:
			timer = self._scheduledTimers[callback]
			scheduler = self.getDirector().getScheduler()
			scheduler.schedule(timer)
		actionManager = self.getDirector().getActionManager()
		actionManager.resumeAllActions(self)

	def deactivateTimers(self):
		"""
		Deactivates any L{Timer}C{s} that this Node has.
		"""
		for callback in self._scheduledTimers:
			timer = self._scheduledTimers[callback]
			scheduler = self.getDirector().getScheduler()
			scheduler.unschedule(timer)
		actionManager = self.getDirector().getActionManager()
		actionManager.pauseAllActions(self)

	def scheduleCallback(self, callback, interval=0):
		"""
		Registers a function to be called every C{interval} seconds.

		@requires: This method should only be used by a subclass. If you wish to create a timer, see L{Timer} and L{Scheduler}.

		@param callback: The method to be called by the L{Scheduler}.
		@type callback: Python C{function}
		@param interval: How often (in seconds) the C{callback} should be called.
		@type interval: Non-negative C{float}
		"""
		if callback in self._scheduledTimers:
			return
		if interval < 0.0:
			return

		timer = Timer(callback, interval)
		if self._isRunning:
			scheduler = self.getDirector().getScheduler()
			scheduler.schedule(timer)

		self._scheduledTimers[callback] = timer

	def unscheduleCallback(self, callback):
		"""
		Removes a C{callback} that has been added via L{scheduleCallback}.

		@param callback: The scheduled callback to unschedule.
		@type callback: C{function}
		"""
		if callback not in self._scheduledTimers:
			return

		timer = self._scheduledTimers[callback]
		del self._scheduledTimers[callback]

		if self._isRunning:
			scheduler = self.getDirector().getScheduler()
			scheduler.unschedule(timer)

	def getIntervalForScheduledCallback(self, callback):
		"""
		Returns how often (in seconds) the callback will be called (or C{None} if the callback is not currently scheduled).

		@param callback: The scheduled callback.
		@type callback: C{function}
		@return: The interval for the callback.
		@rtype: C{float} (or C{None})
		"""
		if callback not in self._scheduledTimers:
			return None
		return self._scheduledTimers[callback].getInterval()

	def setIntervalForScheduledCallback(self, callback, interval):
		"""
		Sets how often (in seconds) the callback will be called.

		@param callback: The scheduled callback.
		@type callback: C{function}
		@param interval: How often (in seconds) the C{callback} should be called.
		@type interval: Non-negative C{float}
		"""
		if callback not in self._scheduledTimers:
			return
		timer = self._scheduledTimers[callback]
		timer.setInterval(interval)
#}


#{ Action methods.
	def runAction(self, action):
		"""
		Runs an L{Action} on this Node.
		"""
		if self.getDirector() is not None:
			actionManager = self.getDirector().getActionManager()
			actionManager.addAction(action, self, (not self._isRunning))
			return action
		else:
			return None

	def stopAllActions(self):
		"""
		Stops all L{Action}C{s} currently running on this Node.
		"""
		actionManager = self.getDirector().getActionManager()
		actionManager.removeAllActions(self)

	def stopAction(self, action):
		"""
		Stops a particular L{Action} currently running on this Node.
		"""
		actionManager = self.getDirector().getActionManager()
		actionManager.removeAction(action)

	def stopActionByTag(self, tag):
		"""
		Stops a particular L{Action} currently running on this Node.

		@param tag: The tag of the Node.
		@type tag: C{string}
		"""
		actionManager = self.getDirector().getActionManager()
		actionManager.removeActionByTag(tag, self)

	def getActionByTag(self, tag):
		"""
		Gets a particular L{Action} currently running on this Node. If the Action cannot be found, it will return C{None}.

		@param tag: The tag of the Node.
		@type tag: C{string}
		@return: The Action.
		@rtype: L{Action} (or C{None})
		"""
		actionManager = self.getDirector().getActionManager()
		return actionManager.getActionByTag(tag, self)

	def numberOfRunningActions(self):
		"""
		Returns the number of L{Action}C{s} currently running on this Node.
	
		@return: Number of running actions.
		@rtype: C{int}
		"""
		actionManager = self.getDirector().getActionManager()
		return actionManager.getNumberOfRunningActions(self)
#}


#{ Cleanup
	def _cleanup(self):
		"""
		Private method used by Node. Stops all actions for the Node, clears out any scheduled timers, and tells its children to do the same.
		"""
		self.stopAllActions()
		self._scheduledTimers = {}
		for child in self._children:
			child._cleanup()
Esempio n. 58
0
def main(argv):
    port = 1
    baud = 115200
    outputfile = 'log'
    print 'CommTool V0.3'
    try:
        opts, args = getopt.getopt(argv,"hlp:o:b:",["help","list","port=","baudrate=","output="])
    except getopt.GetoptError:
        print 'Wrong arguments, try: python logtool.py -h'
        sys.exit(2)

    #parse the parameters input form console
    for opt, arg in opts:
        # print opt, args #debug only  
        if opt in ("-h", "--help"):
            print 'Usage: python logtool.py [OPTION]... [FILE]...'
            print 'python logtool.py -p <port> -b <baudrate> -o <logfile>'
            print 'If the <args> are not set, the default values are used:'
            print 'port = 1, baudrate = 115200, logfile = log.log'
            print 'Example: '
            print 'python logtool.py -p 2'
            print 'python logtool.py -p 1 -b 9600'
            print 'python logtool.py -p 1 -b 9600 -o mylog.log'
            print ''
            print 'Mandatory arguments to long options are mandatory for short options too.'
            print '-p, --port                       Uart port number'
            print '-b, --baudrate                   Baudrate for selected port'
            print '-o, --output                     Output file for storing the log'
            print '-h, --help                       Help doc'
            print '-l, --list                       List avaliable com ports'
            print ''
            #print 'python -m serial.tools.list_ports    --show the avaliable uart ports'
            sys.exit()
        elif opt in ("-p", "--port"):
            port = string.atoi(arg)
            if port < 0:
                print 'Port number error'
                sys.exit()
        elif opt in ("-b", "--baudrate"):
            baud = string.atoi(arg)
            print 'baud', baud
        elif opt in ("-o", "--output"):
            outputfile = arg + "_COM" + str(port) + ".log"
        elif opt in ("-l", "--list"):
			#print(serial_ports())
			list_ports()
        else:
            print 'Wrong pararmeters, try: python logtool.py -h'

    print 'Ctrl+C to exit'

    logger = logging.getLogger('LOG')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(outputfile)
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # create formatter and add it to the handlers
    #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    console_color = Color()

    # 'application' code
    #logger.debug('debug message')
    #logger.info('info message')
    #logger.warn('warn message')
    #logger.error('error message')
    #logger.critical('critical message')

    try:
        ser = serial.Serial(port-1, baud, timeout=0)
        #print ser
    except:
        print 'Can\'t open uart', port
        sys.exit()

    toogle_color = False
    try:
        while True:
            start_time = datetime.now()
            cur_time = start_time
            last_time = start_time
            s = ''
            while True:
                cur_time = datetime.now()
                num = ser.inWaiting()
                if num > 0:
                    last_time = cur_time    
                    s += ser.read(num)
                else:
                    idle_time = cur_time - last_time
                    time.sleep(0.001)
                    if idle_time.microseconds > 10000:
                        break
            if s != '':
                if not toogle_color:
                    toogle_color = True
                    console_color.set_cmd_color(FOREGROUND_GREEN | FOREGROUND_INTENSITY)
                    logger.info(s)
                else:
                    toogle_color = False
                    console_color.reset_color()
                    logger.info(s)
                # console_color.print_green_text(start_time)
                # print s
    except:
        print 'Ctrl+C pressed'
    ser.close()
    console_color.reset_color()
    print 'Exit'