class Color(Setting):
    def __init__(self, pluginName, name, scope, defaultValue, options={}):

        setGlobal = lambda (value): QSettings(pluginName, pluginName).setValue(
            name, [value.red(),
                   value.green(),
                   value.blue(),
                   value.alpha()])
        setProject = lambda (value): QgsProject.instance().writeEntry(
            pluginName, name, [
                "%u" % value.red(),
                "%u" % value.green(),
                "%u" % value.blue(),
                "%u" % value.alpha()
            ])
        getGlobal = lambda: self.list2color(
            QSettings(pluginName, pluginName).value(name, defaultValue))
        getProject = lambda: self.list2color(QgsProject.instance(
        ).readListEntry(pluginName, name, defaultValue))

        Setting.__init__(self, pluginName, name, scope, defaultValue, options,
                         setGlobal, setProject, getGlobal, getProject)

    def check(self, color):
        if type(color) != QColor:
            raise NameError("Color setting %s must be a QColor." % self.name)

    def setWidget(self, widget):
        txt = self.options.get("dialogTitle", "")
        self.widget = QgsColorButton(widget, txt)
        if self.options.get("alpha", False):
            self.widget.setColorDialogOptions(QColorDialog.ShowAlphaChannel)
        self.signal = "colorChanged"  # TODO: check if signal is working
        self.widgetSetMethod = self.widget.setColor
        self.widgetGetMethod = self.widget.color

    def list2color(self, color):
        if type(color) != list or len(color) != 4:
            return self.defaultValue
        else:
            r = int(color[0])
            g = int(color[1])
            b = int(color[2])
            a = int(color[3])
            if not self.options.get("alpha", False):
                a = 255
        return QColor(r, g, b, a)
class Color(Setting):

    def __init__(self, pluginName, name, scope, defaultValue, options={}):

        setGlobal = lambda(value): QSettings(pluginName, pluginName).setValue(name, [value.red(),
                                                                                     value.green(),
                                                                                     value.blue(),
                                                                                     value.alpha()])
        setProject = lambda(value): QgsProject.instance().writeEntry(pluginName, name,
                                                                     ["%u" % value.red(),
                                                                      "%u" % value.green(),
                                                                      "%u" % value.blue(),
                                                                      "%u" % value.alpha()])
        getGlobal = lambda: self.list2color(QSettings(pluginName, pluginName).value(name, defaultValue))
        getProject = lambda: self.list2color(QgsProject.instance().readListEntry(pluginName, name, defaultValue))

        Setting.__init__(self, pluginName, name, scope, defaultValue, options,
                         setGlobal, setProject, getGlobal, getProject)

    def check(self, color):
        if type(color) != QColor:
            raise NameError("Color setting %s must be a QColor." % self.name)

    def setWidget(self, widget):
        txt = self.options.get("dialogTitle", "")
        self.widget = QgsColorButton(widget, txt)
        if self.options.get("alpha", False):
            self.widget.setColorDialogOptions(QColorDialog.ShowAlphaChannel)
        self.signal = "colorChanged"  # TODO: check if signal is working
        self.widgetSetMethod = self.widget.setColor
        self.widgetGetMethod = self.widget.color

    def list2color(self, color):
        if type(color) != list or len(color) != 4:
            return self.defaultValue
        else:
            r = int(color[0])
            g = int(color[1])
            b = int(color[2])
            a = int(color[3])
            if not self.options.get("alpha", False):
                a = 255
        return QColor(r, g, b, a)
class QgsTextAnnotationDialog(QDialog):
    def __init__(self, item):
        QDialog.__init__(self)
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName(("gridLayout"))
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(("horizontalLayout"))
        self.mFontComboBox = QFontComboBox(self)
        self.mFontComboBox.setObjectName(("mFontComboBox"))
        self.horizontalLayout.addWidget(self.mFontComboBox)
        spacerItem = QSpacerItem(38, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.mFontSizeSpinBox = QSpinBox(self)
        self.mFontSizeSpinBox.setObjectName(("mFontSizeSpinBox"))
        self.horizontalLayout.addWidget(self.mFontSizeSpinBox)
        self.mBoldPushButton = QPushButton(self)
        self.mBoldPushButton.setMinimumSize(QSize(50, 0))
        self.mBoldPushButton.setCheckable(True)
        self.mBoldPushButton.setObjectName(("mBoldPushButton"))
        self.horizontalLayout.addWidget(self.mBoldPushButton)
        self.mItalicsPushButton = QPushButton(self)
        self.mItalicsPushButton.setMinimumSize(QSize(50, 0))
        self.mItalicsPushButton.setCheckable(True)
        self.mItalicsPushButton.setObjectName(("mItalicsPushButton"))
        self.horizontalLayout.addWidget(self.mItalicsPushButton)
        self.mFontColorButton = QgsColorButton(self)
        self.mFontColorButton.setText((""))
        self.mFontColorButton.setAutoDefault(False)
        self.mFontColorButton.setObjectName(("mFontColorButton"))
        self.horizontalLayout.addWidget(self.mFontColorButton)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.mButtonBox = QDialogButtonBox(self)
        self.mButtonBox.setOrientation(Qt.Horizontal)
        self.mButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.mButtonBox.setObjectName(("mButtonBox"))
        self.gridLayout.addWidget(self.mButtonBox, 3, 0, 1, 1)
        self.mTextEdit = QTextEdit(self)
        self.mTextEdit.setObjectName(("mTextEdit"))
        self.gridLayout.addWidget(self.mTextEdit, 1, 0, 1, 1)
        self.mStackedWidget = QStackedWidget(self)
        self.mStackedWidget.setObjectName(("mStackedWidget"))
        self.page = QWidget()
        self.page.setObjectName(("page"))
        self.mStackedWidget.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName(("page_2"))
        self.mStackedWidget.addWidget(self.page_2)
        self.gridLayout.addWidget(self.mStackedWidget, 2, 0, 1, 1)
        self.setLayout(self.gridLayout)
        
        self.mStackedWidget.setCurrentIndex(0)
        QObject.connect(self.mButtonBox, SIGNAL(("accepted()")), self.accept)
        QObject.connect(self.mButtonBox, SIGNAL(("rejected()")), self.reject)
        
        self.setTabOrder(self.mFontComboBox, self.mFontSizeSpinBox)
        self.setTabOrder(self.mFontSizeSpinBox, self.mBoldPushButton)
        self.setTabOrder(self.mBoldPushButton, self.mItalicsPushButton)
        self.setTabOrder(self.mItalicsPushButton, self.mFontColorButton)
        self.setTabOrder(self.mFontColorButton, self.mTextEdit)
        self.setTabOrder(self.mTextEdit, self.mButtonBox)
        
        self.setWindowTitle("Annotation text")
        self.mBoldPushButton.setText("B")
        self.mItalicsPushButton.setText("I")
        
        self.mTextDocument = None
        self.mItem = item
        self.mEmbeddedWidget = QgsAnnotationWidget(self, self.mItem )
        self.mEmbeddedWidget.show()
        self.mStackedWidget.addWidget( self.mEmbeddedWidget )
        self.mStackedWidget.setCurrentWidget( self.mEmbeddedWidget )
        if ( self.mItem != None ):
            self.mTextDocument = self.mItem.document()
            self.mTextEdit.setDocument( self.mTextDocument )
        self.mFontColorButton.setColorDialogTitle(  "Select font color"  )
        self.mFontColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
        self.setCurrentFontPropertiesToGui()
        QObject.connect( self.mButtonBox, SIGNAL("accepted()"), self.applyTextToItem)
#         QObject.connect( self.mFontComboBox, SIGNAL( "currentFontChanged(QFont())"), self.changeCurrentFormat)
        self.mFontComboBox.currentFontChanged.connect(self.changeCurrentFormat)
        QObject.connect( self.mFontSizeSpinBox, SIGNAL( "valueChanged( int )" ), self.changeCurrentFormat ) 
        QObject.connect( self.mBoldPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mItalicsPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mTextEdit, SIGNAL( "cursorPositionChanged()" ), self.setCurrentFontPropertiesToGui )
        
#         QObject.connect( self.mButtonBox, SIGNAL( "accepted()" ), self.applySettingsToItem)
        deleteButton = QPushButton( "Delete" )
        QObject.connect( deleteButton, SIGNAL( "clicked()" ), self.deleteItem )
        self.mButtonBox.addButton( deleteButton, QDialogButtonBox.RejectRole )
    def applyTextToItem(self):
        if ( self.mItem  != None and self.mTextDocument !=None ):
            if ( self.mEmbeddedWidget != None):
                self.mEmbeddedWidget.apply()
            self.mItem.setDocument( self.mTextDocument )
            self.mItem.update()
    def changeCurrentFormat(self):
        newFont = QFont()
        newFont.setFamily( self.mFontComboBox.currentFont().family() )
        #bold
        if ( self.mBoldPushButton.isChecked() ):
            newFont.setBold( True )
        else:
            newFont.setBold( False )
        #italic
        if ( self.mItalicsPushButton.isChecked() ):
            newFont.setItalic( True )
        else:
            newFont.setItalic( False )
        #size
        newFont.setPointSize( self.mFontSizeSpinBox.value() )
        self.mTextEdit.setCurrentFont( newFont )
        #color
        self.mTextEdit.setTextColor( self.mFontColorButton.color() )
        
    def on_mFontColorButton_colorChanged(self, color ):
        self.changeCurrentFormat()
    def setCurrentFontPropertiesToGui(self):
        self.blockAllSignals( True )
        currentFont = self.mTextEdit.currentFont()
        self.mFontComboBox.setCurrentFont( currentFont )
        self.mFontSizeSpinBox.setValue( currentFont.pointSize() )
        self.mBoldPushButton.setChecked( currentFont.bold() )
        self.mItalicsPushButton.setChecked( currentFont.italic() )
        self.mFontColorButton.setColor( self.mTextEdit.textColor() )
        self.blockAllSignals( False )
        
    def blockAllSignals(self, block ):
        self.mFontComboBox.blockSignals( block )
        self.mFontSizeSpinBox.blockSignals( block )
        self.mBoldPushButton.blockSignals( block )
        self.mItalicsPushButton.blockSignals( block )
        self.mFontColorButton.blockSignals( block )
    
    def deleteItem(self):
        scene = self.mItem.scene()
        if ( scene != None ):
            scene.removeItem( self.mItem )
        self.mItem = None
class QgsAnnotationWidget(QWidget):
    def __init__(self, parent, item):
        QWidget.__init__(self, parent)
        self.gridLayout_2 = QGridLayout(self)
        self.gridLayout_2.setObjectName(("gridLayout_2"))
        self.mMapPositionFixedCheckBox = QCheckBox(self)
        self.mMapPositionFixedCheckBox.setObjectName(
            ("mMapPositionFixedCheckBox"))
        self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1)
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName(("gridLayout"))
        self.mFrameColorButton = QgsColorButton(self)
        self.mFrameColorButton.setText((""))
        self.mFrameColorButton.setObjectName(("mFrameColorButton"))
        self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1)
        self.mFrameColorButton.colorChanged.connect(
            self.on_mFrameColorButton_colorChanged)
        self.mBackgroundColorLabel = QLabel(self)
        self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel"))
        self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1)
        self.mMapMarkerLabel = QLabel(self)
        self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel"))
        self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1)
        self.mBackgroundColorButton = QgsColorButton(self)
        self.mBackgroundColorButton.setText((""))
        self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton"))
        self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1)
        self.mBackgroundColorButton.colorChanged.connect(
            self.on_mBackgroundColorButton_colorChanged)
        self.mMapMarkerButton = QPushButton(self)
        self.mMapMarkerButton.setText((""))
        self.mMapMarkerButton.setObjectName(("mMapMarkerButton"))
        self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1)
        self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked)
        self.mFrameWidthLabel = QLabel(self)
        self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel"))
        self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1)
        self.mFrameWidthSpinBox = QDoubleSpinBox(self)
        self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox"))
        self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1)
        self.mFrameColorLabel = QLabel(self)
        self.mFrameColorLabel.setObjectName(("mFrameColorLabel"))
        self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1)
        self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton)
        self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox)

        self.setWindowTitle("QgsAnnotationWidgetBase")
        self.mMapPositionFixedCheckBox.setText("Fixed map position")
        self.mBackgroundColorLabel.setText("Background color")
        self.mMapMarkerLabel.setText("Map marker")
        self.mFrameWidthLabel.setText("Frame width")
        self.mFrameColorLabel.setText("Frame color")
        self.setLayout(self.gridLayout_2)
        self.mItem = item
        if (self.mItem != None):
            self.blockAllSignals(True)

            if (self.mItem.mapPositionFixed()):
                self.mMapPositionFixedCheckBox.setCheckState(Qt.Checked)
            else:
                self.mMapPositionFixedCheckBox.setCheckState(Qt.Unchecked)

            self.mFrameWidthSpinBox.setValue(self.mItem.frameBorderWidth())
            self.mFrameColorButton.setColor(self.mItem.frameColor())
            self.mFrameColorButton.setColorDialogTitle("Select frame color")
            self.mFrameColorButton.setColorDialogOptions(
                QColorDialog.ShowAlphaChannel)
            self.mBackgroundColorButton.setColor(
                self.mItem.frameBackgroundColor())
            self.mBackgroundColorButton.setColorDialogTitle(
                "Select background color")
            self.mBackgroundColorButton.setColorDialogOptions(
                QColorDialog.ShowAlphaChannel)
            self.symbol = self.mItem.markerSymbol()
            if (self.symbol != None):
                self.mMarkerSymbol = self.symbol.clone()
                self.updateCenterIcon()
            self.blockAllSignals(False)

    def apply(self):
        if (self.mItem != None):
            self.mItem.setMapPositionFixed(
                self.mMapPositionFixedCheckBox.checkState() == Qt.Checked)
            self.mItem.setFrameBorderWidth(self.mFrameWidthSpinBox.value())
            self.mItem.setFrameColor(self.mFrameColorButton.color())
            self.mItem.setFrameBackgroundColor(
                self.mBackgroundColorButton.color())
            self.mItem.setMarkerSymbol(self.mMarkerSymbol)
            self.mMarkerSymbol = None  #//item takes ownership
            self.mItem.update()

    def blockAllSignals(self, block):
        self.mMapPositionFixedCheckBox.blockSignals(block)
        self.mMapMarkerButton.blockSignals(block)
        self.mFrameWidthSpinBox.blockSignals(block)
        self.mFrameColorButton.blockSignals(block)

    def on_mMapMarkerButton_clicked(self):
        if (self.mMarkerSymbol == None):
            return
        markerSymbol = self.mMarkerSymbol.clone()
        dlg = QgsSymbolV2SelectorDialog(markerSymbol,
                                        QgsStyleV2.defaultStyle(), None, self)
        if (dlg.exec_() != QDialog.Rejected):
            self.mMarkerSymbol = markerSymbol
            self.updateCenterIcon()

    def on_mFrameColorButton_colorChanged(self, color):
        if (self.mItem == None):
            return
        self.mItem.setFrameColor(color)

    def updateCenterIcon(self):
        if (self.mMarkerSymbol == None):
            return
        icon = QgsSymbolLayerV2Utils.symbolPreviewIcon(
            self.mMarkerSymbol, self.mMapMarkerButton.iconSize())
        self.mMapMarkerButton.setIcon(icon)

    def on_mBackgroundColorButton_colorChanged(self, color):
        if (self.mItem == None):
            return
        self.mItem.setFrameBackgroundColor(color)