class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0

        self.xml_helper = ResultsManagerXMLHelper(toolboxBase=self.toolboxBase)
        self.result_generator = OpusResultGenerator(
            toolboxBase=self.toolboxBase)

        self.result_generator.guiElement = self

        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)

        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)

        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)

        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()

    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))

        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)

        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName(
            'pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()

        QObject.connect(self.pbn_set_esri_storage_location,
                        SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)

    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)

        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText, 'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)

#

    def _setup_definition_widget(self):

        #### setup results group box ####

        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results, 0, 0, 1, 3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results, 0, 3, 1, 10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))

        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators, 1, 1, 1, 13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))

        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)

        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style, 1, 0, 1, 2)

        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep, 1, 2, 1, 1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type, 1, 3, 1, 2)

        ##### setup options group box ####

        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')

        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        QObject.connect(self.co_result_style,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_style_changed)
        QObject.connect(self.co_result_type,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_type_changed)

    def _setup_co_results(self):

        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))

        results = self.xml_helper.get_available_results()

        for result in results:
            name = '%i.%s' % (result['run_id'], result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')

        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')

        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))

    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()

    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return

        self.lw_indicators.addItem(cur_selected)

    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())

    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        available_export_types = ['ESRI table (for loading in ArcGIS)']

        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types

        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)

    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()

        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()

        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()
            self.le_esri_storage_location.show()
            self.gridlayout3.addWidget(self.le_esri_storage_location, 0, 1, 1,
                                       6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location, 0,
                                       7, 1, 1)
            self.optionsGroupBox.show()

    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)

    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))

        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))

        if indicator_names == []:
            print 'no indicators selected'
            return

        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)': 'mapnik_map',
            'Chart (per indicator, spans years)': 'matplotlib_chart',
            'Table (per indicator, spans years)': 'table_per_attribute',
            'Table (per year, spans indicators)': 'table_per_year',
            'ESRI table (for loading in ArcGIS)': 'table_esri'
        }[indicator_type]

        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!' % storage_location
            kwargs['storage_location'] = storage_location

        self.result_manager.addIndicatorForm(indicator_type=indicator_type,
                                             indicator_names=indicator_names,
                                             kwargs=kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(
            self.logFileKey)

    def runErrorFromThread(self, errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
Exemple #2
0
class GUI(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        # Set size of window
        MainWindow.resize(800, 589)
        MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
        MainWindow.setWindowTitle("Text to Kill")
        
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        font = QFont()
        font.setFamily("Times New Roman")
        
        # Main menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.titleLabel = QLabel(self.menuPage)
        self.titleLabel.setGeometry(QtCore.QRect(250, 60, 300, 50))
        font.setPointSize(45)
        self.titleLabel.setFont(font)
        self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.titleLabel.setObjectName("titleLabel")
        self.titleLabel.setText("Text to Kill")
        self.subtitleLabel = QLabel(self.menuPage)
        self.subtitleLabel.setGeometry(QtCore.QRect(100, 140, 600, 40))
        font.setPointSize(25)
        self.subtitleLabel.setFont(font)
        self.subtitleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.subtitleLabel.setObjectName("subtitleLabel")
        self.subtitleLabel.setText("The Murder Mystery Automation System")
        self.createButton = QPushButton(self.menuPage)
        self.createButton.setGeometry(QtCore.QRect(310, 260, 180, 60))
        self.createButton.setObjectName("createButton")
        self.createButton.setText("Create Game")
        self.runButton = QPushButton(self.menuPage)
        self.runButton.setGeometry(QtCore.QRect(310, 350, 180, 60))
        self.runButton.setObjectName("runButton")
        self.runButton.setText("Run Game")
        self.stackedWidget.addWidget(self.menuPage)
        
        # Create page
        self.createPage = QWidget()
        self.createPage.setObjectName("createPage")
        self.createTabWidget = QTabWidget(self.createPage)
        self.createTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))

        self.createTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.createTabWidget.setObjectName("createTabWidget")
        
        # Create game tab
        self.createTab = QWidget()
        self.createTab.setObjectName("createTab")
        self.createDoneButton = QPushButton(self.createTab)
        self.createDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.createDoneButton.setObjectName("createDoneButton")
        self.createDoneButton.setText("Done")
        self.gameNameEdit = QLineEdit(self.createTab)
        self.gameNameEdit.setGeometry(QtCore.QRect(140, 20, 160, 30))
        self.gameNameEdit.setObjectName("gameNameEdit")
        self.gameNameLabel = QLabel(self.createTab)
        self.gameNameLabel.setGeometry(QtCore.QRect(20, 25, 110, 20))

        font.setPointSize(15)
        self.gameNameLabel.setFont(font)
        self.gameNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.gameNameLabel.setObjectName("gameNameLabel")
        self.gameNameLabel.setText("Game name")
        self.line = QFrame(self.createTab)
        self.line.setGeometry(QtCore.QRect(20, 150, 311, 20))
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.addCharLabel = QLabel(self.createTab)
        self.addCharLabel.setGeometry(QtCore.QRect(20, 180, 160, 20))
        
        font.setPointSize(20)
        self.addCharLabel.setFont(font)
        self.addCharLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.addCharLabel.setObjectName("addCharLabel")
        self.addCharLabel.setText("Add Character")
        self.charNameLabel = QLabel(self.createTab)
        self.charNameLabel.setGeometry(QtCore.QRect(20, 230, 66, 20))

        font.setPointSize(15)
        self.charNameLabel.setFont(font)
        self.charNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.charNameLabel.setObjectName("charNameLabel")
        self.charNameLabel.setText("Name")
        self.charNameEdit = QLineEdit(self.createTab)
        self.charNameEdit.setGeometry(QtCore.QRect(140, 220, 160, 30))
        self.charNameEdit.setObjectName("charNameEdit")
        self.charAbilScroll = QListWidget(self.createTab)
        self.charAbilScroll.setGeometry(QtCore.QRect(140, 260, 161, 51))
        self.charAbilScroll.setObjectName("charAbilScroll")
        self.characterTable = QTableWidget(self.createTab)
        self.characterTable.setGeometry(QtCore.QRect(405, 20, 381, 401))
        self.characterTable.setFocusPolicy(QtCore.Qt.NoFocus)
        self.characterTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.characterTable.setRowCount(1)
        self.characterTable.setColumnCount(2)
        self.characterTable.setObjectName("characterTable")
        self.characterTable.horizontalHeader().setVisible(False)
        self.characterTable.horizontalHeader().setCascadingSectionResizes(False)
        self.characterTable.horizontalHeader().setMinimumSectionSize(50)
        self.characterTable.horizontalHeader().setStretchLastSection(True)
        self.characterTable.verticalHeader().setVisible(False)
        self.characterTable.verticalHeader().setDefaultSectionSize(30)
        self.scrollArea = QListWidget(self.createTab)
        self.scrollArea.setGeometry(QtCore.QRect(140, 60, 161, 71))
        self.scrollArea.setObjectName("scrollArea")
        self.scrollArea.setSelectionMode(3)
        self.createSaveButton = QPushButton(self.createTab)
        self.createSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.createSaveButton.setObjectName("createSaveButton")
        self.createSaveButton.setText("Save")
        self.charAbilitiesLabel = QLabel(self.createTab)
        self.charAbilitiesLabel.setGeometry(QtCore.QRect(30, 280, 71, 20))

        font.setPointSize(15)
        self.charAbilitiesLabel.setFont(font)
        self.charAbilitiesLabel.setObjectName("charAbilitiesLabel")
        self.charAbilitiesLabel.setText("Abilities")
        self.abilitiesDropdown = QComboBox(self.createTab)
        self.abilitiesDropdown.setGeometry(QtCore.QRect(140, 330, 151, 25))
        self.abilitiesDropdown.setObjectName("abilitiesDropdown")
        
        self.addCharButton = QPushButton(self.createTab)
        self.addCharButton.setGeometry(QtCore.QRect(30, 370, 98, 27))
        self.addCharButton.setObjectName("addCharButton")
        self.addCharButton.setText("Add")
        self.gameAbilitiesLabel = QLabel(self.createTab)
        self.gameAbilitiesLabel.setGeometry(QtCore.QRect(30, 80, 71, 20))
        
        self.setGameAbilButton = QPushButton(self.createTab)
        self.setGameAbilButton.setGeometry(QtCore.QRect(30, 110, 71, 27))
        self.setGameAbilButton.setObjectName("setGameAbilButton")
        self.setGameAbilButton.setText("Set")
        
        self.saveCharButton = QPushButton(self.createTab)
        self.saveCharButton.setGeometry(QtCore.QRect(70, 430, 180, 60))
        self.saveCharButton.setObjectName("saveCharButton")
        self.saveCharButton.setText("Save Character")

        font.setPointSize(15)
        self.gameAbilitiesLabel.setFont(font)
        self.gameAbilitiesLabel.setObjectName("gameAbilitiesLabel")
        self.gameAbilitiesLabel.setText("Abilities")
        self.createTabWidget.addTab(self.createTab, "")
        
        # Setup tab widget
        self.setupTab = QWidget()
        self.setupTab.setObjectName("setupTab")
        self.setupDoneButton = QPushButton(self.setupTab)
        self.setupDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.setupDoneButton.setObjectName("setupDoneButton")
        self.setupDoneButton.setText("Done")
        self.setupTable = QTableWidget(self.setupTab)
        self.setupTable.setGeometry(QtCore.QRect(20, 20, 750, 400))
        self.setupTable.setFocusPolicy(QtCore.Qt.TabFocus)
        self.setupTable.setRowCount(1)
        self.setupTable.setColumnCount(3)
        self.setupTable.setObjectName("setupTable")
        self.setupTable.horizontalHeader().setVisible(False)
        self.setupTable.horizontalHeader().setCascadingSectionResizes(False)
        self.setupTable.horizontalHeader().setDefaultSectionSize(187)
        self.setupTable.horizontalHeader().setHighlightSections(False)
        self.setupTable.horizontalHeader().setStretchLastSection(True)
        self.setupTable.verticalHeader().setVisible(False)
        self.setupTable.verticalHeader().setHighlightSections(False)
        self.setupSaveButton = QPushButton(self.setupTab)
        self.setupSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.setupSaveButton.setObjectName("setupSaveButton")
        self.setupSaveButton.setText("Save")
        self.createTabWidget.addTab(self.setupTab, "")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.createTab), "Create New Game")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.setupTab), "Set Up Game")
        self.stackedWidget.addWidget(self.createPage)
        
        # Game page
        self.gamePage = QWidget()
        self.gamePage.setObjectName("gamePage")
        self.gameTabWidget = QTabWidget(self.gamePage)
        self.gameTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))
        self.gameTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.gameTabWidget.setObjectName("gameTabWidget")
        self.statusTab = QWidget()
        self.statusTab.setObjectName("statusTab")
        self.startGameButton = QPushButton(self.statusTab)
        self.startGameButton.setGeometry(QtCore.QRect(60, 180, 180, 60))
        self.startGameButton.setObjectName("startGameButton")
        self.startGameButton.setText("Start Game")
        self.endGameButton = QPushButton(self.statusTab)
        self.endGameButton.setGeometry(QtCore.QRect(60, 260, 180, 60))
        self.endGameButton.setObjectName("endGameButton")
        self.endGameButton.setText("End Game")
        self.loadGameLabel = QLabel(self.statusTab)
        self.loadGameLabel.setGeometry(QtCore.QRect(20, 65, 101, 21))

        font.setPointSize(15)
        self.loadGameLabel.setFont(font)
        self.loadGameLabel.setObjectName("loadGameLabel")
        self.loadGameLabel.setText("Load Game")
        self.gameTabWidget.addTab(self.statusTab, "")
        self.logTab = QWidget()
        self.logTab.setObjectName("logTab")
        self.logList = QListWidget(self.logTab)
        self.logList.setGeometry(QtCore.QRect(30, 30, 730, 500))
        self.logList.setObjectName("logList")
        self.gameTabWidget.addTab(self.logTab, "")
        self.inputTab = QWidget()
        self.inputTab.setObjectName("inputTab")
        self.gameTabWidget.addTab(self.inputTab, "")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.statusTab), "Game Status")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.logTab), "Game Log")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.inputTab), "Input")
        self.stackedWidget.addWidget(self.gamePage)
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        self.createTabWidget.setCurrentIndex(0)
        self.gameTabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass
Exemple #3
0
class ListBox(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("ListBox" + str(len(parent.findChildren(ListBox))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(3, 3, 3, 3)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.listBox = QListWidget(self.frameBoxPanel)
        self.listBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.listBox.setFont(font)
        self.listBox.setObjectName(("listBox"))
        # self.listBox.setText("0.0")
        self.hLayoutframeBoxPanel.addWidget(self.listBox)

        self.imageButton = QToolButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        self.listBox.currentRowChanged.connect(self.listBoxChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.captionUnits = ""

        self.hasObject = False

        self.objectList = []
        self.captionLabel.setVisible(False)

    def get_Count(self):
        return self.listBox.count()

    Count = property(get_Count, None, None, None)

    def method_3(self, string_0):
        return self.listBox.row(self.listBox.findItems(string_0)[0])

    def method_11(self, string_0):
        if (self.IsEmpty):
            return "%s%s\t" % (string_0, self.Caption)
        return "%s%s\t%s %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def listBoxChanged(self, index):
        i = index
        self.emit(SIGNAL("Event_0"), self)

    def IndexOf(self, item):
        if isinstance(item, str):
            return self.listBox.row(self.listBox.findItems(item)[0])
        else:
            return self.listBox.row(
                self.listBox.findItems(item.ToString())[0])

    def Contains(self, item):
        compStr = None
        if isinstance(item, str):
            compStr = item
        elif isinstance(item, float) or isinstance(item, int):
            compStr = str(item)
        else:
            compStr = item.ToString()
        for i in range(self.listBox.count()):
            comboItemstr = self.listBox.item(i).text()
            if compStr == comboItemstr:
                return True
        return False

    def Clear(self):
        self.listBox.clear()
        self.objectList = []
        self.hasObject = False

    def Add(self, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.listBox.addItem(item.ToString())
            self.objectList.append(item)
            self.hasObject = True
            return
        self.listBox.addItem(item)
        self.hasObject = False
        return self.listBox.count() - 1

    def Insert(self, index, item):
        if not isinstance(item, str):
            self.listBox.insertItem(index, item.ToString())
            self.objectList.insert(index, item)
            self.hasObject = True
            return
        self.listBox.insertItem(index, item)
        self.hasObject = False

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_3"), self)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if captionStr == "":
            self.captionLabel.setText("")
            self.LabelWidth = 0
            return
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(captionStr + "(" +
                                      str(self.CaptionUnits) + ")" + ":")
        else:
            self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def set_ButtonVisible(self, bool):
        self.imageButton.setVisible(bool)

    ButtonVisible = property(None, set_ButtonVisible, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    #
    # def set_Value(self, value):
    #     try:
    #         self.listBox.setCurrentIndex(value)
    #     except:
    #         self.textBox.setText("")
    # Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.listBox.currentText() == "" or self.listBox.currentIndex() == -1
    # IsEmpty = property(get_IsEmpty, None, None, None)

    # def get_ReadOnly(self):
    #     return self.listBox.isReadOnly()
    # # def set_ReadOnly(self, bool):
    # #     self.listBox.setR.setReadOnly(bool)
    # # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.listBox.setMinimumSize(QSize(width, 0))
        self.listBox.setMaximumSize(QSize(width, 16777215))

    Width = property(None, set_Width, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)

    def get_SelectedIndex(self):
        try:
            return self.listBox.currentRow()
        except:
            return 0

    def set_SelectedIndex(self, index):
        if self.listBox.count() == 0:
            return
        if index > self.listBox.count() - 1:
            self.listBox.setCurrentRow(0)
        else:
            self.listBox.setCurrentRow(index)

    SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    # def set_Value(self, valueStr):
    #     if self.listBox.count() == 0:
    #         return
    #     self.listBox.setCurrentIndex(self.listBox.findText(valueStr))
    # Value = property(get_Value, set_Value, None, None)

    def get_Items(self):
        if self.hasObject:
            return self.objectList
        itemList = []
        if self.listBox.count() > 0:
            for i in range(self.listBox.count()):
                itemList.append(self.listBox.item(i).text())
        return itemList

    def set_AddItems(self, strList):
        if len(strList) != 0 and not isinstance(
                strList[0], str) and not isinstance(strList[0], QString):
            for obj in strList:
                self.listBox.addItem(obj.ToString())
                self.objectList.append(obj)
            self.hasObject = True
            return
        self.listBox.addItems(strList)

    Items = property(get_Items, set_AddItems, None, None)

    def get_Enabled(self):
        return self.listBox.isEnabled()

    def set_Enabled(self, bool):
        self.listBox.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_SelectedItem(self):
        if self.listBox.count() == 0:
            return None
        if self.hasObject:
            return self.objectList[self.SelectedIndex]
        return self.listBox.currentItem().text()

    # def set_SelectedItem(self, val):
    #     index = self.listBox.findText(val)
    #     self.listBox.setCurrentIndex(index)
    SelectedItem = property(get_SelectedItem, None, None, None)
class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0
        
        self.xml_helper = ResultsManagerXMLHelper(toolboxBase = self.toolboxBase)
        self.result_generator = OpusResultGenerator(
                                    toolboxBase = self.toolboxBase)
            
        self.result_generator.guiElement = self
        
        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)
        
        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)
        
        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)
                
        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()
        
    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))
        
        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)
        
        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName('pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()
        
        QObject.connect(self.pbn_set_esri_storage_location, SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)
        
    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)
    
        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText,'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)
        
#
    def _setup_definition_widget(self):
        
        #### setup results group box ####
        
        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results,0,0,1,3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results,0,3,1,10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))
        
        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators,1,1,1,13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))
        
        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)


        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style,1,0,1,2)
                
        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep,1,2,1,1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type,1,3,1,2)

        ##### setup options group box ####
        
        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')
        
        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        
        QObject.connect(self.co_result_style, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_style_changed)
        QObject.connect(self.co_result_type, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_type_changed)

    def _setup_co_results(self):
        
        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))
        
        results = self.xml_helper.get_available_results()
            
        for result in results:
            name = '%i.%s'%(result['run_id'],result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')
        
        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
                
        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')
        
        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))
                    
    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()
        
    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()        
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return
        
        self.lw_indicators.addItem(cur_selected)
        
    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())
        
    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
        
        available_export_types = [
            'ESRI table (for loading in ArcGIS)'
        ]
                
        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types
            
        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)
    
    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()
        
        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()
        
        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()   
            self.le_esri_storage_location.show()   
            self.gridlayout3.addWidget(self.le_esri_storage_location,0,1,1,6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location,0,7,1,1)   
            self.optionsGroupBox.show()   
            
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                                          QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
            
                
    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))
        
        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))
                
        if indicator_names == []:
            print 'no indicators selected'
            return
                
        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)':'mapnik_map',
            'Chart (per indicator, spans years)':'matplotlib_chart',
            'Table (per indicator, spans years)':'table_per_attribute',
            'Table (per year, spans indicators)':'table_per_year',
            'ESRI table (for loading in ArcGIS)':'table_esri'
        }[indicator_type]
        
        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!'%storage_location
            kwargs['storage_location'] = storage_location
        
        self.result_manager.addIndicatorForm(indicator_type = indicator_type,
                                             indicator_names = indicator_names,
                                             kwargs = kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(self.logFileKey)


    def runErrorFromThread(self,errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
class FileSelector(QDialog):

    def __init__(self, parent=None):
        super(FileSelector, self).__init__(parent,
                                           Qt.Dialog | Qt.FramelessWindowHint)
        self.setObjectName("file-selector")
        self._files = {}
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        self.animation = QPropertyAnimation(self.effect, "opacity")
        self.animation.setDuration(1500)
        box = QVBoxLayout(self)
        box.setSpacing(30)
        self.list_of_files = QListWidget()
        self.list_of_files.setObjectName("list-selector")
        box.addWidget(self.list_of_files)
        self.label_path = QLabel()
        box.addWidget(self.label_path)
        self._load_files()

        self.connect(self.list_of_files,
                     SIGNAL("itemSelectionChanged()"),
                     self._update_label)
        self.connect(self.list_of_files,
                     SIGNAL("itemActivated(QListWidgetItem*)"),
                     self._open_file)
        self.connect(self.list_of_files,
                     SIGNAL("itemEntered(QListWidgetItem*)"),
                     self._open_file)

    def _load_files(self):
        """ Carga los archivos abiertos en la lista """

        editor_container = Edis.get_component("principal")
        opened_files = editor_container.opened_files_for_selector()
        for _file in opened_files:
            base_name = os.path.basename(_file)
            self._files[base_name] = _file
            self.list_of_files.addItem(base_name)
        index = editor_container.current_index()
        self.list_of_files.setCurrentRow(index)
        self._update_label()

    def _update_label(self):
        """ Actualiza el QLabel """

        item = self.list_of_files.currentItem()
        show_in_label = self._files.get(item.text())
        self.label_path.setText(show_in_label)

    def _open_file(self, item):
        """ Cambia de archivo en el stacked """

        editor_container = Edis.get_component("principal")
        index = self.list_of_files.row(item)
        editor_container.editor_widget.change_item(index)
        self.close()

    def showEvent(self, event):
        super(FileSelector, self).showEvent(event)
        self.animation.setStartValue(0)
        self.animation.setEndValue(1)
        self.animation.start()