def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        central_widget = QtGui.QWidget()

        self._stylesheet = "color: {}; background-color: {}"

        layout = QtGui.QFormLayout()
        self._lbl1 = QtGui.QLabel()
        self._lbl1.setText('Foreground')
        self._fg_color = ColorPicker()
        self._fg_color.colorChanged.connect(self._update_foreground)

        layout.addRow(self._lbl1, self._fg_color)

        self._lbl2 = QtGui.QLabel()
        self._lbl2.setText('Background')
        self._bg_color = ColorPicker()
        self._bg_color.colorChanged.connect(self._update_background)

        self._fg_color.setColor(QtGui.QColor(0, 0, 0))
        self._bg_color.setColor(QtGui.QColor(255, 255, 255))

        layout.addRow(self._lbl2, self._bg_color)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
Exemple #2
0
    def Gague_Value_ColorChange(self):

        # 打开颜色识获器
        my_color_picker = ColorPicker(useAlpha=False)
        picker_color = my_color_picker.rgb2hex(my_color_picker.getColor())
        # print("------->")
        # print(picker_color)

        value_color = '#' + picker_color

        self.label_value.setStyleSheet('color:' + value_color + '; background: transparent;')

        # 将数值颜色写入Config json文件
        with open('./gaguge_config.json', 'r', encoding='utf8') as read_congfig_file:
            str = read_congfig_file.read()
            json_data = json.loads(str)
            self.pointer_color = json_data['pointer_color']
            json_data['value_color'] = value_color
            write_json =  json_data
        with  open('./gaguge_config.json','w+',encoding = 'utf-8') as congfig_file:
            json.dump(write_json, congfig_file, indent=4, sort_keys=True)

        # 生成新的home_page.xml文件
        with  open('./meter_images/home_page.xml','w',encoding = 'utf-8') as f:
            f.write('''<?xml ruler_y="220" ruler_x="297,42,-439,-112"?>
<window name="home_page" style:normal:bg_color="#FFFFFF">
<guage name="guage" x="0" y="0" w="320" h="240" draw_type="scale_auto" image="voltmeter">
    <guage_pointer name="guage_pointer" x="294" y="10" w="7" h="420" value="0" angle="-90" anchor_x="0.5" anchor_y="0.5" animation="value(easing=bounce_out,from=0,to=-90)" min="-90" max="0" style:normal:fg_color="#00000000" style:normal:bg_color="''' + self.pointer_color + '''" image="pointer_2" style:normal:border="all" style:normal:border_color="#00000000"/>
</guage>
<label name="val" x="221" y="155" w="89" h="75" style:normal:font_size="30" style:normal:text_color="'''+ value_color +'''" style:normal:text_align_h="right" visible="true" min="0" max="40" enable="true" style:normal:font_name="default" text="0"/>
</window>''')
            f.close()
 def onClick(self):
     proxy = self.proxy()
     if proxy:
         self.dialog = ColorPicker(self.attribs['widget_label'],
                                   hsv_degree_to_rgb_hex_str(self.attribs['item_state']))
         color = self.dialog.show()
         self.dialog = None
         if color is not None:
             proxy.cmd_set_hsv(rgb_hex_str_to_hsv_degree(color))
Exemple #4
0
    def Gague_Pointer_ColorChange(self):

        # 打开颜色识获器
        my_color_picker = ColorPicker(useAlpha=False)
        picker_color = my_color_picker.rgb2hex(my_color_picker.getColor())
        # print("------->")
        # print(picker_color)

        pointer_color = '#' + picker_color

        # 生成新的svg图形
        with  open('./meter_images/dx.svg','w',encoding = 'utf-8') as f:
            f.write('<svg id="图层_1" data-name="图层 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 5.67 127.56"><defs><style>.cls-1,.cls-2{fill:'+ pointer_color + ';}.cls-2{stroke:#000;stroke-miterlimit:10;stroke-width:0.25px;}</style></defs><title>指针45</title><polygon class="cls-1" points="5.67 127.56 0 127.56 2.83 0 4.25 63.78 5.67 127.56"/><polygon class="cls-1" points="1.42 63.78 2.83 63.78 4.25 63.78 5.67 127.56 0 127.56 1.42 63.78"/><polygon class="cls-2" points="1.42 63.78 4.25 63.78 2.83 0 1.42 63.78"/></svg>')
            f.close()

        # 将表盘指针颜色写入Config json文件
        with open('./gaguge_config.json', 'r', encoding='utf8') as read_congfig_file:
            str_temp = read_congfig_file.read()
            json_data = json.loads(str_temp)
            self.value_color = json_data['value_color']
            self.value_min = json_data['value_min']
            self.value_max = json_data['value_max']
            value_min_str = str(self.value_min)
            value_max_str = str(self.value_max)
            json_data['pointer_color'] = pointer_color
            write_json =  json_data
        with  open('./gaguge_config.json','w+',encoding = 'utf-8') as congfig_file:
            json.dump(write_json, congfig_file, indent=4, sort_keys=True)


        # 生成新的home_page.xml文件
        with  open('./meter_images/home_page.xml','w',encoding = 'utf-8') as f:
            f.write('''<?xml ruler_y="220" ruler_x="297,42,-439,-112"?>
<window name="home_page" style:normal:bg_color="#FFFFFF">
<guage name="guage" x="0" y="0" w="320" h="240" draw_type="scale_auto" image="voltmeter">
    <guage_pointer name="guage_pointer" x="294" y="10" w="7" h="420" value="0" angle="-90" anchor_x="0.5" anchor_y="0.5" animation="value(easing=bounce_out,from=0,to=-90)" min="-90" max="0" style:normal:fg_color="#00000000" style:normal:bg_color="''' + pointer_color + '''" image="pointer_2" style:normal:border="all" style:normal:border_color="#00000000"/>
</guage>
<label name="val" x="221" y="155" w="89" h="75" style:normal:font_size="30" style:normal:text_color="'''+ self.value_color +'''" style:normal:text_align_h="right" visible="true" min="'''+ value_min_str + '''" max="'''+ value_max_str + '''" enable="true" style:normal:font_name="default" text="0"/>
</window>''')
            f.close()

        # 刷新表盘指针svg
        defaultPix2 = QtGui.QPixmap("./meter_images/dx.svg")
        # 旋转pix
        self.rotation = -45
        self.transform = QtGui.QTransform().rotate(self.rotation)
        defaultPix2 = defaultPix2.transformed(self.transform, QtCore.Qt.SmoothTransformation)
        self.label_pointer.setPixmap(defaultPix2)
Exemple #5
0
    def addRepoHandler(self):
        path = self.ui.path.text()
        for r in enumerate(self.repos):
            if r[1][0] == path:
                errbox = QMessageBox()
                errbox.setText(f"{path} is already listed in {self.json_path}")
                errbox.exec()
                return
        colour = ColorPicker().getColor()
        hexcolour = '%02x%02x%02x' % (
            int(colour[0]),  # this is actually so dumb
            int(colour[1]) if int(colour[0]) != 255 or not int(colour[1]) else
            int(colour[1]) + 1,
            int(colour[2]) if int(colour[0]) != 255 or not int(colour[2]) else
            int(colour[2]) + 1)
        if self.ui.checkBox.isChecked():
            if not re.match(self.urlregexp, self.ui.remote.text()):
                errbox = QMessageBox()
                errbox.setText("Invalid URL")
                errbox.exec()
                return
            self.addNewRepo(path, self.ui.remote.text(), hexcolour, self.repos)
        else:
            self.addRepoFromExisting(path, hexcolour, self.repos)

        self.updateTables()
Exemple #6
0
    def openColorDialog(self):
        # color = QColorDialog.getColor()

        # if color.isValid():
        #     # print(color.name())
        #     print(color.name())
        #     color_R = color.red()
        #     color_G = color.green()
        #     color_B = color.blue()
        #     self.udp_send[40] = color_R
        #     self.udp_send[41] = color_G
        #     self.udp_send[42] = color_B
        #     # print(color_R)

        my_color_picker = ColorPicker(useAlpha=False)
        my_color_picker.DX_Color_OutSingal.connect(self.dx_color)
        picked_color = my_color_picker.hsv2hex(my_color_picker.getColor())
Exemple #7
0
    def pick_color(self, mode):

        cp = ColorPicker()
        self.unfocusGui()

        if mode == "diffuse":
            try:
                oldr, oldg, oldb = (int(self.ui.difx.text()),
                                    int(self.ui.dify.text()),
                                    int(self.ui.difz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.difx.setText(str(int(r)))
            self.ui.dify.setText(str(int(g)))
            self.ui.difz.setText(str(int(b)))

        if mode == "specular":
            try:
                oldr, oldg, oldb = (int(self.ui.specx.text()),
                                    int(self.ui.specy.text()),
                                    int(self.ui.specz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.specx.setText(str(int(r)))
            self.ui.specy.setText(str(int(g)))
            self.ui.specz.setText(str(int(b)))

        if mode == "emission":
            try:
                oldr, oldg, oldb = (int(self.ui.emisx.text()),
                                    int(self.ui.emisy.text()),
                                    int(self.ui.emisz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.emisx.setText(str(int(r)))
            self.ui.emisy.setText(str(int(g)))
            self.ui.emisz.setText(str(int(b)))

        self.focusGui()
Exemple #8
0
 def __init__(self, source, parent=None):
     super().__init__(parent)
     self.source = source
     self.grid = QGridLayout()
     self.grid.setSpacing(0)
     self.grid.setContentsMargins(0, 0, 0, 0)
     self.picker = ColorPicker(self)
     self.color_preview = ColorPreview(self.source, self)
     self.color_preview.switch.connect(self.switchColors)
     self.palette = [Color(n, self.source, self) for n in range(16)]
     positions = [(row, col) for row in range(4) for col in range(4)]
     for position, swatch in zip(positions, self.palette):
         swatch.color_selected.connect(self.selectColor)
         swatch.edit.connect(self.openPicker)
         self.grid.addWidget(swatch, *position)
     self.enabled = False
     self.main_layout = QHBoxLayout()
     self.main_layout.addLayout(self.grid)
     self.main_layout.addWidget(self.color_preview)
     self.main_layout.setContentsMargins(0, 0, 5, 0)
     self.main_layout.setSpacing(19)
     self.setLayout(self.main_layout)
class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        central_widget = QtGui.QWidget()

        self._stylesheet = "color: {}; background-color: {}"

        layout = QtGui.QFormLayout()
        self._lbl1 = QtGui.QLabel()
        self._lbl1.setText('Foreground')
        self._fg_color = ColorPicker()
        self._fg_color.colorChanged.connect(self._update_foreground)

        layout.addRow(self._lbl1, self._fg_color)

        self._lbl2 = QtGui.QLabel()
        self._lbl2.setText('Background')
        self._bg_color = ColorPicker()
        self._bg_color.colorChanged.connect(self._update_background)

        self._fg_color.setColor(QtGui.QColor(0, 0, 0))
        self._bg_color.setColor(QtGui.QColor(255, 255, 255))

        layout.addRow(self._lbl2, self._bg_color)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def _color_to_hex(self, color):
        r = color.red()
        g = color.green()
        b = color.blue()

        return "#{1:0{0}x}{2:0{0}x}{3:0{0}x}".format(2, r, g, b)

    def _update_foreground(self, color):
        logger.log(logging.DEBUG,
                   "Updating fg_color: {}".format(self._color_to_hex(color)))
        self._update_stylesheet()

    def _update_background(self, color):
        logger.log(logging.DEBUG,
                   "Updating bg_color: {}".format(self._color_to_hex(color)))
        self._update_stylesheet()

    def _update_stylesheet(self):
        c1 = self._color_to_hex(self._fg_color.color())
        c2 = self._color_to_hex(self._bg_color.color())
        self.setStyleSheet(self._stylesheet.format(c1, c2))
class ListItemColor(ListItemWithValue):
    def __init__(self, proxy):
        super(ListItemColor, self).__init__("text", proxy)
        self.set_show_next_icon(True)
        self.dialog = None

    def update(self, changed, deleted):
        super(ListItemColor, self).update(changed, deleted)
        if self.dialog:
            if 'widget_label' in changed:
                self.dialog.set_title(changed['widget_label'])
            if 'item_state' in changed:
                self.dialog.set_color(hsv_degree_to_rgb_hex_str(self.attribs['item_state']))

    def onClick(self):
        proxy = self.proxy()
        if proxy:
            self.dialog = ColorPicker(self.attribs['widget_label'],
                                      hsv_degree_to_rgb_hex_str(self.attribs['item_state']))
            color = self.dialog.show()
            self.dialog = None
            if color is not None:
                proxy.cmd_set_hsv(rgb_hex_str_to_hsv_degree(color))
Exemple #11
0
class ColorEditor(QWidget):
    colorChanged = pyqtSignal(object)

    def __init__(self, label, parent=None):
        super(ColorEditor, self).__init__(parent)
        layout = QGridLayout()
        self.color = QLineEdit()
        self.colorPicker = ColorPicker()
        self.colorPicker.setVisible(False)
        self.hueSlider = QSlider()
        self.hueSlider.setVisible(False)
        self.hueSlider.setMinimum(0)
        self.hueSlider.setMaximum(100.0)
        self.hueSlider.setOrientation(Qt.Vertical)
        self.hueSlider.setMaximumHeight(100.0)
        self.rect = ColorRect()
        self.hue = QSpinBox()
        self.saturation = QSpinBox()
        self.lightness = QSpinBox()
        self.labelHue = QLabel("H")
        self.labelSaturation = QLabel("S")
        self.labelLightness = QLabel("L")
        self.red = QSpinBox()
        self.green = QSpinBox()
        self.blue = QSpinBox()
        self.labelRed = QLabel("R")
        self.labelGreen = QLabel("G")
        self.labelBlue = QLabel("B")
        self.hue.setVisible(False)
        self.saturation.setVisible(False)
        self.lightness.setVisible(False)
        self.red.setVisible(False)
        self.green.setVisible(False)
        self.blue.setVisible(False)
        self.labelHue.setVisible(False)
        self.labelSaturation.setVisible(False)
        self.labelLightness.setVisible(False)
        self.labelRed.setVisible(False)
        self.labelGreen.setVisible(False)
        self.labelBlue.setVisible(False)
        self.red.setMinimum(0)
        self.red.setMaximum(255)
        self.green.setMinimum(0)
        self.green.setMaximum(255)
        self.blue.setMinimum(0)
        self.blue.setMaximum(255)
        self.hue.setMinimum(0)
        self.hue.setMaximum(100.0)
        self.saturation.setMinimum(0)
        self.saturation.setMaximum(100.0)
        self.lightness.setMinimum(0)
        self.lightness.setMaximum(100.0)
        self.labelHue.setFixedWidth(15)
        self.labelSaturation.setFixedWidth(15)
        self.labelLightness.setFixedWidth(15)
        self.labelRed.setFixedWidth(15)
        self.labelGreen.setFixedWidth(15)
        self.labelBlue.setFixedWidth(15)
        l = QLabel(label)
        l.setMinimumWidth(100.0)

        layout.addWidget(l, 0, 0)
        layout.addWidget(self.rect, 0, 1)
        layout.addWidget(self.color, 0, 2, 1, 3)
        layout.addWidget(self.colorPicker, 1, 0, 3, 2)
        layout.addWidget(self.hueSlider, 1, 2, 3, 1)
        layout.addWidget(self.labelHue, 1, 3)
        layout.addWidget(self.hue, 1, 4)
        layout.addWidget(self.labelSaturation, 2, 3)
        layout.addWidget(self.saturation, 2, 4)
        layout.addWidget(self.labelLightness, 3, 3)
        layout.addWidget(self.lightness, 3, 4)
        layout.addWidget(self.labelRed, 1, 5)
        layout.addWidget(self.red, 1, 6)
        layout.addWidget(self.labelGreen, 2, 5)
        layout.addWidget(self.green, 2, 6)
        layout.addWidget(self.labelBlue, 3, 5)
        layout.addWidget(self.blue, 3, 6)
        self.setLayout(layout)
        self.connectControls()

    def color(self):
        return QColor(self.color.text())

    def setColor(self, color):
        self.setColorParts(color)

    def disconnectControls(self):
        self.color.editingFinished.disconnect()
        self.hueSlider.valueChanged.disconnect()
        self.hueSlider.sliderReleased.disconnect()
        self.colorPicker.colorChanged.disconnect()
        self.colorPicker.colorPicked.disconnect()
        self.rect.mouseClicked.disconnect()
        self.hue.valueChanged.disconnect()
        self.saturation.valueChanged.disconnect()
        self.lightness.valueChanged.disconnect()
        self.red.valueChanged.disconnect()
        self.green.valueChanged.disconnect()
        self.blue.valueChanged.disconnect()

    def connectControls(self):
        self.color.editingFinished.connect(self.colorTextChanged)
        self.hueSlider.valueChanged.connect(self.hueChanged)
        self.hueSlider.sliderReleased.connect(self.huePicked)
        self.colorPicker.colorChanged.connect(self.colorPickerChanged)
        self.colorPicker.colorPicked.connect(self.colorPicked)
        self.rect.mouseClicked.connect(self.rectClicked)
        self.hue.valueChanged.connect(self.hueValueChanged)
        self.saturation.valueChanged.connect(self.saturationValueChanged)
        self.lightness.valueChanged.connect(self.lightnessValueChanged)
        self.red.valueChanged.connect(self.redValueChanged)
        self.green.valueChanged.connect(self.greenValueChanged)
        self.blue.valueChanged.connect(self.blueValueChanged)

    def rectClicked(self):
        self.setExpanded(not self.colorPicker.isVisible())

    def setExpanded(self, value):
        self.colorPicker.setVisible(value)
        self.hueSlider.setVisible(value)
        self.labelHue.setVisible(value)
        self.labelSaturation.setVisible(value)
        self.labelLightness.setVisible(value)
        self.hue.setVisible(value)
        self.saturation.setVisible(value)
        self.lightness.setVisible(value)
        self.labelRed.setVisible(value)
        self.labelGreen.setVisible(value)
        self.labelBlue.setVisible(value)
        self.red.setVisible(value)
        self.green.setVisible(value)
        self.blue.setVisible(value)

    def isExpanded(self):
        return self.colorPicker.isVisible()

    def setColorParts(self, value):
        self.disconnectControls()
        self.hue.setValue(round(value.hslHueF() * 100.0))
        self.hueSlider.setValue(round(value.hslHueF() * 100.0))
        self.colorPicker.setHue(value.hslHueF())
        self.saturation.setValue(round(value.hslSaturationF() * 100.0))
        self.lightness.setValue(round(value.lightnessF() * 100.0))
        self.red.setValue(value.red())
        self.green.setValue(value.green())
        self.blue.setValue(value.blue())
        self.color.setText(value.name())
        self.rect.setColor(value)
        self.connectControls()

    def colorTextChanged(self):
        color = QColor(self.color.text())
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def colorPicked(self, value):
        self.setColorParts(value)
        self.colorChanged.emit(value)

    def colorPickerChanged(self, value):
        self.setColorParts(value)

    def hueChanged(self, value):
        self.colorPicker.setHue(value / 100.0)
        color = QColor.fromHslF(value / 100.0, self.saturation.value() / 100.0, self.lightness.value() / 100.0, 1.0)
        self.setColorParts(color)

    def hueValueChanged(self, value):
        self.hueSlider.setValue(value)
        color = QColor.fromHslF(value / 100.0, self.saturation.value() / 100.0, self.lightness.value() / 100.0, 1.0)
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def huePicked(self):
        value = self.hueSlider.value()
        self.colorPicker.setHue(value / 100.0)
        color = QColor.fromHslF(value / 100.0, self.saturation.value() / 100.0, self.lightness.value() / 100.0, 1.0)
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def saturationValueChanged(self, value):
        color = QColor.fromHslF(self.hue.value() / 100.0, value / 100.0, self.lightness.value() / 100.0, 1.0)
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def lightnessValueChanged(self, value):
        color = QColor.fromHslF(self.hue.value() / 100.0, self.saturation.value() / 100.0, value / 100.0, 1.0)
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def redValueChanged(self, value):
        color = QColor.fromRgb(value, self.green.value(), self.blue.value())
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def greenValueChanged(self, value):
        color = QColor.fromRgb(self.red.value(), value, self.blue.value())
        self.setColorParts(color)
        self.colorChanged.emit(color)

    def blueValueChanged(self, value):
        color = QColor.fromRgb(self.red.value(), self.green.value(), value)
        self.setColorParts(color)
        self.colorChanged.emit(color)
Exemple #12
0
 def pick_bg_color(self):
     cp = ColorPicker(self.parent, "Select color", self.select_bg_color)
Exemple #13
0
def main_prog():

    # init objects every state will have
    mouse = MouseHandler()
    drawablesController = DrawablesController()
    colorPicker = None
    trashCan = None

    # create state manager depending on operation type selected in menu:
    if program_OperationType == MULTIPLICATION:
        stateManager = StateManagerMult(program_CuttingType,screen)
        stateManager.setMouse(mouse) # link state manager and mouse
        stateManager.setDrawablesController(drawablesController) # link state manager and drawables controller
        testRectangle = Rectangle(WIDTH/2,HEIGHT/2,350,350,screen,drawablesController,True,mouse,stateManager, 1)
        cutter = testRectangle.getCutter() # need to get cutter here for draw call

        colorPicker = ColorPicker(screen,WIDTH,HEIGHT,mouse,stateManager,drawablesController)
        stateManager.setColorPicker(colorPicker)

    elif program_OperationType == ADDITION:
        stateManager = StateManagerAdd(program_CuttingType,screen)
        stateManager.setMouse(mouse)    # link state manager and mouse
        stateManager.setDrawablesController(drawablesController) # link state manager and drawables controller

        # Create rectangles and their respective cutters
        testRectangle = Rectangle((int)(WIDTH/3),HEIGHT/3,270,270,screen,drawablesController,True,mouse,stateManager, 1)
        cutter = testRectangle.getCutter() # need to get cutter here for draw call
        testRectangle2 = Rectangle((int)(WIDTH/3),HEIGHT-(HEIGHT/4.5)+15,270,270,screen,drawablesController,True,mouse,stateManager, 2)
        cutter2 = testRectangle2.getCutter()
        testRectangle3 = Rectangle(WIDTH-(int)(WIDTH/5.7),HEIGHT/3,270,270,screen,drawablesController,True,mouse,stateManager, 3)
        cutter3 = testRectangle3.getCutter()
        testRectangle4 = Rectangle(WIDTH-(int)(WIDTH/5.7),HEIGHT-(HEIGHT/4.5)+15,270,270,screen,drawablesController,True,mouse,stateManager, 4)
        cutter4 = testRectangle4.getCutter()
        colorPicker = ColorPicker(screen,WIDTH,HEIGHT,mouse,stateManager,drawablesController)
        stateManager.setColorPicker(colorPicker)

    elif program_OperationType == SUBTRACTION:
        stateManager = StateManagerSub(program_CuttingType,screen)
        stateManager.setMouse(mouse) # link state manager and mouse
        stateManager.setDrawablesController(drawablesController) # link state manager and drawables controller

        testRectangle = Rectangle((int)((WIDTH/3)),HEIGHT/2-30,280, 280,screen,drawablesController,True,mouse,stateManager, 1)
        cutter = testRectangle.getCutter() # need to get cutter here for draw call
        testRectangle2 = Rectangle((int)((WIDTH/3)*2),HEIGHT/2-30,280,280,screen,drawablesController,True,mouse,stateManager, 2)
        cutter2 = testRectangle2.getCutter() # need to get cutter here for draw call

        colorPicker = ColorPicker(screen,WIDTH,HEIGHT,mouse,stateManager,drawablesController)
        trashCan = TrashCan(screen,WIDTH,HEIGHT,mouse,stateManager,drawablesController)
        stateManager.setColorPicker(colorPicker)
        stateManager.setTrashCan(trashCan)

    elif program_OperationType == DIVISION:
        # For division, rectangles are created later because the number of rectangles depends on the fractions
        stateManager = StateManagerDiv(program_CuttingType,screen)
        stateManager.setMouse(mouse) # link state manager and mouse
        stateManager.setDrawablesController(drawablesController) # link state manager and drawables controller
        colorPicker = ColorPicker(screen,WIDTH,HEIGHT,mouse,stateManager,drawablesController)
        stateManager.setColorPicker(colorPicker)
        positionSet = 0

    # init problemDisplay here, every operation will have
    problemDisplay = ProblemDisplay(screen,WIDTH,HEIGHT,stateManager,program_OperationType)

    # set up problemGenerator here because it needs to know problemDisplay
    problemGenerator.setProblemDisplay(problemDisplay)
    problemGenerator.setOperationType(program_OperationType)

    # Checks whether a new problem needs to be created or just reset the current problem
    if problemGenerator.needsNewProblem == True:
        problemGenerator.getProblem()
        problemGenerator.needsNewProblem = False
    else:
        problemGenerator.resetCurrentProblem()

    # Creating division rectangles down here because we first need to know what the problem answer will be
    stateManager.cpuDenomAns = problemGenerator.problemDisplay.denominatorAnswer
    stateManager.cpuNumerAns = problemGenerator.problemDisplay.numeratorAnswer
    if program_OperationType == DIVISION:
        extraRect = False
        answerCeiling = math.ceil(problemGenerator.problemDisplay.numeratorAnswer/problemGenerator.problemDisplay.denominatorAnswer)
        fractionReciprocal = problemGenerator.problemDisplay.denominator2/problemGenerator.problemDisplay.numerator2
        if fractionReciprocal < answerCeiling:
            extraRect = True
        if extraRect is True:
                testRectangle = Rectangle((int)((WIDTH/4))-50,HEIGHT/2-30,280, 280,screen,drawablesController,True,mouse,stateManager, 1)
                cutter = testRectangle.getCutter() # need to get cutter here for draw call
                testRectangle2 = Rectangle((int)((WIDTH/4)*2),HEIGHT/2-30,280,280,screen,drawablesController,True,mouse,stateManager, 2)
                cutter2 = testRectangle2.getCutter() # need to get cutter here for draw call
                stateManager.hasThreeSquares = True
                # The third rectangle is created in stateManagerDiv when in moving state
        else:
                testRectangle = Rectangle((int)((WIDTH/3)),HEIGHT/2-30,280, 280,screen,drawablesController,True,mouse,stateManager, 1)
                cutter = testRectangle.getCutter() # need to get cutter here for draw call
                testRectangle2 = Rectangle((int)((WIDTH/3)*2),HEIGHT/2-30,280,280,screen,drawablesController,True,mouse,stateManager, 2)
                cutter2 = testRectangle2.getCutter() # need to get cutter here for draw call

    # bring in userAnswerSystem
    userAnswerSystem = UserAnswerSystem(screen, stateManager, WIDTH, HEIGHT,problemDisplay)

    isProgramRunning = True
    check = False
    click = False       # To check if Main Menu button is clicked
    keyDown = None # for passing information to userAnswerSystem
    # main loop
    while isProgramRunning:
        # main event loop -- user keyboard/mouse input here
        for event in pygame.event.get():
            if event.type == QUIT:
                isProgramRunning = False
                break
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    check = True
                    click = True
                    if mouse.isHeld == False:
                        mouse.setHeld(True)
                    else:
                        mouse.setHeld(False)
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    mouse.leftMouseReleasedThisFrame = True
                    check = False
                    #setClick(check)
                    click = False
                    #hold = False
            if event.type == KEYDOWN:
                if event.key == pygame.K_1:
                    keyDown = "1"
                elif event.key == pygame.K_2:
                    keyDown = "2"
                elif event.key == pygame.K_3:
                    keyDown = "3"
                elif event.key == pygame.K_4:
                    keyDown = "4"
                elif event.key == pygame.K_5:
                    keyDown = "5"
                elif event.key == pygame.K_6:
                    keyDown = "6"
                elif event.key == pygame.K_7:
                    keyDown = "7"
                elif event.key == pygame.K_8:
                    keyDown = "8"
                elif event.key == pygame.K_9:
                    keyDown = "9"
                elif event.key == pygame.K_0:
                    keyDown = "0"
                elif event.key == pygame.K_BACKSPACE:
                    keyDown = "Backspace"


        #---------UPDATE BEGIN-------UPDATE ALL OBJECTS
        mouse.update(check)
        if program_OperationType == MULTIPLICATION:
            stateManager.update(testRectangle.myCutter)
        elif program_OperationType == DIVISION:
            if (stateManager.cpuNumerAns/stateManager.cpuDenomAns) > 2:
                stateManager.update(testRectangle.myCutter, testRectangle2.myCutter)
            else:
                stateManager.update(testRectangle.myCutter, testRectangle2.myCutter)
        elif program_OperationType == SUBTRACTION:
            stateManager.update(testRectangle.myCutter, testRectangle2.myCutter)
            if TrashCan != None:
                trashCan.update()
        elif program_OperationType == ADDITION:
            stateManager.update(testRectangle.myCutter, testRectangle2.myCutter, testRectangle3.myCutter, testRectangle4.myCutter)
        
        for rect in drawablesController.rectangles:
            rect.update(mouse)
        for cm in drawablesController.cutmarkers:
            cm.update(mouse.isClick)
        if colorPicker != None:
            colorPicker.update()

        userAnswerSystem.update(mouse.leftMouseReleasedThisFrame,keyDown)

        if program_OperationType == DIVISION:
            if stateManager.hasThreeSquares is True:
                if positionSet == 0:
                    secondLeft, secondTop = stateManager.getSecondBorderPos()
                    positionSet = 1
                borderTop, borderLeft, numBoundaries = stateManager.getBorderPos()
                borderHeight = testRectangle2.height
                borderWidth = (testRectangle2.width/problemGenerator.problemDisplay.denominator2)*problemGenerator.problemDisplay.numerator2
            else:
                numBoundaries = 0
                borderTop, borderLeft, numBoundaries = stateManager.getBorderPos()
                borderHeight = testRectangle2.height
                borderWidth = (testRectangle2.width/problemGenerator.problemDisplay.denominator2)*problemGenerator.problemDisplay.numerator2
        elif program_OperationType == ADDITION:
            border1Top, border1Left = stateManager.border1Top, stateManager.border1Left
            borderHeight, borderWidth = testRectangle3.height, testRectangle3.width
            if stateManager.twoWholes is True:
                border2Top, border2Left = stateManager.border2Top, stateManager.border2Left
        elif program_OperationType == MULTIPLICATION:
            borderTop, borderLeft = stateManager.borderTop, stateManager.borderLeft
            borderHeight, borderWidth = testRectangle.height, testRectangle.width
        elif program_OperationType == SUBTRACTION:
            borderTop, borderLeft = stateManager.borderTop, stateManager.borderLeft
            borderHeight, borderWidth = testRectangle.height, testRectangle.width

        # ---------UPDATE END----------------------------------
        # ---------DRAW BEGIN--------------------------------
        # Menu button and logic to go back to main screen and get new problem
        menu_button = pygame.Rect(WIDTH-100, 0, 100, 50)
        if menu_button.collidepoint((mouse.mx, mouse.my)):
            if click:
                problemGenerator.needsNewProblem = True
                main_menu()
                isProgramRunning = False
                break

        restart_button = pygame.Rect(WIDTH-220, 0, 100, 50)
        if restart_button.collidepoint((mouse.mx, mouse.my)):
            if click:
                main_prog()
                isProgramRunning = False
                break
        
        newProblem_button = pygame.Rect(WIDTH - 370, 0 , 130, 50)
        if newProblem_button.collidepoint((mouse.mx, mouse.my)):
            if click:
                if problemGenerator.program_problemCreationType == problemGenerator.USERPROBLEM:
                    createUserProblem()
                problemGenerator.needsNewProblem = True
                main_prog()
                isProgramRunning = False
                break
        

        if program_OperationType == ADDITION:
            if stateManager.currentState == stateManager.CHECKCUTS or stateManager.currentState == stateManager.CHECKCUTS2 or stateManager.currentState == stateManager.CHECKCUTS3:
                undoCut_button = pygame.Rect(WIDTH/3-testRectangle.width+5, HEIGHT/3, 130, 50)
                undoCut_button2 = pygame.Rect(WIDTH/3-testRectangle.width+5, HEIGHT/3*2+100, 130, 50)
                undoCut_button3 = pygame.Rect(WIDTH/3*2-75, HEIGHT/3, 130, 50)
                undoCut_button4 = pygame.Rect(WIDTH/3*2-75, HEIGHT/3*2+175, 130, 50)
                if undoCut_button.collidepoint((mouse.mx, mouse.my)):
                    if click:
                        if stateManager.lastCuts == 0:
                            stateManager.undoCutsVert(1, cutter)
                        elif stateManager.lastCuts == 1:
                            stateManager.undoCutsHoriz(1, cutter)
                if undoCut_button2.collidepoint((mouse.mx, mouse.my)):
                    if click:
                        if stateManager.lastCuts == 0:
                            stateManager.undoCutsVert(2, cutter2)
                        elif stateManager.lastCuts == 1:
                            stateManager.undoCutsHoriz(2, cutter2)
                if undoCut_button3.collidepoint((mouse.mx, mouse.my)):
                    if click:
                        if stateManager.lastCuts == 2:
                            stateManager.undoCutsVert(3, cutter3)
                        elif stateManager.lastCuts == 3:
                            stateManager.undoCutsHoriz(3, cutter3)
                if undoCut_button4.collidepoint((mouse.mx, mouse.my)):
                    if click:
                        if stateManager.lastCuts == 4:
                            stateManager.undoCutsVert(4, cutter4)
                        elif stateManager.lastCuts == 5:
                            stateManager.undoCutsHoriz(4, cutter4)

        elif program_OperationType == DIVISION:
            if stateManager.currentState == stateManager.CHECKCUTS:
                if stateManager.hasThreeSquares:
                    undoCut_button = pygame.Rect(WIDTH/5 - 55, HEIGHT/2 + testRectangle.height/2 - 30 , 130, 50)
                    undoCut_button2 = pygame.Rect(WIDTH/2-65, HEIGHT/2 + testRectangle.height/2 - 30 , 130, 50)
                else:
                    undoCut_button = pygame.Rect(WIDTH/3 - 60, HEIGHT/2 + testRectangle.height/2 - 30 , 130, 50)
                    undoCut_button2 = pygame.Rect(WIDTH/3*2 - 65, (HEIGHT/2 + testRectangle.height/2)-30, 130, 50)
                if undoCut_button.collidepoint((mouse.mx, mouse.my)):
                    if click:
                            if stateManager.lastCuts == 0:
                                stateManager.undoCutsVert(1, cutter)
                            else:
                                stateManager.undoCutsHoriz(1, cutter)
                if undoCut_button2.collidepoint((mouse.mx, mouse.my)):
                    if click:
                            if stateManager.lastCuts == 0:
                                stateManager.undoCutsVert(2, cutter2)
                            else:
                                stateManager.undoCutsHoriz(2, cutter2)
    
        elif program_OperationType == SUBTRACTION:
            if stateManager.currentState == stateManager.CHECKCUTS:
                undoCut_button = pygame.Rect(WIDTH/3 - 65, (HEIGHT/2 + testRectangle.height/2)-30 , 130, 50)
                undoCut_button2 = pygame.Rect(WIDTH/3*2 - 65, (HEIGHT/2 + testRectangle.height/2)-30, 130, 50)
                if undoCut_button.collidepoint((mouse.mx, mouse.my)):
                    if click:
                            if stateManager.lastCuts == 0:
                                stateManager.undoCutsVert(1, cutter)
                            else:
                                stateManager.undoCutsHoriz(1, cutter)
                if undoCut_button2.collidepoint((mouse.mx, mouse.my)):
                    if click:
                            if stateManager.lastCuts == 0:
                                stateManager.undoCutsVert(2, cutter2)
                            else:
                                stateManager.undoCutsHoriz(2, cutter2)
        elif program_OperationType == MULTIPLICATION:
            if stateManager.currentState == stateManager.CHECKCUTS:
                undoCut_button = pygame.Rect(WIDTH/4, HEIGHT/2, 130, 50)
                if undoCut_button.collidepoint((mouse.mx, mouse.my)):
                    if click:
                        if stateManager.lastCuts == 0:
                            stateManager.undoCutsVert(cutter)
                        else:
                            stateManager.undoCutsHoriz(cutter)

        # drawing here
        screen.fill(colors.BGCOLOR) #fill screen bg   


        # Drawing menu button
        pygame.draw.rect(screen, (8, 41, 255), menu_button)
        draw_text('Main Menu', button_font, (0,0,0), screen, WIDTH-50, 25)
        pygame.draw.rect(screen, (8, 41, 255), restart_button)
        draw_text('Restart', button_font, (0,0,0), screen, WIDTH-170, 25)
        pygame.draw.rect(screen, (8, 41, 255), newProblem_button) # for new prob button
        draw_text('New Problem', button_font, (0,0,0), screen, WIDTH-305, 25) # for new prob button


        # ALL LOGIC FOR DRAWING UNDO BUTTONS HERE
        if program_OperationType == ADDITION:
            if stateManager.currentState == stateManager.CHECKCUTS:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button)
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button2)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3 - testRectangle.width/1.5-20, (HEIGHT/3)+25)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3 - testRectangle.width/1.5-20, (HEIGHT/3)*2+125)
            elif stateManager.currentState == stateManager.CHECKCUTS2:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button3)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3*2-10, (HEIGHT/3)+25)
            elif stateManager.currentState == stateManager.CHECKCUTS3:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button4)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3*2-10, (HEIGHT/3)*2+200)

        elif program_OperationType == DIVISION:
            if stateManager.currentState == stateManager.CHECKCUTS:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button)
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button2)

                if stateManager.hasThreeSquares is True:
                    draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/4-55, (HEIGHT/2)+(testRectangle.height/2))
                    draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/4*2, (HEIGHT/2)+(testRectangle.height/2))
                else:
                    draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3, (HEIGHT/2)+(testRectangle.height/2))
                    draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3*2, (HEIGHT/2)+(testRectangle.height/2))
        elif program_OperationType == SUBTRACTION:
            
            if stateManager.currentState == stateManager.CHECKCUTS:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3, (HEIGHT/2)+(testRectangle.height/2)-5)
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button2)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/3*2, (HEIGHT/2)+(testRectangle.height/2)-5)
        else:
            if stateManager.currentState == stateManager.CHECKCUTS:
                pygame.draw.rect(screen, (8, 41, 255), undoCut_button)
                draw_text('Undo Cut', button_font, (0,0,0), screen, WIDTH/4 + 65, (HEIGHT/2)+25)

        if stateManager.getCurrentState() != "Finished":
            state_message = "Current state: " + stateManager.getCurrentState()
        else:
            state_message = ""
        draw_textLeftToRight(state_message, button_font, (0,0,0), screen, 15, 15)

        tempRectList = list()
        for bgS in drawablesController.bgSquares:
            bgS.draw()
        if program_OperationType == MULTIPLICATION:
            for rect in drawablesController.rectangles:
                rect.draw()
        if program_OperationType == SUBTRACTION:
            for rect in drawablesController.rectangles:
                rect.draw()
                if rect.isMarked == True:
                    rect.drawMark()
        if program_OperationType != MULTIPLICATION and program_OperationType != SUBTRACTION:
            for rect in drawablesController.rectangles:
                #move to rectangle class
                if rect.ownerID == 2:
                    rect.draw()
                    if rect.isShadedB:
                        rect.drawBLines(rect.colorHatch)
                else:
                    tempRectList.append(rect)
            for trect in tempRectList:
                trect.draw()
                if trect.isShadedV == True and trect.isShadedH != True:
                    trect.drawVLines(trect.colorHatch)
                if trect.isShadedH == True and trect.isShadedV != True:
                    trect.drawHLines(trect.colorHatch)
                if trect.isShadedB:
                    trect.drawBLines(trect.colorHatch)
        for gl in drawablesController.guidelines:
            gl.draw()
        for cm in drawablesController.cutmarkers:
            cm.draw()
        
        cutter.draw()
        if program_OperationType == DIVISION or program_OperationType == SUBTRACTION:
            cutter2.draw()
            if stateManager.cpuNumerAns > stateManager.cpuDenomAns:
                pass
        if program_OperationType == ADDITION:
            cutter2.draw()
            cutter3.draw()
            cutter4.draw()
        stateManager.draw()
        if colorPicker != None:
            colorPicker.draw()
        problemDisplay.draw()
        userAnswerSystem.draw()
        # DRAW BORDER HERE TO HIGHLIGHT CURRENT SECTION
        if program_OperationType == DIVISION:
            if stateManager.hasThreeSquares is True:
                if stateManager.currentState == stateManager.MOVING or stateManager.currentState == stateManager.ANSWERSUBMISSION or stateManager.currentState == stateManager.DONE:
                    pygame.draw.rect(screen, colors.GOLD, (borderLeft, borderTop, borderWidth, borderHeight), 4)  # width = 4
                    pygame.draw.rect(screen, colors.GOLD, (secondLeft, secondTop, borderWidth, borderHeight), 4)  # width = 4

            else:
                if stateManager.currentState == stateManager.MOVING or stateManager.currentState == stateManager.ANSWERSUBMISSION or stateManager.currentState == stateManager.DONE:
                    numBoundaries += 1
                    for i in range(numBoundaries):
                        if i < stateManager.answerCeiling:
                            pygame.draw.rect(screen, colors.GOLD, (borderLeft-((i)*borderWidth), borderTop, borderWidth, borderHeight), 4)  # width = 4
        elif program_OperationType == ADDITION:
            if stateManager.currentState == stateManager.MOVING or stateManager.currentState == stateManager.ANSWERSUBMISSION or stateManager.currentState == stateManager.DONE or stateManager.currentState == stateManager.CUTTINGHORIZONTALLY3 or stateManager.currentState == stateManager.CUTTINGVERTICALLY3 or stateManager.currentState == stateManager.CHECKCUTS3:
                pygame.draw.rect(screen, colors.GOLD, (border1Left, border1Top, borderWidth, borderHeight), 4)
                if stateManager.twoWholes is True:
                    pygame.draw.rect(screen, colors.GOLD, (border2Left, border2Top, borderWidth, borderHeight), 4)
        elif program_OperationType == MULTIPLICATION:
            if stateManager.currentState == stateManager.ANSWERSUBMISSION or stateManager.currentState == stateManager.DONE:
                pygame.draw.rect(screen, colors.GOLD, (borderLeft, borderTop, borderWidth, borderHeight), 4)
        elif program_OperationType == SUBTRACTION:
            if stateManager.currentState == stateManager.ANSWERSUBMISSION or stateManager.currentState == stateManager.DONE:
                pygame.draw.rect(screen, colors.GOLD, (borderLeft, borderTop, borderWidth, borderHeight), 4)
            
        if mouse.whoisHeld != None:
            mouse.whoisHeld.draw()

        #-----------------------------DRAW END---------------------------------------
        mouse.leftMouseReleasedThisFrame = False
        keyDown = None
        #update screen and set framerate
        pygame.display.flip()
        clock.tick(fps)

    #end of main loop
    pygame.quit()
Exemple #14
0
 def getColor(self):
     self.color_picker = ColorPicker()
     self.picked_color = self.color_picker.getColor()
     self.picked_color = tuple([int(x) for x in self.picked_color])
     self.borderStylesheet()
Exemple #15
0
class Elicit:
    def save(self):
        old_filename = self.palette.filename
        self.palette.save()
        if old_filename == None:
            self.gconf.set_string("/apps/elicit/palette", os.path.basename(self.palette.filename))

    def quit(self, widget=None, data=None):
        self.save()
        gtk.main_quit()

    def main(self):
        gtk.main()

    def show(self):
        self.win.show_all()

    def hide(self):
        self.win.hide()

    def grab(self, x, y, w, h):
        self.mag.grab(x, y, w, h)

    def mag_grid_toggled(self, mag):
        self.grid_check.set_active(mag.show_grid)

    def mag_zoom_changed(self, mag):
        self.gconf.set_int("/apps/elicit/zoom_level", mag.zoom)

    def mag_measure_changed(self, mag):
        if mag.measure_rect:
            text = "[%dx%d] (%.1f diag) " % (
                mag.measure_rect.width,
                mag.measure_rect.height,
                math.sqrt(mag.measure_rect.width ** 2 + mag.measure_rect.height ** 2),
            )
        else:
            text = ""

        self.measure_label.set_text(text)

    def mag_location_changed(self, mag):
        if mag.screen_rect:
            text = "  (%d,%d) %dx%d" % (
                mag.screen_rect.x,
                mag.screen_rect.y,
                mag.screen_rect.width,
                mag.screen_rect.height,
            )
        else:
            text = ""

        self.mag_label.set_text(text)

    def grid_check_toggled(self, check):
        self.gconf.set_bool("/apps/elicit/show_grid", check.get_active())

    def zoom_spin_value_changed(self, spin):
        self.gconf.set_int("/apps/elicit/zoom_level", int(spin.get_value()))

    def picker_save_color(self, picker):
        c = Color()
        c.set_rgb(*picker.color.rgb())
        self.palette.append(c)
        self.palette_view.select(c)

    def palette_view_select_color(self, palette_view, color):
        if color == None:
            self.color_name_entry.set_text("")
            self.color_name_entry.set_sensitive(False)
        else:
            self.gconf.set_string("/apps/elicit/color", color.hex())
            self.color_name_entry.set_text(color.name)
            self.color_name_entry.set_sensitive(True)

    def palette_view_delete_color(self, palette_view, color):
        self.palette.remove(color)

    def wheel_changed(self, wheel):
        self.wheel.was_adjusting = self.wheel.is_adjusting()
        h, s, v = wheel.get_color()
        h = h * 360.0
        # I need Color to emit 'changed' even when it is not changed
        # because otherwise the wheel doesn't set the color when the user
        # stops moving the cursor. Yeah, hackish.
        self.color.set_hsv(h, s, v, do_emit=True)

    def color_name_entry_changed(self, color_name_entry):
        if self.palette and self.palette_view.selected:
            self.palette_view.selected.name = color_name_entry.get_text()

    def color_changed(self, color):

        # TODO: FIXME  I think there is a bug in here
        for type in "r", "g", "b", "h", "s", "v", "c", "m", "y", "k":
            self.colorspin[type].handler_block(self.h_ids[type])
        self.hex_entry.handler_block(self.h_ids["hex"])
        self.wheel.handler_block(self.h_ids["wheel"])
        # self.name_combobox.handler_block(self.h_ids['name'])

        self.colorspin["r"].set_value(self.color.r)
        self.colorspin["g"].set_value(self.color.g)
        self.colorspin["b"].set_value(self.color.b)

        self.colorspin["h"].set_value(self.color.h)
        self.colorspin["s"].set_value(self.color.s)
        self.colorspin["v"].set_value(self.color.v)

        self.colorspin["c"].set_value(self.color.c)
        self.colorspin["m"].set_value(self.color.m)
        self.colorspin["y"].set_value(self.color.y)
        self.colorspin["k"].set_value(self.color.k)

        self.hex_entry.set_text(self.color.hex())
        if not self.wheel.was_adjusting:
            self.name_palette.closest(self.color.r, self.color.g, self.color.b)

        h, s, v = color.hsv()
        self.wheel.set_color(h / 360.0, s, v)

        if self.palette_view.selected and color.hex() != self.palette_view.selected.hex():
            self.palette_view.select(None)

        for type in "r", "g", "b", "h", "s", "v", "c", "m", "y", "k":
            self.colorspin[type].handler_unblock(self.h_ids[type])
        self.hex_entry.handler_unblock(self.h_ids["hex"])
        self.wheel.handler_unblock(self.h_ids["wheel"])
        # self.name_combobox.handler_unblock(self.h_ids['name'])

    def color_spin_rgb_changed(self, spin):
        r, g, b = self.color.rgb()
        if spin == self.colorspin["r"]:
            r = spin.get_value()
        elif spin == self.colorspin["g"]:
            g = spin.get_value()
        elif spin == self.colorspin["b"]:
            b = spin.get_value()
        self.color.set_rgb(r, g, b)

    def color_spin_cmyk_changed(self, spin):
        c, m, y, k = self.color.cmyk()
        if spin == self.colorspin["c"]:
            c = spin.get_value()
        elif spin == self.colorspin["m"]:
            m = spin.get_value()
        elif spin == self.colorspin["y"]:
            y = spin.get_value()
        elif spin == self.colorspin["k"]:
            k = spin.get_value()
        self.color.set_cmyk(c, m, y, k)

    def color_spin_hsv_changed(self, spin):
        h, s, v = self.color.hsv()
        if spin == self.colorspin["h"]:
            h = spin.get_value()
        elif spin == self.colorspin["s"]:
            s = spin.get_value()
        elif spin == self.colorspin["v"]:
            v = spin.get_value()
        self.color.set_hsv(h, s, v)

    def name_combobox_changed(self, name_combobox):
        i = name_combobox.get_active()
        color = name_combobox.get_model()[i][0]
        self.color.set_hex(color)

    def hex_entry_changed(self, entry):
        text = entry.get_text()
        if text != "":
            if (text[0] == "#" and len(text) == 7) or (text[0] != "#" and len(text) == 6):
                self.color.set_hex(text)

    def palette_combo_selected(self, combo, palette):
        if self.palette != palette:
            if palette.filename:
                self.gconf.set_string("/apps/elicit/palette", os.path.basename(palette.filename))
            if self.palette:
                old_filename = self.palette.filename
                self.palette.save()

                # update palette list with new filename
                if old_filename != self.palette.filename:
                    index = self.palette_list.index_of_palette(self.palette)
                    if index != None:
                        self.palette_list[index][1] = self.palette.filename

            self.palette = palette
            self.palette_view.set_palette(self.palette)
            self.color_name_entry.set_sensitive(False)

    def add_palette(self, button):
        p = Palette()
        p.name = "Untitled Palette"
        self.palette_list.append(p)
        self.palette_combo.select(self.palette_list.index_of_palette(p))

    def delete_palette(self, button):
        if not self.palette:
            return

        d = gtk.MessageDialog(self.win, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL, None)

        d.set_markup(
            "Are you sure you want to delete the palette <b>%s</b>? This cannot be undone." % self.palette.name
        )
        response = d.run()
        d.destroy()
        if response == gtk.RESPONSE_OK:
            p = self.palette
            self.palette_combo.remove(self.palette_list.index_of_palette(p))
            p.delete()

    def select_color_clicked(self, button):
        sel_action = self.actiongroup.get_action("Select Color")
        sel_action.activate()

    def magnify_clicked(self, button):
        mag_action = self.actiongroup.get_action("Magnify")
        mag_action.activate()

    def build_menu(self):
        uimanager = gtk.UIManager()
        accelgroup = uimanager.get_accel_group()
        self.accelgroup = accelgroup
        self.win.add_accel_group(accelgroup)

        actiongroup = gtk.ActionGroup("ElicitActions")
        self.actiongroup = actiongroup

        actiongroup.add_actions(
            [
                ("Quit", gtk.STOCK_QUIT, "_Quit", "<Ctrl>q", "Quit Elicit", self.action_quit),
                ("Save", gtk.STOCK_QUIT, "_Save Palette", "<Ctrl>s", "Save Palette", self.action_save),
                ("About", gtk.STOCK_ABOUT, "_About", None, "About Elicit", self.action_about),
                ("Magnify", gtk.STOCK_ABOUT, "_Magnify", "<Ctrl>z", "Start Magnifying", self.action_magnify),
                (
                    "Select Color",
                    gtk.STOCK_ABOUT,
                    "Select _Color",
                    "<Ctrl>d",
                    "Start Selecting Color",
                    self.action_pick_color,
                ),
                ("File", None, "_File"),
                ("Action", None, "_Action"),
                ("Help", None, "_Help"),
            ]
        )

        uimanager.insert_action_group(actiongroup)
        uimanager.add_ui_from_string(
            """
    <ui>
      <menubar name="ElicitMain">
        <menu action="File">
          <menuitem action="Save"/>
          <menuitem action="Quit"/>
        </menu>
        <menu action="Action">
          <menuitem action="Magnify"/>
          <menuitem action="Select Color"/>
        </menu>
        <menu action="Help">
          <menuitem action="About"/>
        </menu>
      </menubar>
    </ui>
    """
        )
        menubar = uimanager.get_widget("/ElicitMain")
        return menubar

    def build_gui(self):
        self.win = gtk.Window()
        self.win.set_title("Elicit")
        self.win.set_icon_name("rephorm-elicit")
        self.win.connect("destroy", self.quit, None)

        main_vbox = gtk.VBox(False, 2)

        menubar = self.build_menu()
        w_vbox = gtk.VBox()
        w_vbox.pack_start(menubar, False)
        w_vbox.pack_end(main_vbox, True)
        # main_vbox.pack_start(menubar, False)
        main_vbox.set_border_width(7)
        self.win.add(w_vbox)

        frame_mag = gtk.Frame()
        frame_mag.set_shadow_type(gtk.SHADOW_NONE)

        frame_mag_inner = gtk.Frame()
        frame_mag_inner.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.mag = Magnifier()
        frame_mag_inner.add(self.mag)
        mag_vbox = gtk.VBox()
        mag_vbox.pack_start(frame_mag_inner)
        frame_mag.add(mag_vbox)
        self.mag.connect("zoom-changed", self.mag_zoom_changed)
        self.mag.connect("grid-toggled", self.mag_grid_toggled)
        self.mag.connect("measure-changed", self.mag_measure_changed)
        self.mag.connect("location-changed", self.mag_location_changed)

        hbox = gtk.HBox(False, 0)

        self.mag_label = gtk.Label()
        hbox.pack_start(self.mag_label, False)

        icon_path = os.path.join(os.path.dirname(__file__), "data", "icons")

        frame_wheel = gtk.Frame()
        frame_wheel.set_shadow_type(gtk.SHADOW_NONE)
        self.notebook = gtk.Notebook()
        frame_mag_label = gtk.Image()
        frame_mag_label.set_from_file(os.path.join(icon_path, "magnify-16.png"))
        frame_wheel_label = gtk.Image()
        frame_wheel_label.set_from_file(os.path.join(icon_path, "color-wheel-16.png"))
        frame_wheel.connect("size-allocate", self.wheel_size_allocate)
        frame_wheel.connect("size-request", self.wheel_size_request)
        self.notebook.append_page(frame_mag, frame_mag_label)
        self.notebook.append_page(frame_wheel, frame_wheel_label)

        # TODO: do not hardcode tha palette path!
        # self.name_palette = NamePalette('../ntc.txt', self.color)
        self.name_palette = NamePalette("/etc/X11/rgb.txt", self.color)
        self.name_treeview = ColorName(self.name_palette)
        # self.h_ids['name'] = self.name_combobox.connect('changed', self.name_combobox_changed)
        # name_hbox.pack_start(self.name_combobox, True, True, 2)

        frame_name_palette = gtk.Frame()
        frame_name_palette_label = gtk.Image()
        frame_name_palette_label.set_from_file(os.path.join(icon_path, "palette-16.png"))
        self.notebook.append_page(frame_name_palette, frame_name_palette_label)
        name_scroll = gtk.ScrolledWindow()
        name_scroll.add(self.name_treeview)
        frame_name_palette.add(name_scroll)

        self.wheel = gtk.HSV()
        self.wheel.was_adjusting = False
        frame_wheel.add(self.wheel)
        self.h_ids["wheel"] = self.wheel.connect("changed", self.wheel_changed)

        main_vbox.pack_start(self.notebook, True, True)
        mag_vbox.pack_start(hbox, False)
        main_vbox.set_spacing(5)

        pick_view_hbox = gtk.HBox()
        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(icon_path, "dropper-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
        button.connect("clicked", self.select_color_clicked)
        pick_view_hbox.pack_start(button, False)
        main_vbox.pack_start(pick_view_hbox)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(icon_path, "magnify-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
        button.connect("clicked", self.magnify_clicked)
        hbox.pack_end(button, False)

        self.measure_label = gtk.Label()
        hbox.pack_end(self.measure_label, False)

        hbox = gtk.HBox(False, 5)
        mag_vbox.pack_start(hbox, False)

        check = gtk.CheckButton("Show Grid")
        check.set_active(self.mag.show_grid)
        check.connect("toggled", self.grid_check_toggled)
        hbox.pack_start(check)
        self.grid_check = check

        spin = gtk.SpinButton()
        spin.set_range(1, 50)
        spin.set_increments(1, 10)
        spin.set_value(self.mag.zoom)
        spin.connect("value-changed", self.zoom_spin_value_changed)
        hbox.pack_end(spin, False)
        self.zoom_spin = spin

        zoom_label = gtk.Label("Zoom:")
        hbox.pack_end(zoom_label, False)

        vbox = gtk.VBox(False, 5)
        main_vbox.pack_start(vbox, False)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        pick_view_hbox.pack_end(frame, True, True)

        self.colorpicker = ColorPicker()
        frame.add(self.colorpicker)
        self.colorpicker.connect("save-color", self.picker_save_color)
        self.colorpicker.set_magnifier(self.mag)
        self.name_palette.connect("colorname-changed", self.colorpicker.colorname_changed)

        self.colorspin = {}
        # add RGB spinboxes
        table = gtk.Table(6, 4)
        vbox.pack_start(table, True)

        row = 0
        for type in ("r", "g", "b"):
            label = gtk.Label(type.upper())
            table.attach(label, 0, 1, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 255)
            spin.set_increments(1, 10)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_rgb_changed)
            table.attach(spin, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("h", "s", "v"):
            label = gtk.Label(type.upper())
            table.attach(label, 2, 3, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            if type == "h":
                spin.set_range(0, 360)
                spin.set_increments(1, 10)
            else:
                spin.set_digits(2)
                spin.set_range(0, 1.0)
                spin.set_increments(0.01, 0.1)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_hsv_changed)
            table.attach(spin, 3, 4, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("c", "m", "y", "k"):
            label = gtk.Label(type.upper())
            table.attach(label, 4, 5, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 100)
            spin.set_increments(1, 10)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_cmyk_changed)
            table.attach(spin, 5, 6, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        self.hex_label = gtk.Label("Hex")
        table.attach(self.hex_label, 0, 1, 3, 4, 0, 0, 2, 2)

        self.hex_entry = gtk.Entry()
        self.hex_entry.set_max_length(7)
        self.hex_entry.set_width_chars(7)
        table.attach(self.hex_entry, 1, 2, 3, 4, gtk.FILL | gtk.EXPAND, 0, 2, 2)
        self.h_ids["hex"] = self.hex_entry.connect("changed", self.hex_entry_changed)

        name_hbox = gtk.HBox()
        self.name_label = ColorLabel()
        self.name_palette.connect("colorname-changed", self.name_label.colorname_changed)
        name_hbox.pack_end(self.name_label, False, False, 2)
        vbox.pack_start(name_hbox)
        vbox.reorder_child(name_hbox, 0)

        sep = gtk.HSeparator()
        main_vbox.pack_start(sep, False)

        # palette tools
        hbox = gtk.HBox(False, 5)
        main_vbox.pack_start(hbox, False)

        # Palette tools
        hbox.pack_start(gtk.Label("Palette:"), False)

        self.palette_combo = PaletteCombo()
        hbox.pack_start(self.palette_combo)
        self.palette_combo.connect("selected", self.palette_combo_selected)

        button = gtk.Button()
        button.set_image(gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Add Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect("clicked", self.add_palette)
        hbox.pack_start(button, False)

        button = gtk.Button()
        button.set_image(gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Delete Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect("clicked", self.delete_palette)
        hbox.pack_start(button, False)

        # palette view
        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        main_vbox.pack_start(frame, False)

        self.palette_view = PaletteView()
        self.palette_view.connect("select-color", self.palette_view_select_color)
        self.palette_view.connect("delete-color", self.palette_view_delete_color)
        frame.add(self.palette_view)

        # color name entry / palette tools
        hbox = gtk.HBox(False, 5)
        main_vbox.pack_start(hbox, False)

        hbox.pack_start(gtk.Label("Color Name:"), False)

        self.color_name_entry = gtk.Entry()
        self.color_name_entry.set_sensitive(False)
        self.color_name_entry.connect("changed", self.color_name_entry_changed)
        hbox.pack_start(self.color_name_entry, True, True)

    def init_config(self):
        self.gconf = gconf.client_get_default()
        self.gconf.add_dir("/apps/elicit", preload=True)
        self.gconf_id = self.gconf.notify_add("/apps/elicit", self.config_changed)

    def load_config(self):
        color = self.gconf.get_string("/apps/elicit/color")
        if color:
            self.color.set_hex(color)

        zoom_level = self.gconf.get_int("/apps/elicit/zoom_level")
        self.mag.set_zoom(zoom_level)
        self.zoom_spin.set_value(self.mag.zoom)

        grab_rate = self.gconf.get_int("/apps/elicit/grab_rate")
        if grab_rate > 0:
            self.mag.grab_rate = grab_rate

        show_grid = self.gconf.get_bool("/apps/elicit/show_grid")
        self.mag.set_show_grid(show_grid)
        self.grid_check.set_active(self.mag.show_grid)

        palette = self.gconf.get_string("/apps/elicit/palette")
        if not palette:
            palette = "default.gpl"
        index = self.palette_list.index_of_file(palette)
        if index == None:
            index = 0
        self.palette_combo.select(index)

    def wheel_size_allocate(self, frame, allocation):
        style = frame.get_style()
        focus_width = frame.style_get_property("focus-line-width")
        focus_padding = frame.style_get_property("focus-padding")
        size = (
            min(allocation.width, allocation.height)
            - 2 * max(style.xthickness, style.ythickness)
            - 2 * (focus_width + focus_padding)
        )

        self.wheel.set_metrics(int(size), int(size / 10))

    def wheel_size_request(self, frame, requisition):
        focus_width = frame.style_get_property("focus-line-width")
        focus_padding = frame.style_get_property("focus-padding")
        requisition.width = 2 * (focus_width + focus_padding)
        requisition.height = 2 * (focus_width + focus_padding)

    def config_changed(self, client, gconf_id, entry, user_data):
        key = entry.key[13:]

        if key == "color":
            hex = entry.value.get_string()
            self.color.set_hex(hex)
        elif key == "zoom_level":
            self.mag.set_zoom(entry.value.get_int())
            self.zoom_spin.set_value(self.mag.zoom)
        elif key == "show_grid":
            self.mag.set_show_grid(entry.value.get_bool())
            self.grid_check.set_active(self.mag.show_grid)
        elif key == "palette":
            palette = entry.value.get_string()
            if not palette:
                palette = "default.gpl"
            self.palette_combo.select(self.palette_list.index_of_file(palette))
        elif key == "grab_rate":
            self.mag.set_grab_rate(entry.value.get_int())

    def action_quit(self, action):
        self.quit()

    def action_save(self, action):
        self.save()

    def action_about(self, action):
        a = gtk.AboutDialog()
        a.set_name(appinfo.name)
        a.set_version(appinfo.version)
        a.set_website(appinfo.website)
        a.set_authors([appinfo.author])
        a.set_logo_icon_name("rephorm-elicit")

        a.connect("response", lambda dialog, respons: dialog.destroy())
        a.show()

    def action_magnify(self, action):
        if self.mag.grabbing:
            self.mag.grab_stop()

        if self.colorpicker.picking:
            self.colorpicker.pick_stop()

        self.mag.grab_start()

    def action_pick_color(self, action):
        if self.colorpicker.picking:
            self.colorpicker.pick_stop()

        if self.mag.grabbing:
            self.mag.grab_stop()

        self.colorpicker.pick_start()

    def __init__(self):
        self.palette = None
        self.color = Color()
        self.h_ids = {}
        self.color.connect("changed", self.color_changed)

        self.init_config()
        self.build_gui()

        self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), "palettes")
        Palette.PaletteDir = self.palette_dir

        self.palette_list = PaletteList()
        self.palette_list.load(self.palette_dir)
        self.palette_combo.set_model(self.palette_list)

        # no palettes, so create default
        if len(self.palette_list) == 0:
            palette = Palette()
            palette.name = "Default Palette"
            palette.filename = os.path.join(self.palette_dir, "default.gpl")
            self.palette_list.append(palette)

            self.palette_combo.select(0)

        self.colorpicker.set_color(self.color)

        self.load_config()
Exemple #16
0
class ColorPalette(QWidget):
    """Represents a palette of colors

    :param source:  Subject source of the palette, either sprite or tile
    :type source:   Source
    :param parent:  Parent widget, defaults to None
    :type parent:   QWidget, optional
    """

    palette_updated = pyqtSignal(str)
    color_selected = pyqtSignal(int)

    def __init__(self, source, parent=None):
        super().__init__(parent)
        self.source = source
        self.grid = QGridLayout()
        self.grid.setSpacing(0)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.picker = ColorPicker(self)
        self.color_preview = ColorPreview(self.source, self)
        self.color_preview.switch.connect(self.switchColors)
        self.palette = [Color(n, self.source, self) for n in range(16)]
        positions = [(row, col) for row in range(4) for col in range(4)]
        for position, swatch in zip(positions, self.palette):
            swatch.color_selected.connect(self.selectColor)
            swatch.edit.connect(self.openPicker)
            self.grid.addWidget(swatch, *position)
        self.enabled = False
        self.main_layout = QHBoxLayout()
        self.main_layout.addLayout(self.grid)
        self.main_layout.addWidget(self.color_preview)
        self.main_layout.setContentsMargins(0, 0, 5, 0)
        self.main_layout.setSpacing(19)
        self.setLayout(self.main_layout)

    def setup(self, data):
        """Sets up the data source for the palette and initial selection

        :param data:    Data source of palette
        :type data:     GameData
        """
        self.data = data
        self.data.col_pal_updated.connect(self.setPalette)
        self.palette[0].select()

    @pyqtSlot(int, QColor)
    def openPicker(self, index, orig_color):
        """Handles opening the color picker after double-clicking on a color

        :param index:       Index of the color selected
        :type index:        int
        :param orig_color:  Original color of the selection color
        :type orig_color:   QColor
        """
        self.picker.setColor(orig_color)
        self.picker.preview_color.connect(
            lambda orig_color: self.previewColor(index, orig_color)
        )
        if self.picker.exec():
            new_color = self.picker.getColor()
            self.sendColorUpdate(index, new_color, orig_color)
        else:
            self.previewColor(index, orig_color)
        self.picker.preview_color.disconnect()

    @pyqtSlot(int, QColor)
    def sendColorUpdate(self, index, new_color, orig_color=None):
        """Sends color update to centralized GameData data

        :param index:       Index of changed color in palette
        :type index:        int
        :param new_color:   Color to be changed to
        :type new_color:    QColor
        :param orig_color:  Original color, defaults to None
        :type orig_color:   QColor, optional
        """
        self.data.setColor(
            self.current_palette, index, new_color, self.source, orig_color
        )

    @pyqtSlot(QColor)
    def previewColor(self, index, color):
        """Triggers preview of color throughout application when interacting
        with color picker

        :param index:   Index of the color being changed
        :type index:    int
        :param color:   Color to be previewed
        :type color:    QColor
        """
        self.data.previewColor(self.current_palette, index, color, self.source)

    @pyqtSlot(Source, str)
    def setPalette(self, source, palette):
        """Sets the overall color palette colors

        :param source:  Subject source of color palette, either sprite or tile
        :type source:   Source
        :param palette: Name of the color palette to be set to
        :type palette:  str
        """
        if source is not self.source:
            return
        self.current_palette = palette
        widgets = [
            self.grid.itemAt(index) for index in range(self.grid.count())
        ]
        for color, widget in zip(
            self.data.getColPal(self.current_palette, self.source), widgets
        ):
            widget.widget().fill(color)
            index = widgets.index(widget)
            if index == self.color_preview.primary_index:
                self.color_preview.setPrimaryColor(
                    color
                    if (index != 0 or self.source is Source.TILE)
                    else QColor(Qt.magenta)
                )
            if index == self.color_preview.secondary_index:
                self.color_preview.setSecondaryColor(
                    color
                    if (index != 0 or self.source is Source.TILE)
                    else QColor(Qt.magenta)
                )
        if self.source is Source.SPRITE:
            self.grid.itemAt(0).widget().fill(QColor(Qt.magenta))
        self.palette_updated.emit(self.current_palette)

    @pyqtSlot()
    def switchColors(self):
        """Switches the active color between the primary and secondary colors
        """
        pindex = self.color_preview.primary_index
        pcolor = self.color_preview.primary_color
        sindex = self.color_preview.secondary_index
        scolor = self.color_preview.secondary_color
        self.selectColor(sindex, scolor, Qt.LeftButton)
        self.selectColor(pindex, pcolor, Qt.RightButton)

    @pyqtSlot(int, QColor, Qt.MouseButton)
    def selectColor(self, index, color, button):
        """Selects a primary or secondary color from the palette

        :param index:   Index of the chosen color
        :type index:    int
        :param color:   Color chosen
        :type color:    QColor
        :param button:  Which mouse button was used to select the primary or
                        secondary color
        :type button:   Qt.MouseButton
        """
        if button == Qt.LeftButton:
            self.color_preview.setPrimaryColor(color)
            self.color_preview.setPrimaryIndex(index)
            for idx in range(self.grid.count()):
                if idx != index:
                    self.grid.itemAt(idx).widget().deselect()
                else:
                    self.grid.itemAt(idx).widget().select()
            self.color_selected.emit(index)
        elif button == Qt.RightButton:
            self.color_preview.setSecondaryColor(color)
            self.color_preview.setSecondaryIndex(index)
Exemple #17
0
class UI_MainWindow(QMainWindow):
    def __init__(self):
        super(UI_MainWindow, self).__init__()
        self.currentShow = ""
        self.picked_color = (255, 255, 255)
        self.setupUi(self)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(656, 820)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.app = QApplication([])

        self.dialog = QFileDialog()

        self.saveButton = QtWidgets.QPushButton(self.centralwidget)
        self.saveButton.setGeometry(QtCore.QRect(120, 700, 131, 41))
        self.saveButton.setObjectName("saveButton")
        self.saveButton.clicked.connect(lambda: self.save())

        self.newButton = QtWidgets.QPushButton(self.centralwidget)
        self.newButton.setGeometry(QtCore.QRect(410, 700, 131, 41))
        self.newButton.setObjectName("newButton")
        self.newButton.clicked.connect(lambda: self.resetScreen())

        self.title = QtWidgets.QTextBrowser(self.centralwidget)
        self.title.setGeometry(QtCore.QRect(100, 10, 461, 61))
        self.title.setObjectName("title")

        self.seriesInput = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.seriesInput.setGeometry(QtCore.QRect(100, 110, 371, 31))
        self.seriesInput.setObjectName("seriesInput")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(100, 90, 71, 16))
        self.label.setObjectName("label")

        self.errorLabel = QtWidgets.QLabel(self.centralwidget)
        self.errorLabel.setGeometry(QtCore.QRect(300, 200, 71, 16))
        self.errorLabel.setObjectName("error")
        self.errorLabel.setStyleSheet("color: red")

        self.colourInput = QtWidgets.QLabel(self.centralwidget)
        self.colourInput.setGeometry(QtCore.QRect(190, 160, 81, 51))
        self.colourInput.setObjectName("BlockColor")
        self.borderStylesheet()

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(100, 140, 101, 16))
        self.label_2.setObjectName("label_2")

        self.seriesNameEnter = QtWidgets.QPushButton(self.centralwidget)
        self.seriesNameEnter.setGeometry(QtCore.QRect(480, 110, 81, 31))
        self.seriesNameEnter.setObjectName("seriesNameEnter")
        self.seriesNameEnter.clicked.connect(lambda: self.createImage())

        self.colourEnter = QtWidgets.QPushButton(self.centralwidget)
        self.colourEnter.setGeometry(QtCore.QRect(100, 160, 81, 51))
        self.colourEnter.setObjectName("colourEnter")
        self.colourEnter.clicked.connect(lambda: self.getColor())

        MainWindow.setCentralWidget(self.centralwidget)

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 656, 21))
        self.menubar.setObjectName("menubar")

        self.imgLabel = QtWidgets.QLabel(self.centralwidget)
        self.imgLabel.setGeometry(120, 230, 400, 400)
        self.imgLabel.setObjectName('image')
        self.imgLabel.setText("")
        self.imgLabel.setScaledContents(True)

        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")

        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")

        MainWindow.setStatusBar(self.statusbar)

        self.actionSave = QtWidgets.QAction(MainWindow)
        self.actionSave.setObjectName("actionSave")

        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")

        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionNew)

        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.actionNew.triggered.connect(lambda: self.resetScreen())

        self.actionSave.triggered.connect(lambda: self.save())

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("MainWindow", "Series rating generator."))
        self.saveButton.setText(_translate("MainWindow", "Save"))
        self.newButton.setText(_translate("MainWindow", "New"))
        self.title.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:28pt; font-weight:600;\">Series Rating Generator</span></p></body></html>"
            ))
        self.label.setText(_translate("MainWindow", "Series name"))
        self.errorLabel.setText(_translate("MainWindow", ""))
        self.seriesNameEnter.setText(_translate("MainWindow", "Enter"))
        self.colourEnter.setText(_translate("MainWindow", "Choose a color"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionSave.setText(_translate("MainWindow", "Save"))
        self.actionSave.setStatusTip(_translate("MainWindow", "Save image"))
        self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S"))
        self.actionNew.setText(_translate("MainWindow", "New"))
        self.actionNew.setStatusTip(_translate("MainWindow", "New Image"))
        self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N"))

    def createImage(self):
        text = self.seriesInput.toPlainText()
        colour = '#%02x%02x%02x' % self.picked_color

        text = text.rstrip()
        text = text.lstrip()
        self.clearExceptions()

        if text != '':
            try:
                picture = CreatePicture(text, colour)
                picture.createImage()
                self.updatePhoto(text)
                self.currentShow = text
            except KeyError:
                self.updateErrorLabel(
                    'Enter a valid series (Movies dont work)')
        else:
            self.updateErrorLabel('Enter a valid series')

    def updateErrorLabel(self, text):
        self.errorLabel.setText(text)
        self.errorLabel.adjustSize()

    def updatePhoto(self, name):
        if self.currentShow != "":
            try:
                os.remove(self.currentShow + '.png')
            except FileNotFoundError:
                pass
        self.imgLabel.setPixmap(QtGui.QPixmap(name + '.png'))

    def resetScreen(self):
        self.imgLabel.setPixmap(QtGui.QPixmap(""))
        self.seriesInput.appendPlainText("")
        self.picked_color = (255, 255, 255)
        self.borderStylesheet()
        self.clearExceptions()

        try:
            os.remove(self.currentShow + '.png')
        except FileNotFoundError:
            pass

    def getColor(self):
        self.color_picker = ColorPicker()
        self.picked_color = self.color_picker.getColor()
        self.picked_color = tuple([int(x) for x in self.picked_color])
        self.borderStylesheet()

    def save(self):

        if self.currentShow != "":
            dir = self.chooseDir()
            show = self.currentShow + '.png'
            shutil.copy(show, dir)
            os.remove(show)
        else:
            self.updateErrorLabel('Please create a poster before saving')

    def chooseDir(self):
        self.dialog = QFileDialog()
        folder_path = self.dialog.getExistingDirectory(None, "Select Folder")
        return folder_path

    def closeEvent(self, event):
        if self.currentShow != "":
            try:
                os.remove(self.currentShow + '.png')
            except FileNotFoundError:
                pass

    def clearExceptions(self):
        self.errorLabel.setText("")

    def borderStylesheet(self):
        self.colourInput.setStyleSheet(
            """QWidget {{border: 1px solid black; border-radius: 2px; background-color: rgb{};}} """
            .format(self.picked_color))
Exemple #18
0
 def startPicking(self):
     picker = ColorPicker()
     picker.picked.connect(self.setColor)
     picker.exec_()
Exemple #19
0
class Elicit:
    def save(self):
        old_filename = self.palette.filename
        self.palette.save()
        if old_filename == None:
            self.gconf.set_string('/apps/elicit/palette',
                                  os.path.basename(self.palette.filename))

    def quit(self, widget=None, data=None):
        self.save()
        gtk.main_quit()

    def main(self):
        gtk.main()

    def show(self):
        self.win.show_all()

    def hide(self):
        self.win.hide()

    def grab(self, x, y, w, h):
        self.mag.grab(x, y, w, h)

    def mag_grid_toggled(self, mag):
        self.grid_check.set_active(mag.show_grid)

    def mag_zoom_changed(self, mag):
        self.gconf.set_int('/apps/elicit/zoom_level', mag.zoom)

    def mag_measure_changed(self, mag):
        if mag.measure_rect:
            text = "[%dx%d] (%.1f diag) " % (
                mag.measure_rect.width, mag.measure_rect.height,
                math.sqrt(mag.measure_rect.width**2 +
                          mag.measure_rect.height**2))
        else:
            text = ""

        self.measure_label.set_text(text)

    def mag_location_changed(self, mag):
        if mag.screen_rect:
            text = "  (%d,%d) %dx%d" % (mag.screen_rect.x, mag.screen_rect.y,
                                        mag.screen_rect.width,
                                        mag.screen_rect.height)
        else:
            text = ""

        self.mag_label.set_text(text)

    def grid_check_toggled(self, check):
        self.gconf.set_bool('/apps/elicit/show_grid', check.get_active())

    def zoom_spin_value_changed(self, spin):
        self.gconf.set_int('/apps/elicit/zoom_level', int(spin.get_value()))

    def picker_save_color(self, picker):
        c = Color()
        c.set_rgb(*picker.color.rgb())
        self.palette.append(c)
        self.palette_view.select(c)
        self.palette.save()

    def palette_view_select_color(self, palette_view, color):
        if color == None:
            self.color_name_entry.set_text("")
            self.color_name_entry.set_sensitive(False)
        else:
            self.gconf.set_string('/apps/elicit/color', color.hex())
            self.color_name_entry.set_text(color.name)
            self.color_name_entry.set_sensitive(True)

    def palette_view_delete_color(self, palette_view, color):
        self.palette.remove(color)
        self.palette.save()

    def color_name_entry_changed(self, color_name_entry):
        if self.palette and self.palette_view.selected:
            self.palette_view.selected.name = color_name_entry.get_text()
            self.palette.save()

    def color_changed(self, color):
        self.colorspin['r'].set_value(self.color.r)
        self.colorspin['g'].set_value(self.color.g)
        self.colorspin['b'].set_value(self.color.b)
        self.colorspin['h'].set_value(self.color.h)
        self.colorspin['s'].set_value(self.color.s)
        self.colorspin['v'].set_value(self.color.v)
        self.hex_entry.set_text(self.color.hex())
        if self.palette_view.selected and color.hex(
        ) != self.palette_view.selected.hex():
            self.palette_view.select(None)

        h, s, v = self.color.hsv()
        if self.wheel:
            self.wheel.set_color(h / 360., s, v)
        self.gconf.set_string('/apps/elicit/color', self.color.hex())

    def color_spin_rgb_changed(self, spin):
        r, g, b = self.color.rgb()
        if spin == self.colorspin['r']:
            r = spin.get_value()
        elif spin == self.colorspin['g']:
            g = spin.get_value()
        elif spin == self.colorspin['b']:
            b = spin.get_value()
        self.color.set_rgb(r, g, b)

    def color_spin_hsv_changed(self, spin):
        h, s, v = self.color.hsv()
        if spin == self.colorspin['h']:
            h = spin.get_value()
        elif spin == self.colorspin['s']:
            s = spin.get_value()
        elif spin == self.colorspin['v']:
            v = spin.get_value()
        self.color.set_hsv(h, s, v)

    def hex_entry_changed(self, entry):
        text = entry.get_text()
        if not text: return

        if ((text[0] == '#' and len(text) == 7)
                or (text[0] != '#' and len(text) == 6)):
            try:
                self.color.set_hex(text)
            except ValueError:
                #XXX indicate that the value is bad somehow
                pass

    def palette_combo_selected(self, combo, palette):
        if (self.palette != palette):
            if (palette.filename):
                self.gconf.set_string('/apps/elicit/palette',
                                      os.path.basename(palette.filename))
            if self.palette:
                old_filename = self.palette.filename
                self.palette.save()

                #update palette list with new filename
                if old_filename != self.palette.filename:
                    index = self.palette_list.index_of_palette(self.palette)
                    if index != None:
                        self.palette_list[index][1] = self.palette.filename

            self.palette = palette
            self.palette_view.set_palette(self.palette)
            self.color_name_entry.set_sensitive(False)

    def add_palette(self, button):
        p = Palette()
        p.name = "Untitled Palette"
        self.palette_list.append(p)
        self.palette_combo.select(self.palette_list.index_of_palette(p))

    def delete_palette(self, button):
        if not self.palette: return

        d = gtk.MessageDialog(self.win, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
                              gtk.BUTTONS_OK_CANCEL, None)

        d.set_markup(
            "Are you sure you want to delete the palette <b>%s</b>? This cannot be undone."
            % self.palette.name)
        response = d.run()
        d.destroy()
        if response == gtk.RESPONSE_OK:
            p = self.palette
            self.palette_combo.remove(self.palette_list.index_of_palette(p))
            p.delete()

    def select_color_clicked(self, button):
        sel_action = self.actiongroup.get_action("Select Color")
        sel_action.activate()

    def magnify_clicked(self, button):
        mag_action = self.actiongroup.get_action("Magnify")
        mag_action.activate()

    def build_menu(self):
        uimanager = gtk.UIManager()
        accelgroup = uimanager.get_accel_group()
        self.accelgroup = accelgroup
        self.win.add_accel_group(accelgroup)

        actiongroup = gtk.ActionGroup('ElicitActions')
        self.actiongroup = actiongroup

        actiongroup.add_actions([
            ('Quit', gtk.STOCK_QUIT, '_Quit', '<Ctrl>q', 'Quit Elicit',
             self.action_quit),
            ('Save', gtk.STOCK_QUIT, '_Save Palette', '<Ctrl>s',
             'Save Palette', self.action_save),
            ('About', gtk.STOCK_ABOUT, '_About', None, 'About Elicit',
             self.action_about),
            ('Magnify', gtk.STOCK_ABOUT, '_Magnify', '<Ctrl>z',
             'Start Magnifying', self.action_magnify),
            ('Select Color', gtk.STOCK_ABOUT, 'Select _Color', '<Ctrl>d',
             'Start Selecting Color', self.action_pick_color),
            ('File', None, '_File'), ('Action', None, '_Action'),
            ('Help', None, '_Help')
        ])

        uimanager.insert_action_group(actiongroup)
        uimanager.add_ui_from_string("""
    <ui>
      <menubar name="ElicitMain">
        <menu action="File">
          <menuitem action="Save"/>
          <menuitem action="Quit"/>
        </menu>
        <menu action="Action">
          <menuitem action="Magnify"/>
          <menuitem action="Select Color"/>
        </menu>
        <menu action="Help">
          <menuitem action="About"/>
        </menu>
      </menubar>
    </ui>
    """)
        menubar = uimanager.get_widget("/ElicitMain")
        return menubar

    def build_gui(self):
        self.win = gtk.Window()
        self.win.set_title("Elicit")
        self.win.set_icon_name('rephorm-elicit')
        self.win.connect('destroy', self.quit, None)

        vbox = gtk.VBox(False, 2)
        self.win.add(vbox)

        menubar = self.build_menu()
        vbox.pack_start(menubar, False)

        # notebook with magnifier, etc
        hbox = gtk.HBox(False, 0)
        vbox.pack_start(hbox, True, True)
        notebook = gtk.Notebook()
        self.notebook = notebook
        hbox.pack_start(notebook, True, True, padding=HPAD)

        # magnifier tab
        mag_vbox = gtk.VBox(False, 2)
        mag_tab_icon = gtk.Image()
        mag_tab_icon.set_from_file(
            os.path.join(self.icon_path, "magnify-16.png"))
        notebook.append_page(mag_vbox, mag_tab_icon)

        # the magnifier
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, True, True)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, True, padding=HPAD)

        self.mag = Magnifier()
        frame.add(self.mag)
        self.mag.connect('zoom-changed', self.mag_zoom_changed)
        self.mag.connect('grid-toggled', self.mag_grid_toggled)
        self.mag.connect('measure-changed', self.mag_measure_changed)
        self.mag.connect('location-changed', self.mag_location_changed)

        # magnifier information (coordinates)
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, False)

        self.mag_label = gtk.Label()
        hbox.pack_start(self.mag_label, False, padding=HPAD)

        self.measure_label = gtk.Label()
        hbox.pack_end(self.measure_label, False)

        # magnifier tools
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, False)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(self.icon_path, "magnify-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
        button.connect('clicked', self.magnify_clicked)
        hbox.pack_end(button, False, padding=HPAD)

        check = gtk.CheckButton("Show Grid")
        check.set_active(self.mag.show_grid)
        check.connect('toggled', self.grid_check_toggled)
        hbox.pack_start(check, padding=HPAD)
        self.grid_check = check

        spin = gtk.SpinButton()
        spin.set_range(1, 50)
        spin.set_increments(1, 10)
        spin.set_value(self.mag.zoom)
        spin.connect('value-changed', self.zoom_spin_value_changed)
        hbox.pack_end(spin, False, padding=HPAD)
        self.zoom_spin = spin

        zoom_label = gtk.Label("Zoom:")
        hbox.pack_end(zoom_label, False)

        # color wheel
        wheel_frame = gtk.Frame()
        wheel_tab_icon = gtk.Image()
        wheel_tab_icon.set_from_file(
            os.path.join(self.icon_path, "color-wheel-16.png"))
        notebook.append_page(wheel_frame, wheel_tab_icon)

        if hasattr(gtk, 'HSV'):
            wheel = gtk.HSV()
            self.wheel = wheel
            wheel_frame.add(wheel)

            wheel_frame.connect('size-allocate', self.wheel_size_allocate)
            wheel_frame.connect('size-request', self.wheel_size_request)
            wheel.connect('changed', self.wheel_changed)
        else:
            self.wheel = None
            label = gtk.Label(
                "The color wheel requires gtk ver. 2.28 or higher.")
            wheel_frame.add(label)

        # swatch and eyedropper button
        hbox = gtk.HBox(False, 0)
        vbox.pack_start(hbox, False)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(self.icon_path, "dropper-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
        button.connect('clicked', self.select_color_clicked)
        hbox.pack_end(button, False, padding=HPAD)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, True, padding=HPAD)

        self.colorpicker = ColorPicker()
        frame.add(self.colorpicker)
        self.colorpicker.connect('save-color', self.picker_save_color)
        self.colorpicker.set_magnifier(self.mag)

        # color values (sliders and spinboxes)
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        self.colorspin = {}

        table = gtk.Table(6, 4)
        hbox.pack_start(table, True, True, padding=HPAD)

        row = 0
        for type in ("r", "g", "b"):
            label = gtk.Label(type.upper())
            table.attach(label, 0, 1, row, row + 1, 0, 0, 2, 2)
            cslider = CSlider(self.color, type)
            table.attach(cslider, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND,
                         gtk.EXPAND, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 255)
            spin.set_increments(1, 10)
            spin.connect('value-changed', self.color_spin_rgb_changed)
            table.attach(spin, 2, 3, row, row + 1, 0, gtk.EXPAND, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("h", "s", "v"):
            label = gtk.Label(type.upper())
            table.attach(label, 3, 4, row, row + 1, 0, 0, 2, 2)
            cslider = CSlider(self.color, type)
            table.attach(cslider, 4, 5, row, row + 1, gtk.FILL | gtk.EXPAND,
                         gtk.EXPAND, 2, 2)
            spin = gtk.SpinButton()
            if type == 'h':
                spin.set_range(0, 360)
                spin.set_increments(1, 10)
            else:
                spin.set_digits(2)
                spin.set_range(0, 1.0)
                spin.set_increments(.01, .1)
            spin.connect('value-changed', self.color_spin_hsv_changed)
            table.attach(spin, 5, 6, row, row + 1, 0, gtk.EXPAND, 2, 2)
            self.colorspin[type] = spin
            row += 1

        self.hex_label = gtk.Label("Hex")
        table.attach(self.hex_label, 0, 1, 3, 4, gtk.FILL, gtk.EXPAND, 2, 2)

        self.hex_entry = gtk.Entry()
        table.attach(self.hex_entry, 1, 6, 3, 4, gtk.FILL, gtk.EXPAND, 2, 2)
        self.hex_entry.connect('changed', self.hex_entry_changed)

        sep = gtk.HSeparator()
        vbox.pack_start(sep, False)

        # palette tools
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        hbox.pack_start(gtk.Label("Palette:"), False, padding=HPAD)

        self.palette_combo = PaletteCombo()
        hbox.pack_start(self.palette_combo)
        self.palette_combo.connect('selected', self.palette_combo_selected)

        button = gtk.Button()
        button.set_image(
            gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Add Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect('clicked', self.add_palette)
        hbox.pack_start(button, False)

        button = gtk.Button()
        button.set_image(
            gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Delete Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect('clicked', self.delete_palette)
        hbox.pack_start(button, False, padding=HPAD)

        # palette view
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, padding=HPAD)

        self.palette_view = PaletteView()
        self.palette_view.connect('select-color',
                                  self.palette_view_select_color)
        self.palette_view.connect('delete-color',
                                  self.palette_view_delete_color)
        frame.add(self.palette_view)

        # color name entry
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False, padding=VPAD)

        hbox.pack_start(gtk.Label("Color Name:"), False, padding=HPAD)

        self.color_name_entry = gtk.Entry()
        self.color_name_entry.set_sensitive(False)
        self.color_name_entry.connect('changed', self.color_name_entry_changed)
        hbox.pack_start(self.color_name_entry, True, True, padding=HPAD)

    def init_config(self):
        self.gconf = gconf.client_get_default()
        self.gconf.add_dir('/apps/elicit', preload=True)
        self.gconf_id = self.gconf.notify_add("/apps/elicit",
                                              self.config_changed)

    def load_config(self):
        color = self.gconf.get_string('/apps/elicit/color')
        if color: self.color.set_hex(color)

        zoom_level = self.gconf.get_int('/apps/elicit/zoom_level')
        self.mag.set_zoom(zoom_level)
        self.zoom_spin.set_value(self.mag.zoom)

        grab_rate = self.gconf.get_int('/apps/elicit/grab_rate')
        if grab_rate > 0: self.mag.grab_rate = grab_rate

        show_grid = self.gconf.get_bool('/apps/elicit/show_grid')
        self.mag.set_show_grid(show_grid)
        self.grid_check.set_active(self.mag.show_grid)

        palette = self.gconf.get_string('/apps/elicit/palette')
        if not palette: palette = 'default.gpl'
        index = self.palette_list.index_of_file(palette)
        if index == None:
            index = 0
        self.palette_combo.select(index)

    def wheel_size_allocate(self, frame, allocation):
        style = frame.get_style()
        focus_width = frame.style_get_property('focus-line-width')
        focus_padding = frame.style_get_property('focus-padding')
        size = (min(allocation.width, allocation.height) -
                2 * max(style.xthickness, style.ythickness) - 2 *
                (focus_width + focus_padding))

        self.wheel.set_metrics(int(size), int(size / 10))

    def wheel_size_request(self, frame, requisition):
        focus_width = frame.style_get_property('focus-line-width')
        focus_padding = frame.style_get_property('focus-padding')
        requisition.width = 2 * (focus_width + focus_padding)
        requisition.height = 2 * (focus_width + focus_padding)

    def wheel_changed(self, wheel):
        h, s, v = wheel.get_color()
        h *= 360
        self.color.set_hsv(h, s, v)

    def config_changed(self, client, gconf_id, entry, user_data):
        key = entry.key[13:]

        if key == 'color':
            hex = entry.value.get_string()
            self.color.set_hex(hex)
        elif key == 'zoom_level':
            self.mag.set_zoom(entry.value.get_int())
            self.zoom_spin.set_value(self.mag.zoom)
        elif key == 'show_grid':
            self.mag.set_show_grid(entry.value.get_bool())
            self.grid_check.set_active(self.mag.show_grid)
        elif key == 'palette':
            palette = entry.value.get_string()
            if not palette: palette = 'default.gpl'
            self.palette_combo.select(self.palette_list.index_of_file(palette))
        elif key == 'grab_rate':
            self.mag.set_grab_rate(entry.value.get_int())

    def action_quit(self, action):
        self.quit()

    def action_save(self, action):
        self.save()

    def action_about(self, action):
        a = gtk.AboutDialog()
        a.set_name(appinfo.name)
        a.set_version(appinfo.version)
        a.set_website(appinfo.website)
        a.set_authors([appinfo.author])
        a.set_logo_icon_name('rephorm-elicit')

        a.connect('response', lambda dialog, respons: dialog.destroy())
        a.show()

    def action_magnify(self, action):
        if self.mag.grabbing:
            self.mag.grab_stop()

        if self.colorpicker.picking:
            self.colorpicker.pick_stop()

        self.mag.grab_start()

    def action_pick_color(self, action):
        if self.colorpicker.picking:
            self.colorpicker.pick_stop()

        if self.mag.grabbing:
            self.mag.grab_stop()

        self.colorpicker.pick_start()

    def __init__(self):
        self.palette = None
        self.color = Color()
        self.color.connect('changed', self.color_changed)

        self.icon_path = os.path.join(os.path.dirname(__file__), 'data',
                                      'icons')

        self.init_config()
        self.build_gui()

        self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname),
                                        'palettes')
        Palette.PaletteDir = self.palette_dir

        self.palette_list = PaletteList()
        self.palette_list.load(self.palette_dir)
        self.palette_combo.set_model(self.palette_list)

        # no palettes, so create default
        if len(self.palette_list) == 0:
            palette = Palette()
            palette.name = "Default Palette"
            palette.filename = os.path.join(self.palette_dir, 'default.gpl')
            self.palette_list.append(palette)

            self.palette_combo.select(0)

        self.colorpicker.set_color(self.color)

        self.load_config()
Exemple #20
0
    def build_gui(self):
        self.win = gtk.Window()
        self.win.set_title("Elicit")
        self.win.set_icon_name('rephorm-elicit')
        self.win.connect('destroy', self.quit, None)

        vbox = gtk.VBox(False, 2)
        self.win.add(vbox)

        menubar = self.build_menu()
        vbox.pack_start(menubar, False)

        # notebook with magnifier, etc
        hbox = gtk.HBox(False, 0)
        vbox.pack_start(hbox, True, True)
        notebook = gtk.Notebook()
        self.notebook = notebook
        hbox.pack_start(notebook, True, True, padding=HPAD)

        # magnifier tab
        mag_vbox = gtk.VBox(False, 2)
        mag_tab_icon = gtk.Image()
        mag_tab_icon.set_from_file(
            os.path.join(self.icon_path, "magnify-16.png"))
        notebook.append_page(mag_vbox, mag_tab_icon)

        # the magnifier
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, True, True)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, True, padding=HPAD)

        self.mag = Magnifier()
        frame.add(self.mag)
        self.mag.connect('zoom-changed', self.mag_zoom_changed)
        self.mag.connect('grid-toggled', self.mag_grid_toggled)
        self.mag.connect('measure-changed', self.mag_measure_changed)
        self.mag.connect('location-changed', self.mag_location_changed)

        # magnifier information (coordinates)
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, False)

        self.mag_label = gtk.Label()
        hbox.pack_start(self.mag_label, False, padding=HPAD)

        self.measure_label = gtk.Label()
        hbox.pack_end(self.measure_label, False)

        # magnifier tools
        hbox = gtk.HBox(False, 0)
        mag_vbox.pack_start(hbox, False)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(self.icon_path, "magnify-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
        button.connect('clicked', self.magnify_clicked)
        hbox.pack_end(button, False, padding=HPAD)

        check = gtk.CheckButton("Show Grid")
        check.set_active(self.mag.show_grid)
        check.connect('toggled', self.grid_check_toggled)
        hbox.pack_start(check, padding=HPAD)
        self.grid_check = check

        spin = gtk.SpinButton()
        spin.set_range(1, 50)
        spin.set_increments(1, 10)
        spin.set_value(self.mag.zoom)
        spin.connect('value-changed', self.zoom_spin_value_changed)
        hbox.pack_end(spin, False, padding=HPAD)
        self.zoom_spin = spin

        zoom_label = gtk.Label("Zoom:")
        hbox.pack_end(zoom_label, False)

        # color wheel
        wheel_frame = gtk.Frame()
        wheel_tab_icon = gtk.Image()
        wheel_tab_icon.set_from_file(
            os.path.join(self.icon_path, "color-wheel-16.png"))
        notebook.append_page(wheel_frame, wheel_tab_icon)

        if hasattr(gtk, 'HSV'):
            wheel = gtk.HSV()
            self.wheel = wheel
            wheel_frame.add(wheel)

            wheel_frame.connect('size-allocate', self.wheel_size_allocate)
            wheel_frame.connect('size-request', self.wheel_size_request)
            wheel.connect('changed', self.wheel_changed)
        else:
            self.wheel = None
            label = gtk.Label(
                "The color wheel requires gtk ver. 2.28 or higher.")
            wheel_frame.add(label)

        # swatch and eyedropper button
        hbox = gtk.HBox(False, 0)
        vbox.pack_start(hbox, False)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(self.icon_path, "dropper-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
        button.connect('clicked', self.select_color_clicked)
        hbox.pack_end(button, False, padding=HPAD)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, True, padding=HPAD)

        self.colorpicker = ColorPicker()
        frame.add(self.colorpicker)
        self.colorpicker.connect('save-color', self.picker_save_color)
        self.colorpicker.set_magnifier(self.mag)

        # color values (sliders and spinboxes)
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        self.colorspin = {}

        table = gtk.Table(6, 4)
        hbox.pack_start(table, True, True, padding=HPAD)

        row = 0
        for type in ("r", "g", "b"):
            label = gtk.Label(type.upper())
            table.attach(label, 0, 1, row, row + 1, 0, 0, 2, 2)
            cslider = CSlider(self.color, type)
            table.attach(cslider, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND,
                         gtk.EXPAND, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 255)
            spin.set_increments(1, 10)
            spin.connect('value-changed', self.color_spin_rgb_changed)
            table.attach(spin, 2, 3, row, row + 1, 0, gtk.EXPAND, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("h", "s", "v"):
            label = gtk.Label(type.upper())
            table.attach(label, 3, 4, row, row + 1, 0, 0, 2, 2)
            cslider = CSlider(self.color, type)
            table.attach(cslider, 4, 5, row, row + 1, gtk.FILL | gtk.EXPAND,
                         gtk.EXPAND, 2, 2)
            spin = gtk.SpinButton()
            if type == 'h':
                spin.set_range(0, 360)
                spin.set_increments(1, 10)
            else:
                spin.set_digits(2)
                spin.set_range(0, 1.0)
                spin.set_increments(.01, .1)
            spin.connect('value-changed', self.color_spin_hsv_changed)
            table.attach(spin, 5, 6, row, row + 1, 0, gtk.EXPAND, 2, 2)
            self.colorspin[type] = spin
            row += 1

        self.hex_label = gtk.Label("Hex")
        table.attach(self.hex_label, 0, 1, 3, 4, gtk.FILL, gtk.EXPAND, 2, 2)

        self.hex_entry = gtk.Entry()
        table.attach(self.hex_entry, 1, 6, 3, 4, gtk.FILL, gtk.EXPAND, 2, 2)
        self.hex_entry.connect('changed', self.hex_entry_changed)

        sep = gtk.HSeparator()
        vbox.pack_start(sep, False)

        # palette tools
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        hbox.pack_start(gtk.Label("Palette:"), False, padding=HPAD)

        self.palette_combo = PaletteCombo()
        hbox.pack_start(self.palette_combo)
        self.palette_combo.connect('selected', self.palette_combo_selected)

        button = gtk.Button()
        button.set_image(
            gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Add Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect('clicked', self.add_palette)
        hbox.pack_start(button, False)

        button = gtk.Button()
        button.set_image(
            gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Delete Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect('clicked', self.delete_palette)
        hbox.pack_start(button, False, padding=HPAD)

        # palette view
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        hbox.pack_start(frame, True, padding=HPAD)

        self.palette_view = PaletteView()
        self.palette_view.connect('select-color',
                                  self.palette_view_select_color)
        self.palette_view.connect('delete-color',
                                  self.palette_view_delete_color)
        frame.add(self.palette_view)

        # color name entry
        hbox = gtk.HBox(False, 5)
        vbox.pack_start(hbox, False, padding=VPAD)

        hbox.pack_start(gtk.Label("Color Name:"), False, padding=HPAD)

        self.color_name_entry = gtk.Entry()
        self.color_name_entry.set_sensitive(False)
        self.color_name_entry.connect('changed', self.color_name_entry_changed)
        hbox.pack_start(self.color_name_entry, True, True, padding=HPAD)
Exemple #21
0
    def __init__(self, label, parent=None):
        super(ColorEditor, self).__init__(parent)
        layout = QGridLayout()
        self.color = QLineEdit()
        self.colorPicker = ColorPicker()
        self.colorPicker.setVisible(False)
        self.hueSlider = QSlider()
        self.hueSlider.setVisible(False)
        self.hueSlider.setMinimum(0)
        self.hueSlider.setMaximum(100.0)
        self.hueSlider.setOrientation(Qt.Vertical)
        self.hueSlider.setMaximumHeight(100.0)
        self.rect = ColorRect()
        self.hue = QSpinBox()
        self.saturation = QSpinBox()
        self.lightness = QSpinBox()
        self.labelHue = QLabel("H")
        self.labelSaturation = QLabel("S")
        self.labelLightness = QLabel("L")
        self.red = QSpinBox()
        self.green = QSpinBox()
        self.blue = QSpinBox()
        self.labelRed = QLabel("R")
        self.labelGreen = QLabel("G")
        self.labelBlue = QLabel("B")
        self.hue.setVisible(False)
        self.saturation.setVisible(False)
        self.lightness.setVisible(False)
        self.red.setVisible(False)
        self.green.setVisible(False)
        self.blue.setVisible(False)
        self.labelHue.setVisible(False)
        self.labelSaturation.setVisible(False)
        self.labelLightness.setVisible(False)
        self.labelRed.setVisible(False)
        self.labelGreen.setVisible(False)
        self.labelBlue.setVisible(False)
        self.red.setMinimum(0)
        self.red.setMaximum(255)
        self.green.setMinimum(0)
        self.green.setMaximum(255)
        self.blue.setMinimum(0)
        self.blue.setMaximum(255)
        self.hue.setMinimum(0)
        self.hue.setMaximum(100.0)
        self.saturation.setMinimum(0)
        self.saturation.setMaximum(100.0)
        self.lightness.setMinimum(0)
        self.lightness.setMaximum(100.0)
        self.labelHue.setFixedWidth(15)
        self.labelSaturation.setFixedWidth(15)
        self.labelLightness.setFixedWidth(15)
        self.labelRed.setFixedWidth(15)
        self.labelGreen.setFixedWidth(15)
        self.labelBlue.setFixedWidth(15)
        l = QLabel(label)
        l.setMinimumWidth(100.0)

        layout.addWidget(l, 0, 0)
        layout.addWidget(self.rect, 0, 1)
        layout.addWidget(self.color, 0, 2, 1, 3)
        layout.addWidget(self.colorPicker, 1, 0, 3, 2)
        layout.addWidget(self.hueSlider, 1, 2, 3, 1)
        layout.addWidget(self.labelHue, 1, 3)
        layout.addWidget(self.hue, 1, 4)
        layout.addWidget(self.labelSaturation, 2, 3)
        layout.addWidget(self.saturation, 2, 4)
        layout.addWidget(self.labelLightness, 3, 3)
        layout.addWidget(self.lightness, 3, 4)
        layout.addWidget(self.labelRed, 1, 5)
        layout.addWidget(self.red, 1, 6)
        layout.addWidget(self.labelGreen, 2, 5)
        layout.addWidget(self.green, 2, 6)
        layout.addWidget(self.labelBlue, 3, 5)
        layout.addWidget(self.blue, 3, 6)
        self.setLayout(layout)
        self.connectControls()
Exemple #22
0
    def build_gui(self):
        self.win = gtk.Window()
        self.win.set_title("Elicit")
        self.win.set_icon_name("rephorm-elicit")
        self.win.connect("destroy", self.quit, None)

        main_vbox = gtk.VBox(False, 2)

        menubar = self.build_menu()
        w_vbox = gtk.VBox()
        w_vbox.pack_start(menubar, False)
        w_vbox.pack_end(main_vbox, True)
        # main_vbox.pack_start(menubar, False)
        main_vbox.set_border_width(7)
        self.win.add(w_vbox)

        frame_mag = gtk.Frame()
        frame_mag.set_shadow_type(gtk.SHADOW_NONE)

        frame_mag_inner = gtk.Frame()
        frame_mag_inner.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.mag = Magnifier()
        frame_mag_inner.add(self.mag)
        mag_vbox = gtk.VBox()
        mag_vbox.pack_start(frame_mag_inner)
        frame_mag.add(mag_vbox)
        self.mag.connect("zoom-changed", self.mag_zoom_changed)
        self.mag.connect("grid-toggled", self.mag_grid_toggled)
        self.mag.connect("measure-changed", self.mag_measure_changed)
        self.mag.connect("location-changed", self.mag_location_changed)

        hbox = gtk.HBox(False, 0)

        self.mag_label = gtk.Label()
        hbox.pack_start(self.mag_label, False)

        icon_path = os.path.join(os.path.dirname(__file__), "data", "icons")

        frame_wheel = gtk.Frame()
        frame_wheel.set_shadow_type(gtk.SHADOW_NONE)
        self.notebook = gtk.Notebook()
        frame_mag_label = gtk.Image()
        frame_mag_label.set_from_file(os.path.join(icon_path, "magnify-16.png"))
        frame_wheel_label = gtk.Image()
        frame_wheel_label.set_from_file(os.path.join(icon_path, "color-wheel-16.png"))
        frame_wheel.connect("size-allocate", self.wheel_size_allocate)
        frame_wheel.connect("size-request", self.wheel_size_request)
        self.notebook.append_page(frame_mag, frame_mag_label)
        self.notebook.append_page(frame_wheel, frame_wheel_label)

        # TODO: do not hardcode tha palette path!
        # self.name_palette = NamePalette('../ntc.txt', self.color)
        self.name_palette = NamePalette("/etc/X11/rgb.txt", self.color)
        self.name_treeview = ColorName(self.name_palette)
        # self.h_ids['name'] = self.name_combobox.connect('changed', self.name_combobox_changed)
        # name_hbox.pack_start(self.name_combobox, True, True, 2)

        frame_name_palette = gtk.Frame()
        frame_name_palette_label = gtk.Image()
        frame_name_palette_label.set_from_file(os.path.join(icon_path, "palette-16.png"))
        self.notebook.append_page(frame_name_palette, frame_name_palette_label)
        name_scroll = gtk.ScrolledWindow()
        name_scroll.add(self.name_treeview)
        frame_name_palette.add(name_scroll)

        self.wheel = gtk.HSV()
        self.wheel.was_adjusting = False
        frame_wheel.add(self.wheel)
        self.h_ids["wheel"] = self.wheel.connect("changed", self.wheel_changed)

        main_vbox.pack_start(self.notebook, True, True)
        mag_vbox.pack_start(hbox, False)
        main_vbox.set_spacing(5)

        pick_view_hbox = gtk.HBox()
        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(icon_path, "dropper-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
        button.connect("clicked", self.select_color_clicked)
        pick_view_hbox.pack_start(button, False)
        main_vbox.pack_start(pick_view_hbox)

        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        img = gtk.Image()
        img.set_from_file(os.path.join(icon_path, "magnify-button.png"))
        button.set_image(img)
        button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
        button.connect("clicked", self.magnify_clicked)
        hbox.pack_end(button, False)

        self.measure_label = gtk.Label()
        hbox.pack_end(self.measure_label, False)

        hbox = gtk.HBox(False, 5)
        mag_vbox.pack_start(hbox, False)

        check = gtk.CheckButton("Show Grid")
        check.set_active(self.mag.show_grid)
        check.connect("toggled", self.grid_check_toggled)
        hbox.pack_start(check)
        self.grid_check = check

        spin = gtk.SpinButton()
        spin.set_range(1, 50)
        spin.set_increments(1, 10)
        spin.set_value(self.mag.zoom)
        spin.connect("value-changed", self.zoom_spin_value_changed)
        hbox.pack_end(spin, False)
        self.zoom_spin = spin

        zoom_label = gtk.Label("Zoom:")
        hbox.pack_end(zoom_label, False)

        vbox = gtk.VBox(False, 5)
        main_vbox.pack_start(vbox, False)

        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        pick_view_hbox.pack_end(frame, True, True)

        self.colorpicker = ColorPicker()
        frame.add(self.colorpicker)
        self.colorpicker.connect("save-color", self.picker_save_color)
        self.colorpicker.set_magnifier(self.mag)
        self.name_palette.connect("colorname-changed", self.colorpicker.colorname_changed)

        self.colorspin = {}
        # add RGB spinboxes
        table = gtk.Table(6, 4)
        vbox.pack_start(table, True)

        row = 0
        for type in ("r", "g", "b"):
            label = gtk.Label(type.upper())
            table.attach(label, 0, 1, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 255)
            spin.set_increments(1, 10)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_rgb_changed)
            table.attach(spin, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("h", "s", "v"):
            label = gtk.Label(type.upper())
            table.attach(label, 2, 3, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            if type == "h":
                spin.set_range(0, 360)
                spin.set_increments(1, 10)
            else:
                spin.set_digits(2)
                spin.set_range(0, 1.0)
                spin.set_increments(0.01, 0.1)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_hsv_changed)
            table.attach(spin, 3, 4, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        row = 0
        for type in ("c", "m", "y", "k"):
            label = gtk.Label(type.upper())
            table.attach(label, 4, 5, row, row + 1, 0, 0, 2, 2)
            spin = gtk.SpinButton()
            spin.set_range(0, 100)
            spin.set_increments(1, 10)
            self.h_ids[type] = spin.connect("value-changed", self.color_spin_cmyk_changed)
            table.attach(spin, 5, 6, row, row + 1, gtk.FILL | gtk.EXPAND, 0, 2, 2)
            self.colorspin[type] = spin
            row += 1

        self.hex_label = gtk.Label("Hex")
        table.attach(self.hex_label, 0, 1, 3, 4, 0, 0, 2, 2)

        self.hex_entry = gtk.Entry()
        self.hex_entry.set_max_length(7)
        self.hex_entry.set_width_chars(7)
        table.attach(self.hex_entry, 1, 2, 3, 4, gtk.FILL | gtk.EXPAND, 0, 2, 2)
        self.h_ids["hex"] = self.hex_entry.connect("changed", self.hex_entry_changed)

        name_hbox = gtk.HBox()
        self.name_label = ColorLabel()
        self.name_palette.connect("colorname-changed", self.name_label.colorname_changed)
        name_hbox.pack_end(self.name_label, False, False, 2)
        vbox.pack_start(name_hbox)
        vbox.reorder_child(name_hbox, 0)

        sep = gtk.HSeparator()
        main_vbox.pack_start(sep, False)

        # palette tools
        hbox = gtk.HBox(False, 5)
        main_vbox.pack_start(hbox, False)

        # Palette tools
        hbox.pack_start(gtk.Label("Palette:"), False)

        self.palette_combo = PaletteCombo()
        hbox.pack_start(self.palette_combo)
        self.palette_combo.connect("selected", self.palette_combo_selected)

        button = gtk.Button()
        button.set_image(gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Add Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect("clicked", self.add_palette)
        hbox.pack_start(button, False)

        button = gtk.Button()
        button.set_image(gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON))
        button.set_tooltip_text("Delete Palette")
        button.set_relief(gtk.RELIEF_NONE)
        button.connect("clicked", self.delete_palette)
        hbox.pack_start(button, False)

        # palette view
        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_IN)
        main_vbox.pack_start(frame, False)

        self.palette_view = PaletteView()
        self.palette_view.connect("select-color", self.palette_view_select_color)
        self.palette_view.connect("delete-color", self.palette_view_delete_color)
        frame.add(self.palette_view)

        # color name entry / palette tools
        hbox = gtk.HBox(False, 5)
        main_vbox.pack_start(hbox, False)

        hbox.pack_start(gtk.Label("Color Name:"), False)

        self.color_name_entry = gtk.Entry()
        self.color_name_entry.set_sensitive(False)
        self.color_name_entry.connect("changed", self.color_name_entry_changed)
        hbox.pack_start(self.color_name_entry, True, True)
Exemple #23
0
  def build_gui(self):
    self.win = gtk.Window()
    self.win.set_title("Elicit")
    self.win.set_icon_name('rephorm-elicit')
    self.win.connect('destroy', self.quit, None)

    vbox = gtk.VBox(False, 2)
    self.win.add(vbox)

    menubar = self.build_menu()
    vbox.pack_start(menubar, False)

    # notebook with magnifier, etc
    hbox = gtk.HBox(False, 0)
    vbox.pack_start(hbox, True, True)
    notebook = gtk.Notebook()
    self.notebook = notebook
    hbox.pack_start(notebook, True, True, padding=HPAD)

    # magnifier tab
    mag_vbox = gtk.VBox(False, 2)
    mag_tab_icon = gtk.Image()
    mag_tab_icon.set_from_file(os.path.join(self.icon_path, "magnify-16.png"))
    notebook.append_page(mag_vbox, mag_tab_icon)

    # the magnifier
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, True, True)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, True, padding=HPAD)

    self.mag = Magnifier()
    frame.add(self.mag)
    self.mag.connect('zoom-changed', self.mag_zoom_changed)
    self.mag.connect('grid-toggled', self.mag_grid_toggled)
    self.mag.connect('measure-changed', self.mag_measure_changed)
    self.mag.connect('location-changed', self.mag_location_changed)

    # magnifier information (coordinates)
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, False)

    self.mag_label = gtk.Label()
    hbox.pack_start(self.mag_label, False, padding=HPAD)

    self.measure_label = gtk.Label()
    hbox.pack_end(self.measure_label, False)

    # magnifier tools
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, False)

    button = gtk.Button()
    button.set_relief(gtk.RELIEF_NONE)
    img = gtk.Image()
    img.set_from_file(os.path.join(self.icon_path, "magnify-button.png"));
    button.set_image(img)
    button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
    button.connect('clicked', self.magnify_clicked);
    hbox.pack_end(button, False, padding=HPAD)

    check = gtk.CheckButton("Show Grid")
    check.set_active(self.mag.show_grid)
    check.connect('toggled', self.grid_check_toggled)
    hbox.pack_start(check, padding=HPAD)
    self.grid_check = check

    spin = gtk.SpinButton()
    spin.set_range(1,50)
    spin.set_increments(1,10)
    spin.set_value(self.mag.zoom)
    spin.connect('value-changed', self.zoom_spin_value_changed)
    hbox.pack_end(spin, False, padding=HPAD)
    self.zoom_spin = spin

    zoom_label = gtk.Label("Zoom:")
    hbox.pack_end(zoom_label, False)

    # color wheel
    wheel_frame = gtk.Frame()
    wheel_tab_icon = gtk.Image()
    wheel_tab_icon.set_from_file(os.path.join(self.icon_path, "color-wheel-16.png"))
    notebook.append_page(wheel_frame, wheel_tab_icon)

    if hasattr(gtk, 'HSV'):
      wheel = gtk.HSV()
      self.wheel = wheel
      wheel_frame.add(wheel)

      wheel_frame.connect('size-allocate', self.wheel_size_allocate)
      wheel_frame.connect('size-request', self.wheel_size_request)
      wheel.connect('changed', self.wheel_changed)
    else:
      self.wheel = None
      label = gtk.Label("The color wheel requires gtk ver. 2.28 or higher.")
      wheel_frame.add(label)

    # swatch and eyedropper button
    hbox = gtk.HBox(False, 0)
    vbox.pack_start(hbox, False)

    button = gtk.Button()
    button.set_relief(gtk.RELIEF_NONE)
    img = gtk.Image()
    img.set_from_file(os.path.join(self.icon_path, "dropper-button.png"));
    button.set_image(img)
    button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
    button.connect('clicked', self.select_color_clicked);
    hbox.pack_end(button, False, padding=HPAD)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, True, padding=HPAD)

    self.colorpicker = ColorPicker()
    frame.add(self.colorpicker)
    self.colorpicker.connect('save-color', self.picker_save_color)
    self.colorpicker.set_magnifier(self.mag)

    # color values (sliders and spinboxes)
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    self.colorspin = {}

    table = gtk.Table(6,4)
    hbox.pack_start(table, True, True, padding=HPAD)

    row = 0
    for type in ("r","g","b"):
      label = gtk.Label(type.upper())
      table.attach(label, 0,1,row,row+1,0,0,2,2)
      cslider = CSlider(self.color, type)
      table.attach(cslider, 1,2,row,row+1,gtk.FILL|gtk.EXPAND,gtk.EXPAND,2,2)
      spin = gtk.SpinButton()
      spin.set_range(0,255)
      spin.set_increments(1,10)
      spin.connect('value-changed', self.color_spin_rgb_changed)
      table.attach(spin, 2,3,row,row+1,0,gtk.EXPAND,2,2)
      self.colorspin[type] = spin
      row += 1

    row = 0
    for type in ("h","s","v"):
      label = gtk.Label(type.upper())
      table.attach(label, 3,4,row,row+1,0,0,2,2)
      cslider = CSlider(self.color, type)
      table.attach(cslider, 4,5,row,row+1,gtk.FILL|gtk.EXPAND,gtk.EXPAND,2,2)
      spin = gtk.SpinButton()
      if type == 'h':
        spin.set_range(0,360)
        spin.set_increments(1,10)
      else:
        spin.set_digits(2)
        spin.set_range(0,1.0)
        spin.set_increments(.01,.1)
      spin.connect('value-changed', self.color_spin_hsv_changed)
      table.attach(spin, 5,6,row,row+1,0,gtk.EXPAND,2,2)
      self.colorspin[type] = spin
      row += 1

    self.hex_label = gtk.Label("Hex")
    table.attach(self.hex_label,0,1,3,4,gtk.FILL,gtk.EXPAND,2,2)

    self.hex_entry = gtk.Entry()
    table.attach(self.hex_entry,1,6,3,4,gtk.FILL,gtk.EXPAND,2,2)
    self.hex_entry.connect('changed', self.hex_entry_changed)

    sep = gtk.HSeparator()
    vbox.pack_start(sep, False)

    # palette tools
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    hbox.pack_start(gtk.Label("Palette:"), False, padding=HPAD)

    self.palette_combo = PaletteCombo()
    hbox.pack_start(self.palette_combo)
    self.palette_combo.connect('selected', self.palette_combo_selected)

    button = gtk.Button()
    button.set_image(gtk.image_new_from_stock(gtk.STOCK_ADD,gtk.ICON_SIZE_BUTTON))
    button.set_tooltip_text("Add Palette")
    button.set_relief(gtk.RELIEF_NONE)
    button.connect('clicked', self.add_palette)
    hbox.pack_start(button, False)

    button = gtk.Button()
    button.set_image(gtk.image_new_from_stock(gtk.STOCK_DELETE,gtk.ICON_SIZE_BUTTON))
    button.set_tooltip_text("Delete Palette")
    button.set_relief(gtk.RELIEF_NONE)
    button.connect('clicked', self.delete_palette)
    hbox.pack_start(button, False, padding=HPAD)


    # palette view
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, padding=HPAD)

    self.palette_view = PaletteView()
    self.palette_view.connect('select-color', self.palette_view_select_color)
    self.palette_view.connect('delete-color', self.palette_view_delete_color)
    frame.add(self.palette_view)

    # color name entry
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False, padding=VPAD)

    hbox.pack_start(gtk.Label("Color Name:"), False, padding=HPAD)

    self.color_name_entry = gtk.Entry()
    self.color_name_entry.set_sensitive(False)
    self.color_name_entry.connect('changed', self.color_name_entry_changed)
    hbox.pack_start(self.color_name_entry, True, True, padding=HPAD)
Exemple #24
0
 def colorpicker(self):
     """
     Deprecated. A better solution actually came with tkinter.
     :return:
     """
     ColorPicker(self)
Exemple #25
0
from colorpicker import ColorPicker
from PyQt5.QtWidgets import QApplication

app = QApplication([])

my_color_picker = ColorPicker(useAlpha=True)
my_color_picker_light = ColorPicker(lightTheme=True)

old_color = (255, 255, 255, 50)
picked_color = my_color_picker.getColor(old_color)
print(picked_color)

old_color = (255, 0, 255)
picked_color = my_color_picker_light.getColor(old_color)
print(picked_color)

# Don't have your color in RGB format?
my_color = (50, 50, 100, 60)  # HSV Color in percent
old_color = my_color_picker.hsv2rgb(my_color)
picked_color = my_color_picker.rgb2hsv(my_color_picker.getColor(old_color))
print(picked_color)
Exemple #26
0
class Elicit:

  def save(self):
    old_filename = self.palette.filename
    self.palette.save()
    if old_filename == None:
      self.gconf.set_string('/apps/elicit/palette', os.path.basename(self.palette.filename))

  def quit(self, widget=None, data=None):
    self.save()
    gtk.main_quit()

  def main(self):
    gtk.main()

  def show(self):
    self.win.show_all()

  def hide(self):
    self.win.hide()

  def grab(self, x, y, w ,h):
    self.mag.grab(x,y,w,h)

  def mag_grid_toggled(self, mag):
    self.grid_check.set_active(mag.show_grid)

  def mag_zoom_changed(self, mag):
    self.gconf.set_int('/apps/elicit/zoom_level', mag.zoom)

  def mag_measure_changed(self, mag):
    if mag.measure_rect:
      text = "[%dx%d] (%.1f diag) " % (mag.measure_rect.width,
          mag.measure_rect.height,
          math.sqrt(mag.measure_rect.width**2 + mag.measure_rect.height**2)
          )
    else:
      text = ""

    self.measure_label.set_text(text)

  def mag_location_changed(self, mag):
    if mag.screen_rect:
      text = "  (%d,%d) %dx%d" % (mag.screen_rect.x, mag.screen_rect.y,
          mag.screen_rect.width, mag.screen_rect.height)
    else:
      text = ""

    self.mag_label.set_text(text)

  def grid_check_toggled(self, check):
    self.gconf.set_bool('/apps/elicit/show_grid', check.get_active())

  def zoom_spin_value_changed(self, spin):
    self.gconf.set_int('/apps/elicit/zoom_level', int(spin.get_value()))

  def picker_save_color(self, picker):
    c = Color()
    c.set_rgb(*picker.color.rgb())
    self.palette.append(c)
    self.palette_view.select(c)
    self.palette.save()

  def palette_view_select_color(self, palette_view, color):
    if color == None:
      self.color_name_entry.set_text("")
      self.color_name_entry.set_sensitive(False)
    else:
      self.gconf.set_string('/apps/elicit/color', color.hex())
      self.color_name_entry.set_text(color.name)
      self.color_name_entry.set_sensitive(True)

  def palette_view_delete_color(self, palette_view, color):
    self.palette.remove(color)
    self.palette.save()

  def color_name_entry_changed(self, color_name_entry):
    if self.palette and self.palette_view.selected:
      self.palette_view.selected.name = color_name_entry.get_text()
      self.palette.save()

  def color_changed(self, color):
    self.colorspin['r'].set_value(self.color.r)
    self.colorspin['g'].set_value(self.color.g)
    self.colorspin['b'].set_value(self.color.b)
    self.colorspin['h'].set_value(self.color.h)
    self.colorspin['s'].set_value(self.color.s)
    self.colorspin['v'].set_value(self.color.v)
    self.hex_entry.set_text(self.color.hex())
    if self.palette_view.selected and color.hex() != self.palette_view.selected.hex():
      self.palette_view.select(None)

    h,s,v = self.color.hsv()
    if self.wheel:
      self.wheel.set_color(h/360.,s,v)
    self.gconf.set_string('/apps/elicit/color', self.color.hex())

  def color_spin_rgb_changed(self, spin):
    r,g,b = self.color.rgb()
    if spin == self.colorspin['r']:
      r = spin.get_value()
    elif spin == self.colorspin['g']:
      g = spin.get_value()
    elif spin == self.colorspin['b']:
      b = spin.get_value()
    self.color.set_rgb(r,g,b)

  def color_spin_hsv_changed(self, spin):
    h,s,v = self.color.hsv()
    if spin == self.colorspin['h']:
      h = spin.get_value()
    elif spin == self.colorspin['s']:
      s = spin.get_value()
    elif spin == self.colorspin['v']:
      v = spin.get_value()
    self.color.set_hsv(h,s,v)

  def hex_entry_changed(self, entry):
    text = entry.get_text()
    if not text: return

    if ((text[0] == '#' and len(text) == 7) or
        (text[0] != '#' and len(text) == 6)):
      try:
        self.color.set_hex(text)
      except ValueError:
        #XXX indicate that the value is bad somehow
        pass

  def palette_combo_selected(self, combo, palette):
    if (self.palette != palette):
      if (palette.filename):
        self.gconf.set_string('/apps/elicit/palette', os.path.basename(palette.filename))
      if self.palette:
        old_filename = self.palette.filename
        self.palette.save()

        #update palette list with new filename
        if old_filename != self.palette.filename:
          index = self.palette_list.index_of_palette(self.palette)
          if index != None:
            self.palette_list[index][1] = self.palette.filename

      self.palette = palette
      self.palette_view.set_palette(self.palette)
      self.color_name_entry.set_sensitive(False)

  def add_palette(self, button):
    p = Palette()
    p.name = "Untitled Palette"
    self.palette_list.append(p)
    self.palette_combo.select(self.palette_list.index_of_palette(p))

  def delete_palette(self, button):
    if not self.palette: return

    d = gtk.MessageDialog(self.win,
        gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
        gtk.BUTTONS_OK_CANCEL, None)

    d.set_markup("Are you sure you want to delete the palette <b>%s</b>? This cannot be undone." % self.palette.name)
    response = d.run()
    d.destroy()
    if response == gtk.RESPONSE_OK:
      p = self.palette
      self.palette_combo.remove(self.palette_list.index_of_palette(p))
      p.delete()

  def select_color_clicked(self, button):
    sel_action = self.actiongroup.get_action("Select Color")
    sel_action.activate()

  def magnify_clicked(self, button):
    mag_action = self.actiongroup.get_action("Magnify")
    mag_action.activate()

  def build_menu(self):
    uimanager = gtk.UIManager()
    accelgroup = uimanager.get_accel_group()
    self.accelgroup = accelgroup
    self.win.add_accel_group(accelgroup)

    actiongroup = gtk.ActionGroup('ElicitActions')
    self.actiongroup = actiongroup

    actiongroup.add_actions([
      ('Quit', gtk.STOCK_QUIT, '_Quit', '<Ctrl>q', 'Quit Elicit', self.action_quit),
      ('Save', gtk.STOCK_QUIT, '_Save Palette', '<Ctrl>s', 'Save Palette', self.action_save),
      ('About', gtk.STOCK_ABOUT, '_About', None, 'About Elicit', self.action_about),
      ('Magnify', gtk.STOCK_ABOUT, '_Magnify', '<Ctrl>z', 'Start Magnifying', self.action_magnify),
      ('Select Color', gtk.STOCK_ABOUT, 'Select _Color', '<Ctrl>d', 'Start Selecting Color', self.action_pick_color),
      ('File', None, '_File'),
      ('Action', None, '_Action'),
      ('Help', None, '_Help')
      ])

    uimanager.insert_action_group(actiongroup)
    uimanager.add_ui_from_string("""
    <ui>
      <menubar name="ElicitMain">
        <menu action="File">
          <menuitem action="Save"/>
          <menuitem action="Quit"/>
        </menu>
        <menu action="Action">
          <menuitem action="Magnify"/>
          <menuitem action="Select Color"/>
        </menu>
        <menu action="Help">
          <menuitem action="About"/>
        </menu>
      </menubar>
    </ui>
    """)
    menubar = uimanager.get_widget("/ElicitMain")
    return menubar

  def build_gui(self):
    self.win = gtk.Window()
    self.win.set_title("Elicit")
    self.win.set_icon_name('rephorm-elicit')
    self.win.connect('destroy', self.quit, None)

    vbox = gtk.VBox(False, 2)
    self.win.add(vbox)

    menubar = self.build_menu()
    vbox.pack_start(menubar, False)

    # notebook with magnifier, etc
    hbox = gtk.HBox(False, 0)
    vbox.pack_start(hbox, True, True)
    notebook = gtk.Notebook()
    self.notebook = notebook
    hbox.pack_start(notebook, True, True, padding=HPAD)

    # magnifier tab
    mag_vbox = gtk.VBox(False, 2)
    mag_tab_icon = gtk.Image()
    mag_tab_icon.set_from_file(os.path.join(self.icon_path, "magnify-16.png"))
    notebook.append_page(mag_vbox, mag_tab_icon)

    # the magnifier
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, True, True)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, True, padding=HPAD)

    self.mag = Magnifier()
    frame.add(self.mag)
    self.mag.connect('zoom-changed', self.mag_zoom_changed)
    self.mag.connect('grid-toggled', self.mag_grid_toggled)
    self.mag.connect('measure-changed', self.mag_measure_changed)
    self.mag.connect('location-changed', self.mag_location_changed)

    # magnifier information (coordinates)
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, False)

    self.mag_label = gtk.Label()
    hbox.pack_start(self.mag_label, False, padding=HPAD)

    self.measure_label = gtk.Label()
    hbox.pack_end(self.measure_label, False)

    # magnifier tools
    hbox = gtk.HBox(False, 0)
    mag_vbox.pack_start(hbox, False)

    button = gtk.Button()
    button.set_relief(gtk.RELIEF_NONE)
    img = gtk.Image()
    img.set_from_file(os.path.join(self.icon_path, "magnify-button.png"));
    button.set_image(img)
    button.set_tooltip_text("Start Magnifying\n(Left Click to stop)")
    button.connect('clicked', self.magnify_clicked);
    hbox.pack_end(button, False, padding=HPAD)

    check = gtk.CheckButton("Show Grid")
    check.set_active(self.mag.show_grid)
    check.connect('toggled', self.grid_check_toggled)
    hbox.pack_start(check, padding=HPAD)
    self.grid_check = check

    spin = gtk.SpinButton()
    spin.set_range(1,50)
    spin.set_increments(1,10)
    spin.set_value(self.mag.zoom)
    spin.connect('value-changed', self.zoom_spin_value_changed)
    hbox.pack_end(spin, False, padding=HPAD)
    self.zoom_spin = spin

    zoom_label = gtk.Label("Zoom:")
    hbox.pack_end(zoom_label, False)

    # color wheel
    wheel_frame = gtk.Frame()
    wheel_tab_icon = gtk.Image()
    wheel_tab_icon.set_from_file(os.path.join(self.icon_path, "color-wheel-16.png"))
    notebook.append_page(wheel_frame, wheel_tab_icon)

    if hasattr(gtk, 'HSV'):
      wheel = gtk.HSV()
      self.wheel = wheel
      wheel_frame.add(wheel)

      wheel_frame.connect('size-allocate', self.wheel_size_allocate)
      wheel_frame.connect('size-request', self.wheel_size_request)
      wheel.connect('changed', self.wheel_changed)
    else:
      self.wheel = None
      label = gtk.Label("The color wheel requires gtk ver. 2.28 or higher.")
      wheel_frame.add(label)

    # swatch and eyedropper button
    hbox = gtk.HBox(False, 0)
    vbox.pack_start(hbox, False)

    button = gtk.Button()
    button.set_relief(gtk.RELIEF_NONE)
    img = gtk.Image()
    img.set_from_file(os.path.join(self.icon_path, "dropper-button.png"));
    button.set_image(img)
    button.set_tooltip_text("Start Selecting Color\n(Left Click to stop)")
    button.connect('clicked', self.select_color_clicked);
    hbox.pack_end(button, False, padding=HPAD)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, True, padding=HPAD)

    self.colorpicker = ColorPicker()
    frame.add(self.colorpicker)
    self.colorpicker.connect('save-color', self.picker_save_color)
    self.colorpicker.set_magnifier(self.mag)

    # color values (sliders and spinboxes)
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    self.colorspin = {}

    table = gtk.Table(6,4)
    hbox.pack_start(table, True, True, padding=HPAD)

    row = 0
    for type in ("r","g","b"):
      label = gtk.Label(type.upper())
      table.attach(label, 0,1,row,row+1,0,0,2,2)
      cslider = CSlider(self.color, type)
      table.attach(cslider, 1,2,row,row+1,gtk.FILL|gtk.EXPAND,gtk.EXPAND,2,2)
      spin = gtk.SpinButton()
      spin.set_range(0,255)
      spin.set_increments(1,10)
      spin.connect('value-changed', self.color_spin_rgb_changed)
      table.attach(spin, 2,3,row,row+1,0,gtk.EXPAND,2,2)
      self.colorspin[type] = spin
      row += 1

    row = 0
    for type in ("h","s","v"):
      label = gtk.Label(type.upper())
      table.attach(label, 3,4,row,row+1,0,0,2,2)
      cslider = CSlider(self.color, type)
      table.attach(cslider, 4,5,row,row+1,gtk.FILL|gtk.EXPAND,gtk.EXPAND,2,2)
      spin = gtk.SpinButton()
      if type == 'h':
        spin.set_range(0,360)
        spin.set_increments(1,10)
      else:
        spin.set_digits(2)
        spin.set_range(0,1.0)
        spin.set_increments(.01,.1)
      spin.connect('value-changed', self.color_spin_hsv_changed)
      table.attach(spin, 5,6,row,row+1,0,gtk.EXPAND,2,2)
      self.colorspin[type] = spin
      row += 1

    self.hex_label = gtk.Label("Hex")
    table.attach(self.hex_label,0,1,3,4,gtk.FILL,gtk.EXPAND,2,2)

    self.hex_entry = gtk.Entry()
    table.attach(self.hex_entry,1,6,3,4,gtk.FILL,gtk.EXPAND,2,2)
    self.hex_entry.connect('changed', self.hex_entry_changed)

    sep = gtk.HSeparator()
    vbox.pack_start(sep, False)

    # palette tools
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    hbox.pack_start(gtk.Label("Palette:"), False, padding=HPAD)

    self.palette_combo = PaletteCombo()
    hbox.pack_start(self.palette_combo)
    self.palette_combo.connect('selected', self.palette_combo_selected)

    button = gtk.Button()
    button.set_image(gtk.image_new_from_stock(gtk.STOCK_ADD,gtk.ICON_SIZE_BUTTON))
    button.set_tooltip_text("Add Palette")
    button.set_relief(gtk.RELIEF_NONE)
    button.connect('clicked', self.add_palette)
    hbox.pack_start(button, False)

    button = gtk.Button()
    button.set_image(gtk.image_new_from_stock(gtk.STOCK_DELETE,gtk.ICON_SIZE_BUTTON))
    button.set_tooltip_text("Delete Palette")
    button.set_relief(gtk.RELIEF_NONE)
    button.connect('clicked', self.delete_palette)
    hbox.pack_start(button, False, padding=HPAD)


    # palette view
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False)

    frame = gtk.Frame()
    frame.set_shadow_type(gtk.SHADOW_IN)
    hbox.pack_start(frame, True, padding=HPAD)

    self.palette_view = PaletteView()
    self.palette_view.connect('select-color', self.palette_view_select_color)
    self.palette_view.connect('delete-color', self.palette_view_delete_color)
    frame.add(self.palette_view)

    # color name entry
    hbox = gtk.HBox(False, 5)
    vbox.pack_start(hbox, False, padding=VPAD)

    hbox.pack_start(gtk.Label("Color Name:"), False, padding=HPAD)

    self.color_name_entry = gtk.Entry()
    self.color_name_entry.set_sensitive(False)
    self.color_name_entry.connect('changed', self.color_name_entry_changed)
    hbox.pack_start(self.color_name_entry, True, True, padding=HPAD)

  def init_config(self):
    self.gconf = gconf.client_get_default()
    self.gconf.add_dir('/apps/elicit', preload=True)
    self.gconf_id = self.gconf.notify_add("/apps/elicit", self.config_changed)

  def load_config(self):
    color = self.gconf.get_string('/apps/elicit/color')
    if color: self.color.set_hex(color)

    zoom_level = self.gconf.get_int('/apps/elicit/zoom_level')
    self.mag.set_zoom(zoom_level)
    self.zoom_spin.set_value(self.mag.zoom)

    grab_rate = self.gconf.get_int('/apps/elicit/grab_rate')
    if grab_rate > 0: self.mag.grab_rate = grab_rate

    show_grid = self.gconf.get_bool('/apps/elicit/show_grid')
    self.mag.set_show_grid(show_grid)
    self.grid_check.set_active(self.mag.show_grid)

    palette = self.gconf.get_string('/apps/elicit/palette')
    if not palette: palette = 'default.gpl'
    index = self.palette_list.index_of_file(palette)
    if index == None:
      index = 0
    self.palette_combo.select(index)

  def wheel_size_allocate(self, frame, allocation):
    style = frame.get_style()
    focus_width = frame.style_get_property('focus-line-width')
    focus_padding = frame.style_get_property('focus-padding')
    size = (min (allocation.width, allocation.height) -
            2 * max (style.xthickness, style.ythickness) -
            2 * (focus_width + focus_padding))

    self.wheel.set_metrics(int(size), int(size / 10))

  def wheel_size_request(self, frame, requisition):
    focus_width = frame.style_get_property('focus-line-width')
    focus_padding = frame.style_get_property('focus-padding')
    requisition.width = 2 * (focus_width + focus_padding)
    requisition.height = 2 * (focus_width + focus_padding)

  def wheel_changed(self, wheel):
    h,s,v = wheel.get_color()
    h *= 360
    self.color.set_hsv(h,s,v)

  def config_changed(self, client, gconf_id, entry, user_data):
    key = entry.key[13:]

    if key == 'color':
      hex = entry.value.get_string()
      self.color.set_hex(hex)
    elif key == 'zoom_level':
      self.mag.set_zoom(entry.value.get_int())
      self.zoom_spin.set_value(self.mag.zoom)
    elif key == 'show_grid':
      self.mag.set_show_grid(entry.value.get_bool())
      self.grid_check.set_active(self.mag.show_grid)
    elif key == 'palette':
      palette = entry.value.get_string()
      if not palette: palette = 'default.gpl'
      self.palette_combo.select(self.palette_list.index_of_file(palette))
    elif key == 'grab_rate':
      self.mag.set_grab_rate(entry.value.get_int())

  def action_quit(self, action):
    self.quit()

  def action_save(self, action):
    self.save()

  def action_about(self, action):
    a = gtk.AboutDialog()
    a.set_name(appinfo.name)
    a.set_version(appinfo.version)
    a.set_website(appinfo.website)
    a.set_authors([appinfo.author])
    a.set_logo_icon_name('rephorm-elicit')

    a.connect('response', lambda dialog,respons: dialog.destroy())
    a.show()

  def action_magnify(self, action):
    if self.mag.grabbing:
      self.mag.grab_stop()

    if self.colorpicker.picking:
      self.colorpicker.pick_stop()

    self.mag.grab_start()

  def action_pick_color(self, action):
    if self.colorpicker.picking:
      self.colorpicker.pick_stop()

    if self.mag.grabbing:
      self.mag.grab_stop()

    self.colorpicker.pick_start()

  def __init__(self):
    self.palette = None
    self.color = Color()
    self.color.connect('changed', self.color_changed)

    self.icon_path = os.path.join(os.path.dirname(__file__), 'data', 'icons')

    self.init_config()
    self.build_gui()

    self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), 'palettes')
    Palette.PaletteDir = self.palette_dir

    self.palette_list = PaletteList()
    self.palette_list.load(self.palette_dir)
    self.palette_combo.set_model(self.palette_list)

    # no palettes, so create default
    if len(self.palette_list) == 0:
      palette = Palette()
      palette.name = "Default Palette"
      palette.filename = os.path.join(self.palette_dir, 'default.gpl')
      self.palette_list.append(palette)

      self.palette_combo.select(0)

    self.colorpicker.set_color(self.color)

    self.load_config()