Exemplo n.º 1
0
 def get_color():
     iconcolor = None
     background = node.color
     if background is not None:
         c1 = Color("Black")
         c2 = Color("White")
         if Color.distance(background, c1)> Color.distance(background, c2):
             iconcolor = c1
         else:
             iconcolor = c2
     return iconcolor, background
Exemplo n.º 2
0
 def on_selfill(self, origin, rgb, *args):
     # print (origin, rgb, args)
     if rgb[0] == 255 and rgb[1] == 255 and rgb[2] == 255:
         color = None
     else:
         color = Color(rgb[0], rgb[1], rgb[2])
     self.widget_scene.context.elements.default_fill = color
Exemplo n.º 3
0
 def validate(self):
     settings = self.settings
     for v in FLOAT_PARAMETERS:
         if v in settings:
             settings[v] = float(settings[v])
     for v in INT_PARAMETERS:
         if v in settings:
             settings[v] = int(float(settings[v]))
     for v in BOOL_PARAMETERS:
         if v in settings:
             settings[v] = str(settings[v]).lower() == "true"
     for v in STRING_PARAMETERS:
         if v in settings:
             settings[v] = settings[v]
     for v in COLOR_PARAMETERS:
         if v in settings:
             settings[v] = Color(settings[v])
     for v in LIST_PARAMETERS:
         if v in settings:
             if isinstance(settings[v], str):
                 myarr = []
                 sett = settings[v]
                 if sett != "":
                     # First of all is it in he old format where we used eval?
                     if sett.startswith("["):
                         sett = sett[1:-1]
                     if "'," in sett:
                         slist = sett.split(",")
                         for n in slist:
                             n = n.strip().strip("'")
                             myarr.append(n)
                     else:
                         myarr = [sett.strip().strip("'")]
                 settings[v] = myarr
Exemplo n.º 4
0
 def load(self, settings, section):
     settings.read_persistent_attributes(section, self)
     update_dict = settings.read_persistent_string_dict(section, suffix=True)
     self.settings.update(update_dict)
     self.validate()
     hexa = self.settings.get("hex_color")
     if hexa is not None:
         self.color = Color(hexa)
Exemplo n.º 5
0
 def __init__(self, scene, camera, index, mid=False):
     self.cam = camera
     self.mid = mid
     self.index = index
     half = CORNER_SIZE / 2.0
     Widget.__init__(self, scene, -half, -half, half, half)
     self.update()
     c = Color.distinct(self.index + 2)
     self.pen = wx.Pen(wx.Colour(c.red, c.green, c.blue))
Exemplo n.º 6
0
def swizzlecolor(c):
    if c is None:
        return None
    if isinstance(c, int):
        c = Color(argb=c)
    try:
        return c.blue << 16 | c.green << 8 | c.red
    except (ValueError, TypeError):
        return None
Exemplo n.º 7
0
 def matching_color(col1, col2):
     result = False
     if col1 is None and col2 is None:
         result = True
     elif col1 is not None and col1.argb is not None and col2 is not None and col2.argb is not None:
         if fuzzy:
             distance = Color.distance(col1, col2)
             result = distance < fuzzydistance
         else:
             result = col1 == col2
     return result
Exemplo n.º 8
0
 def _get_color(self, key):
     color_key = f"color_{key}"
     if hasattr(self.context, color_key):
         s = getattr(self.context, color_key)
         if len(s) == 0 or s == "default":
             # print ("Reset requested for color: %s" % color_key)
             s = self.default_color[key]
             setattr(self.context, color_key, s)
     else:
         s = self.default_color[key]
     c = Color(s)
     return wx.Colour(red=c.red, green=c.green, blue=c.blue, alpha=c.alpha)
Exemplo n.º 9
0
        def scene_color(command, _, channel, data, aspect=None, color=None, **kwargs):
            """
            Sets the scene colors. This is usually done with `scene color <aspect> <color>` which
            sets the aspect to the color specified. `scene color unset` unsets all colors and returns
            them to the default settings. `scene color random` changes all colors to random.
            """
            if aspect is None:
                for key in dir(self.context):
                    if key.startswith("color_"):
                        channel(key[6:])
            else:
                color_key = f"color_{aspect}"
                if aspect == "unset":  # reset all
                    self.widget_scene.colors.set_default_colors()
                    self.context.signal("theme", True)
                    return "scene", data
                if aspect == "random":  # reset all
                    self.widget_scene.colors.set_random_colors()
                    self.context.signal("theme", True)
                    return "scene", data
                if color == "unset":  # reset one
                    setattr(self.context, color_key, "default")
                    self.context.signal("theme", True)
                    return "scene", data
                if color == "random":  # randomize one
                    random_color = "#%02X%02X%02X" % (
                        random.randint(0, 255),
                        random.randint(0, 255),
                        random.randint(0, 255),
                    )
                    setattr(self.context, color_key, random_color)
                    self.context.signal("theme", True)
                    return "scene", data

                if color is None:
                    channel(
                        _(
                            "No color given! Please provide one like 'green', '#RRBBGGAA' (i.e. #FF000080 for semitransparent red)"
                        )
                    )
                    return "scene", data
                color = Color(color)
                if hasattr(self.context, color_key):
                    setattr(self.context, color_key, color.hexa)
                    channel(_("Scene aspect color is set."))
                    self.context.signal("theme", False)
                else:
                    channel(_("%s is not a known scene color command") % aspect)

            return "scene", data
Exemplo n.º 10
0
 def click(event=None):
     color_data = wx.ColourData()
     color_data.SetColour(wx.Colour(swizzlecolor(ctrl.color)))
     dlg = wx.ColourDialog(self, color_data)
     if dlg.ShowModal() == wx.ID_OK:
         color_data = dlg.GetColourData()
         data = Color(
             swizzlecolor(color_data.GetColour().GetRGB()), 1.0
         )
         set_color(data)
         try:
             setattr(obj, param, data_type(data))
         except ValueError:
             # cannot cast to data_type, pass
             pass
Exemplo n.º 11
0
 def event(
     self, window_pos=None, space_pos=None, event_type=None, nearest_snap=None
 ):
     response = RESPONSE_CHAIN
     if event_type == "leftdown":
         self.p1 = complex(space_pos[0], space_pos[1])
         _ = self.scene.context._
         self.text = SVGText("")
         if nearest_snap is None:
             x = space_pos[0]
             y = space_pos[1]
         else:
             x = nearest_snap[0]
             y = nearest_snap[1]
         self.x = x
         self.y = y
         self.text *= "translate({x}, {y}) scale({scale})".format(
             x=x, y=y, scale=UNITS_PER_PIXEL
         )
         dlg = TextEntry(self.scene.context, "", None, wx.ID_ANY, "")
         if dlg.ShowModal() == wx.ID_OK:
             self.text.text = dlg.result_text
             if dlg.result_anchor == 1:
                 self.text.anchor = "middle"
             elif dlg.result_anchor == 2:
                 self.text.anchor = "end"
             else:
                 self.text.anchor = "start"
             elements = self.scene.context.elements
             node = elements.elem_branch.add(text=self.text, type="elem text")
             color = dlg.result_colour
             rgb = color.GetRGB()
             color = swizzlecolor(rgb)
             color = Color(color, 1.0)
             node.fill = color
             # Translate wxFont to SVG font....
             node.wxfont = dlg.result_font
             dlg.store_font_history()
             wxfont_to_svg(node)
             if elements.classify_new:
                 elements.classify([node])
             self.notify_created(node)
         dlg.Destroy()
         response = RESPONSE_CONSUME
     return response
Exemplo n.º 12
0
        def linetext(command,
                     channel,
                     _,
                     font=None,
                     font_size=None,
                     remainder=None,
                     **kwargs):
            context.setting(str, "shx_preferred", None)
            if font is not None:
                context.shx_preferred = font
            font = context.shx_preferred

            safe_dir = realpath(get_safe_path(context.kernel.name))
            if font is None:
                channel(_("SHX fonts in {path}:").format(path=safe_dir))
                for p in glob(join(safe_dir, "*.shx")):
                    channel(p)
                for p in glob(join(safe_dir, "*.SHX")):
                    channel(p)
                return
            font_path = join(safe_dir, font)
            if not os.path.exists(font_path):
                channel(
                    _("Font was not found at {path}").format(path=font_path))
                for p in glob(join(safe_dir, "*.shx")):
                    channel(p)
                for p in glob(join(safe_dir, "*.SHX")):
                    channel(p)
                return
            if remainder is None:
                channel(_("No text to make a path with."))
                return
            font = ShxFont(font_path)
            path = ShxPath()
            font.render(path, remainder, True, float(font_size))
            path_node = PathNode(
                path=path.path,
                matrix=Matrix.translate(0, float(font_size)),
                stroke=Color("black"),
            )
            context.elements.elem_branch.add_node(path_node)
            context.signal("element_added", path_node)
Exemplo n.º 13
0
 def process_draw(self, gc):
     """
     Draw all the registered reticles.
     """
     context = self.scene.context
     try:
         if context.draw_mode & DRAW_MODE_RETICLE == 0:
             # Draw Reticles
             gc.SetBrush(wx.TRANSPARENT_BRUSH)
             for index, ret in enumerate(self.reticles):
                 r = self.reticles[ret]
                 self.pen.SetColour(Color.distinct(index + 2).hex)
                 gc.SetPen(self.pen)
                 x = r[0]
                 y = r[1]
                 if x is None or y is None:
                     x = 0
                     y = 0
                 x, y = self.scene.convert_scene_to_window([x, y])
                 gc.DrawEllipse(x - 5, y - 5, 10, 10)
     except AttributeError:
         pass
Exemplo n.º 14
0
 def color(self):
     color = self.settings.get("color")
     if color is None:
         try:
             type = self.type
         except AttributeError:
             type = None
         if type == "op cut":
             return Color("red")
         elif type == "op engrave":
             return Color("blue")
         elif type == "op hatch":
             return Color("green")
         elif type == "op raster":
             return Color("black")
         elif type == "op image":
             return Color("transparent")
         elif type == "op dots":
             return Color("transparent")
         else:
             return Color("white")
     if isinstance(color, Color):
         return color
     return Color(color)
Exemplo n.º 15
0
    def parse(self, data, elements):
        self.path = Numpath()

        def position(p):
            if p is None:
                return
            from_x, from_y, to_x, to_y = p

            if self.program_mode:
                if self.laser:
                    self.path.line(complex(from_x, from_y),
                                   complex(to_x, to_y))

        self.position = position
        self.write(data)
        self.path.uscale(UNITS_PER_MIL)
        elements.elem_branch.add(
            type="elem numpath",
            path=self.path,
            stroke=Color("black"),
            **self.settings.settings,
        )
        elements.signal("refresh_scene", 0)
Exemplo n.º 16
0
    def set_buttons(self, new_values, button_bar):
        show_tip = not self.context.disable_tool_tips
        button_bar._current_layout = 0
        button_bar._hovered_button = None
        button_bar._active_button = None
        button_bar.ClearButtons()
        buttons = []
        for button, name, sname in new_values:
            buttons.append(button)

        def sort_priority(elem):
            return elem.get("priority", 0)

        buttons.sort(key=sort_priority)  # Sort buttons by priority

        for button in buttons:
            # Every registered button in the updated lookup gets created.
            new_id = wx.NewId()
            group = button.get("group")
            resize_param = button.get("size")
            if "multi" in button:
                # Button is a multi-type button
                b = button_bar.AddHybridButton(
                    button_id=new_id,
                    label=button["label"],
                    bitmap=button["icon"].GetBitmap(resize=resize_param),
                    help_string=button["tip"] if show_tip else "",
                )
                button_bar.Bind(
                    RB.EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED,
                    self.drop_click,
                    id=new_id,
                )
            else:
                if "group" in button:
                    bkind = RB.RIBBON_BUTTON_TOGGLE
                else:
                    bkind = RB.RIBBON_BUTTON_NORMAL
                if "toggle" in button:
                    bkind = RB.RIBBON_BUTTON_TOGGLE
                b = button_bar.AddButton(
                    button_id=new_id,
                    label=button["label"],
                    bitmap=button["icon"].GetBitmap(resize=resize_param),
                    bitmap_disabled=button["icon"].GetBitmap(
                        resize=resize_param, color=Color("grey")),
                    help_string=button["tip"] if show_tip else "",
                    kind=bkind,
                )

            # Store all relevant aspects for newly registered button.
            b.button_dict = button
            b.state_pressed = None
            b.state_unpressed = None
            b.toggle = False
            b.parent = button_bar
            b.group = group
            b.identifier = button.get("identifier")
            b.action = button.get("action")
            b.action_right = button.get("right")
            if "rule_enabled" in button:
                b.enable_rule = button.get("rule_enabled")
            else:
                b.enable_rule = lambda cond: True

            if "multi" in button:
                # Store alternative aspects for multi-buttons, load stored previous state.

                multi_action = button["multi"]
                multi_ident = button.get("identifier")
                b.save_id = multi_ident
                initial_id = self.context.setting(str, b.save_id, "default")

                for i, v in enumerate(multi_action):
                    key = v.get("identifier", i)
                    self._store_button_aspect(b, key)
                    self._update_button_aspect(b, key, **v)
                    if "icon" in v:
                        v_icon = button.get("icon")
                        self._update_button_aspect(
                            b,
                            key,
                            bitmap_large=v_icon.GetBitmap(resize=resize_param),
                            bitmap_large_disabled=v_icon.GetBitmap(
                                resize=resize_param, color=Color("grey")),
                        )
                        if resize_param is None:
                            siz = v_icon.GetBitmap().GetSize()
                            small_resize = 0.5 * siz[0]
                        else:
                            small_resize = 0.5 * resize_param
                        self._update_button_aspect(
                            b,
                            key,
                            bitmap_small=v_icon.GetBitmap(resize=small_resize),
                            bitmap_small_disabled=v_icon.GetBitmap(
                                resize=small_resize, color=Color("grey")),
                        )
                    if key == initial_id:
                        self._restore_button_aspect(b, key)
            if "toggle" in button:
                # Store toggle and original aspects for toggle-buttons

                b.state_pressed = "toggle"
                b.state_unpressed = "original"

                self._store_button_aspect(b, "original")

                toggle_action = button["toggle"]
                key = toggle_action.get("identifier", "toggle")
                self._store_button_aspect(b, key, **toggle_action)
                if "icon" in toggle_action:
                    toggle_icon = toggle_action.get("icon")
                    self._update_button_aspect(
                        b,
                        key,
                        bitmap_large=toggle_icon.GetBitmap(
                            resize=resize_param),
                        bitmap_large_disabled=toggle_icon.GetBitmap(
                            resize=resize_param, color=Color("grey")),
                    )
                    if resize_param is None:
                        siz = v_icon.GetBitmap().GetSize()
                        small_resize = 0.5 * siz[0]
                    else:
                        small_resize = 0.5 * resize_param
                    self._update_button_aspect(
                        b,
                        key,
                        bitmap_small=toggle_icon.GetBitmap(
                            resize=small_resize),
                        bitmap_small_disabled=toggle_icon.GetBitmap(
                            resize=small_resize, color=Color("grey")),
                    )
            # Store newly created button in the various lookups
            self.button_lookup[new_id] = b
            if group is not None:
                c_group = self.group_lookup.get(group)
                if c_group is None:
                    c_group = []
                    self.group_lookup[group] = c_group
                c_group.append(b)

            button_bar.Bind(RB.EVT_RIBBONBUTTONBAR_CLICKED,
                            self.button_click,
                            id=new_id)
            button_bar.Bind(wx.EVT_RIGHT_UP, self.button_click_right)

        self.ensure_realize()