Example #1
0
    def __init__(self, parent, header, device_settings, firmware_settings, *args):
        QDialog.__init__(self, parent, *args)
        self.setGeometry(300, 200, 570, 450)
        self.setWindowTitle("Device information")
        table_model = DeviceInformationTable(self, header, device_settings)
        dev_settings_table = QTableView()
        dev_settings_table.setModel(table_model)

        table_model = DeviceInformationTable(self, header, firmware_settings)
        fw_settings_table = QTableView()
        fw_settings_table.setModel(table_model)

        # set font
        # font = QFont("monospace", 10)
        font = QFont("", 10)
        dev_settings_table.setFont(font)
        fw_settings_table.setFont(font)
        # set column width to fit contents (set font first!)
        dev_settings_table.resizeColumnsToContents()
        fw_settings_table.resizeColumnsToContents()

        tab_view = QTabWidget()
        tab_view.addTab(dev_settings_table, "User settings")
        tab_view.addTab(fw_settings_table, "Firmware settings")

        layout = QVBoxLayout(self)
        layout.addWidget(tab_view)
        self.setLayout(layout)
Example #2
0
class FoamBoundaryWidget(QWidget):
    """boundary_settings is a python dict with varible as key and OrderedDictionary as value"""
    def __init__(self, boundary_settings, parent=None):
        super(FoamBoundaryWidget, self).__init__(parent)

        assert (boundary_settings)  # each variable could have empty dict

        self.tabWidget = QTabWidget()
        self.tabs = OrderedDict()
        for variable in boundary_settings.keys():
            vtab = FoamDictWidget(boundary_settings[variable],
                                  self)  # accept empty or None
            self.tabs[variable] = vtab
            if variable in _VARIABLE_NAMES.keys():
                variable_name = _VARIABLE_NAMES[variable]
            else:
                variable_name = variable
            self.tabWidget.addTab(vtab, variable_name)
        self.tabWidget.resize(300, 300)

        self.myLayout = QVBoxLayout()
        help_text = """keys and values are raw string (without ;) e.g. 'uniform (1 0 0)'
        leave the table empty if do not want to overwrite setting by raw dict in this table
        """
        self.myLayout.addWidget(QLabel(help_text))
        self.myLayout.addWidget(self.tabWidget)
        self.setLayout(self.myLayout)

    def boundarySettings(self):
        _bcs = {}
        for variable in self.tabs:
            _bcs[variable] = self.tabs[variable].dict()
        return _bcs
 def __init__(self, parent=None):
     '''
     Constructor
     '''
     QDialog.__init__(self, parent)
     self._ui = Ui_CreditsDialog()
     self._ui.setupUi(self)
     
     creditsTab = QTabWidget()
     creditSections = info.CREDITS.keys()
     for creditSection in creditSections:
         creditTab = QWidget()
         creditsTab.addTab(creditTab, creditSection)
         vbox = QVBoxLayout(creditTab)
         creditList = ""
         for person in info.CREDITS[creditSection]:
             creditList += ("\n%s [%s]" % (person['name'], person['email']))
         creditLabel = QLabel()
         creditLabel.setStyleSheet("QLabel { background-color : white}")
         creditLabel.setText(creditList)
         creditLabel.setAlignment(Qt.AlignTop | Qt.AlignLeft)
         vbox.addWidget(creditLabel)
     
     vbox = QVBoxLayout()
     vbox.setContentsMargins(0, 0, 0, 0)
     vbox.addWidget(creditsTab)
     self._ui.frame_CreditsTab.setLayout(vbox)
Example #4
0
class FoamBoundaryWidget(QWidget):
    """boundary_settings is a python dict with varible as key and OrderedDictionary as value"""
    def __init__(self, boundary_settings, parent=None):
        super(FoamBoundaryWidget, self).__init__(parent)

        assert (boundary_settings)  # each variable could have empty dict

        self.setWindowTitle("Add raw dict as boundary settings")
        self.tabWidget = QTabWidget()
        self.tabs = OrderedDict()
        for variable in boundary_settings.keys():
            vtab = FoamDictWidget(boundary_settings[variable], self)  # accept empty or None
            self.tabs[variable] = vtab
            if variable in _VARIABLE_NAMES.keys():
                variable_name = _VARIABLE_NAMES[variable]
            else:
                variable_name = variable
            self.tabWidget.addTab(vtab, variable_name)
        self.tabWidget.resize(300,300)  # todo: sizeHint()

        self.myLayout = QVBoxLayout()
        help_text = """keys and values are raw string (without ;) 
e.g. 'uniform (1 0 0)', add all necessary key-value pairs
to overwrite automatically generated boundary settings"""
        self.labelHelpText = QLabel(help_text)
        self.labelHelpText.setWordWrap(True)
        self.myLayout.addWidget(self.labelHelpText)
        self.myLayout.addWidget(self.tabWidget)
        self.setLayout(self.myLayout)

    def boundarySettings(self):
        _bcs = {}
        for variable in self.tabs:
            _bcs[variable] = self.tabs[variable].dict()
        return _bcs
Example #5
0
class MainWindowNurse(QMainWindow):
    def __init__(self, user, parent=None):
        QMainWindow.__init__(self, None)
        self.parent = parent
        self.user = user
        self.crtlDatabase = Nurse.NurseApplication()
        self.initUI()
        self.initLayout()

    def initUI(self):
        posX, posY, sizeW, sizeH = Setting.GEOMETRY_MAINWIDOW
        self.setGeometry(posX, posY, sizeW, sizeH)
        self.setWindowTitle("Nurse window")
        self.setTab()
        self.show()

    def initLayout(self):
        layout = QGridLayout()
        layout.addWidget(self.tabWidget)
        centralWidget = QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

    def setTab(self):
        self.tabWidget = QTabWidget()
        self.tabWidget.setStyleSheet(Setting.SS_TabWidget)
        self.tab1 = Tab1_PatientClass.Tab1Patient(self.user, self)
        self.tabWidget.addTab(self.tab1, "Patient")

    def getPatientByAN(self, AN):
        return self.crtlDatabase.getPatientByAN(AN)

    def getAppointmentByAN(self, AN):
        return self.crtlDatabase.getAppointmentByAN(AN)
    def setup_ui(self):
        """ Construct the UI for the dialog.

        """
        tab_widget = QTabWidget()

        general_widget = QWidget()
        general_layout = QVBoxLayout()

        general_layout.addWidget(self.setup_general_server_group())
        general_widget.setLayout(general_layout)
        tab_widget.addTab(general_widget, 'General')

        advanced_widget = QWidget()
        advanced_layout = QVBoxLayout()

        warning_label = QLabel('Caution: Changing these settings can potentially break the application.')
        warning_label.setStyleSheet('QLabel { color: red; }')
        advanced_layout.addWidget(warning_label)

        advanced_layout.addWidget(self.setup_advanced_server_group())
        advanced_layout.addWidget(self.setup_advanced_storage_group())
        advanced_widget.setLayout(advanced_layout)
        tab_widget.addTab(advanced_widget, 'Advanced')

        layout = QVBoxLayout()
        layout.addWidget(tab_widget)
        self.setLayout(layout)
Example #7
0
class MainWindowRoomManager(QMainWindow):
    def __init__(self, user):
        QMainWindow.__init__(self, None)
        self.initUI()
        self.initLayout()
        self.user = user

    def initUI(self):
        posX, posY, sizeW, sizeH = Setting.GEOMETRY_MAINWIDOW
        self.setGeometry(posX, posY, sizeW, sizeH)
        self.setWindowTitle("RoomManager Main Window")
        self.setTab()
        self.show()

    def initLayout(self):
        layout = QGridLayout()
        layout.addWidget(self.tabWidget)
        centralWidget = QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

    def setTab(self):
        self.tabWidget = QTabWidget()
        self.tabWidget.setStyleSheet(
            "QTabBar::tab { height: 35px; width: 100px; }")
        self.tab1 = Tab1_AllRoomClass.Tab1AllRoom()
        self.tab2 = Tab2_ManagePatientClass.Tab2ManagePatient()
        self.tabWidget.addTab(self.tab1, "Manage Room")
        self.tabWidget.addTab(self.tab2, "Patient")
Example #8
0
 def addTab(self, name ):
     
     newWidget = QWidget()
     layout = QVBoxLayout( newWidget )
     labelEmpty = QLabel(); labelEmpty.setMinimumHeight(5)
     buttonDelete = QPushButton( "Delete Tab" )
     layout.addWidget( labelEmpty )
     layout.addWidget( buttonDelete )
     QTabWidget.addTab( self, newWidget, name )
     
     QtCore.QObject.connect( buttonDelete, QtCore.SIGNAL( 'clicked()' ), self.deleteTab )
Example #9
0
 def addTab(self, name ):
     
     newWidget = QWidget()
     layout = QVBoxLayout( newWidget )
     labelEmpty = QLabel(); labelEmpty.setMinimumHeight(5)
     buttonDelete = QPushButton( "Delete Tab" )
     layout.addWidget( labelEmpty )
     layout.addWidget( buttonDelete )
     QTabWidget.addTab( self, newWidget, name )
     
     QtCore.QObject.connect( buttonDelete, QtCore.SIGNAL( 'clicked()' ), self.deleteTab )
Example #10
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle('Tab Test')
        self.tabs = QTabWidget(self)
        self.setCentralWidget(self.tabs)
        # QMainWindow inherits QWidget, thus it can simply be added as child
        # widget
        tab = ToolbarTabWidget()
        self.tabs.addTab(tab, 'spam')
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle('Tab Test')
        self.tabs = QTabWidget(self)
        self.setCentralWidget(self.tabs)
        # QMainWindow inherits QWidget, thus it can simply be added as child
        # widget
        tab = ToolbarTabWidget()
        self.tabs.addTab(tab, 'spam')
Example #12
0
class Console():
    def __init__(self, targetLayoutContainer):
        self.textarea = QTextEdit()
        self.commits = QListWidget()
        
        self.commits.addAction(QAction('Rollback to this revision', self.commits, triggered=self.rollback))
        self.commits.setContextMenuPolicy(Qt.ActionsContextMenu)
        
        self.widget = QTabWidget()
        self.widget.addTab(self.textarea, 'Log')
        self.widget.addTab(self.commits, 'Commits')
        
        targetLayoutContainer.addWidget(self.widget)
        
    def color(self, module, function, color,  *args):
        print module, function, args
        
        prettyString = '<font color="' + color + '"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))    
        
    def info(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="black"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def error(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="red"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def warn(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="#BE9900"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def set_commits(self, commits):
        self.commits.clear()
        
        for commit in commits:
            self.commits.addItem(commit)
            
    def clear(self):
        self.textarea.clear()
        
    def rollback(self):
        targetCommit = self.commits.currentItem().text().split(' ')[0]
        if QMessageBox.warning(None, 'Rollback to commit?', 'All commits after ' + targetCommit + ' will be lost, proceed?', QMessageBox.Yes, QMessageBox.No) == QMessageBox.Yes:
            rollback(targetCommit)
class MultiRenderPropWidget(QWidget):
	"""
	MultiRenderPropWidget is a widget that is displayed under the multi render
	widget. It contains tabs with some controls for interaction and
	visualization of the combined / multi-volume render widget.
	"""
	def __init__(self, multiRenderController, parent=None):
		super(MultiRenderPropWidget, self).__init__(parent=parent)

		# Two tabs: Visualization and Data info
		self.mixParamWidget = RenderParameterWidget(multiRenderController)
		self.transformParamWidget = TransformationParameterWidget()
		self.registrationHistoryWidget = TransformationHistoryWidget()
		self.slicesTabWidget = RenderSlicerParamWidget(multiRenderController)

		# Create the tab widget
		self.tabWidget = QTabWidget()
		self.tabWidget.addTab(self.mixParamWidget, "Mix")
		self.tabWidget.addTab(self.transformParamWidget, "Transformation")
		self.tabWidget.addTab(self.registrationHistoryWidget, "History")
		self.tabWidget.addTab(self.slicesTabWidget, "Slices")

		layout = QVBoxLayout()
		self.setLayout(layout)
		layout.addWidget(self.tabWidget)

		self.registrationHistoryWidget.setMultiRenderWidget(multiRenderController.multiRenderWidget)
Example #14
0
class ManagerWindow(QMainWindow):
    """
    This is the Add-on Manager's custom window. Not much else to say, really.
    """

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

        # Set the window title and size.
        self.setWindowTitle(self.tr("Add-on Manager"))
        self.setMinimumSize(400, 300)

        # Build the main widget.
        self.tabs = QTabWidget(self)
        self.setCentralWidget(self.tabs)

        # Load up all our tabs.
        for addon_type in sorted(addons.manager._types.keys()):
            tab = AddonTypeTab(addon_type)
            self.tabs.addTab(tab, tab.windowIcon(), tab.windowTitle())

        # Let plugins get in on this.
        plugins.run_signal('opened_addon_manager', self)

        # Icons and Style!
        #style.enable_aero(self)
        self.reload_icons()
        style.style_reloaded.connect(self.reload_icons)
        

    def reload_icons(self):
        """ Reload all of our icons. Which is... one icon. """
        self.setWindowIcon(style.icon('addon-manager'))

    def showRaise(self):
        """ Show and raise the window. """
        self.show()
        self.raise_()
        self.setFocus()

    ##### The Close Event #####################################################

    def closeEvent(self, event):
        """ Disconnect any signals and remove our reference. """
        global _manager_window
        if _manager_window is self:
            _manager_window = None

        style.style_reloaded.disconnect(self.reload_icons)
        plugins.run_signal('closed_addon_manager', self)
Example #15
0
class Menu():
    """Menu management main container"""
    def __init__(self):
        ####
        self.menu_tab_4 = QWidget()
        self.menu_tab_4.setStyleSheet("")
        self.menu_tab_4.setObjectName("menu_tab_4")
        self.horizontalLayout_7 = QHBoxLayout(self.menu_tab_4)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.menu_detail_tabWidget = QTabWidget(self.menu_tab_4)
        self.menu_detail_tabWidget.setObjectName("menu_detail_tabWidget")
        self.weeklytabs = None
        self.add_tabs()
        self.horizontalLayout_7.addWidget(self.menu_detail_tabWidget)
        ####signals and slots && other stuffs
        # self.mainwindow = Ui_MainWindow  # just for the ease of finding the attributes in pycharm
        self.menu_detail_tabWidget.currentChanged.connect(self.change_focus)
        self.menu_tab_4.setFocusPolicy(Qt.StrongFocus)
        self.menu_tab_4.focusInEvent = self.change_focus


    def add_tabs(self):
        """
        :return: adds the tab
        """
        menu = MenuDetails()
        self.menu_detail_tabWidget.addTab(menu.menudetail_tab_1, "&Menu")
        self.weeklytabs = {}
        days = [('monday', 'Monday'),
                ('tuesday', 'Tuesday'),
                ('wednesday', 'Wednesday'),
                ('thursday', 'Thursday'),
                ('friday', 'Friday'),
                ('saturday', 'Saturday'),
                ('sunday', 'Sunday')]
        for n, i in enumerate(days):
            menu = MenuWeekday(day=i[0])
            index = n + 1
            self.weeklytabs[index] = menu
            self.menu_detail_tabWidget.addTab(menu.menudetail_tab_1, i[1])

    def change_focus(self, event=None):
        """
        focus event handler
        """
        wid = self.menu_detail_tabWidget.currentWidget()
        if wid.isVisible():
            wid.setFocus()
Example #16
0
class DefaultsDialog(QWidget):

    def __init__(self, kind, module, parent=None):
        super(DefaultsDialog, self).__init__()
        self.clipboard = parent.clipboard
        self.setWindowTitle("%s : %s" % (kind, module))
        self.setGeometry(0, 0, 500, 500)
        self.move(
            QApplication.desktop().screenGeometry().center() - self.rect().center())
        self.show()
        # Main layout
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.display_tabs = QTabWidget()
        self.display = {}
        for k in ["yaml", "python", "bibliography"]:
            self.display[k] = QTextEdit()
            self.display[k].setLineWrapMode(QTextEdit.NoWrap)
            self.display[k].setFontFamily("mono")
            self.display[k].setCursorWidth(0)
            self.display[k].setReadOnly(True)
            self.display_tabs.addTab(self.display[k], k)
        self.layout.addWidget(self.display_tabs)
        # Fill text
        defaults_txt = get_default_info(
            module, kind, return_yaml=True, fail_if_not_found=True)
        from cobaya.yaml import yaml_load
        self.display["python"].setText(
            "from collections import OrderedDict\n\ninfo = " +
            pformat(yaml_load(defaults_txt)))
        self.display["yaml"].setText(defaults_txt)
        self.display["bibliography"].setText(get_bib_module(module, kind))
        # Buttons
        self.buttons = QHBoxLayout()
        self.close_button = QPushButton('Close', self)
        self.copy_button = QPushButton('Copy to clipboard', self)
        self.buttons.addWidget(self.close_button)
        self.buttons.addWidget(self.copy_button)
        self.close_button.released.connect(self.close)
        self.copy_button.released.connect(self.copy_clipb)
        self.layout.addLayout(self.buttons)

    @Slot()
    def copy_clipb(self):
        self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())
Example #17
0
class SessionDetails(QWidget):
    def __init__(self, parent = None):
        super(SessionDetails, self).__init__(parent)
        self.tabs = QTabWidget(self)
        layout = QVBoxLayout(self)
        layout.addWidget(self.tabs)
        self.setMinimumSize(600, 600)

    def setSession(self, session):
        self.tabs.clear()
        self.tabs.addTab(IntervalPage(session, self), str(session.start_time))

    def setTab(self, tab):
        t = self.tabs.currentWidget()
        t.setTab(tab)

    def addInterval(self, interval):
        self.tabs.addTab(IntervalPage(interval, self), str(interval.timestamp))
Example #18
0
    def __init__(self):
        QWidget.__init__(self)

        self.title = u"Web对象管理"

        # Page
        _page = PageContainer()

        # Window
        _window = ViewWindow()

        # Widget
        _widget = WidgetContainer()

        # 页面 tab
        _tab = QTabWidget()
        _tab.addTab(_page, _page.title)
        _tab.addTab(_window, _window.title)
        _tab.addTab(_widget, _widget.title)

        _tab.setTabPosition(QTabWidget.West)
        _tab.setStyleSheet(get_theme("TabViewWeb"))

        # 测试区
        self.__test = WidgetTest()
        self.__test.setStyleSheet(get_theme("TestWidget"))

        # 主layout
        _layout = QHBoxLayout()
        _layout.addWidget(_tab)
        _layout.addWidget(self.__test)

        _layout.setStretch(0, 5)
        _layout.setStretch(1, 1)

        _layout.setContentsMargins(0, 0, 0, 0)
        _layout.setSpacing(0)

        self.setLayout(_layout)

        # 信号
        _page.sig_selected.connect(self.set_page)
        _widget.sig_selected.connect(self.set_widget)
        self.__test.sig_exec.connect(self.send)
Example #19
0
class MultiRenderPropWidget(QWidget):
    """
	MultiRenderPropWidget is a widget that is displayed under the multi render
	widget. It contains tabs with some controls for interaction and
	visualization of the combined / multi-volume render widget.
	"""
    def __init__(self, multiRenderController, parent=None):
        super(MultiRenderPropWidget, self).__init__(parent=parent)

        # Two tabs: Visualization and Data info
        self.mixParamWidget = RenderParameterWidget(multiRenderController)
        self.transformParamWidget = TransformationParameterWidget()
        self.registrationHistoryWidget = TransformationHistoryWidget()
        self.slicesTabWidget = RenderSlicerParamWidget(multiRenderController)

        # Create the tab widget
        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.mixParamWidget, "Visualization")
        self.tabWidget.addTab(self.registrationHistoryWidget, "History")
        self.tabWidget.addTab(self.slicesTabWidget, "Slices")

        self.currentTabIndex = 0
        self.tabWidget.currentChanged.connect(self.tabIndexChanged)

        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self.tabWidget)

        self.registrationHistoryWidget.setMultiRenderWidget(
            multiRenderController.multiRenderWidget)

    def setTransformTool(self, transformTool):
        if self.tabWidget.indexOf(self.transformParamWidget) < 0:
            self.tabWidget.addTab(self.transformParamWidget, "Transformation")

        self.tabWidget.setCurrentWidget(self.transformParamWidget)
        self.transformParamWidget.setTransformationTool(transformTool)

    def transformToolFinished(self):
        index = self.tabWidget.indexOf(self.transformParamWidget)
        if index >= 0:
            # Restore the last tab index that wasn't the transform tab
            self.tabWidget.setCurrentIndex(self.currentTabIndex)
            self.tabWidget.removeTab(index)

    @Slot(int)
    def tabIndexChanged(self, index):
        transformIndex = self.tabWidget.indexOf(self.transformParamWidget)
        if index != transformIndex:
            self.currentTabIndex = index
class MultiRenderPropWidget(QWidget):
	"""
	MultiRenderPropWidget is a widget that is displayed under the multi render
	widget. It contains tabs with some controls for interaction and
	visualization of the combined / multi-volume render widget.
	"""
	def __init__(self, multiRenderController, parent=None):
		super(MultiRenderPropWidget, self).__init__(parent=parent)

		# Two tabs: Visualization and Data info
		self.mixParamWidget = RenderParameterWidget(multiRenderController)
		self.transformParamWidget = TransformationParameterWidget()
		self.registrationHistoryWidget = TransformationHistoryWidget()
		self.slicesTabWidget = RenderSlicerParamWidget(multiRenderController)

		# Create the tab widget
		self.tabWidget = QTabWidget()
		self.tabWidget.addTab(self.mixParamWidget, "Visualization")
		self.tabWidget.addTab(self.registrationHistoryWidget, "History")
		self.tabWidget.addTab(self.slicesTabWidget, "Slices")

		self.currentTabIndex = 0
		self.tabWidget.currentChanged.connect(self.tabIndexChanged)

		layout = QVBoxLayout()
		self.setLayout(layout)
		layout.addWidget(self.tabWidget)

		self.registrationHistoryWidget.setMultiRenderWidget(multiRenderController.multiRenderWidget)

	def setTransformTool(self, transformTool):
		if self.tabWidget.indexOf(self.transformParamWidget) < 0:
			self.tabWidget.addTab(self.transformParamWidget, "Transformation")
		
		self.tabWidget.setCurrentWidget(self.transformParamWidget)
		self.transformParamWidget.setTransformationTool(transformTool)

	def transformToolFinished(self):
		index = self.tabWidget.indexOf(self.transformParamWidget)
		if index >= 0:
			# Restore the last tab index that wasn't the transform tab
			self.tabWidget.setCurrentIndex(self.currentTabIndex)
			self.tabWidget.removeTab(index)

	@Slot(int)
	def tabIndexChanged(self, index):
		transformIndex = self.tabWidget.indexOf(self.transformParamWidget)
		if index != transformIndex:
			self.currentTabIndex = index
Example #21
0
class Waste():
    """Waste management main container"""
    def __init__(self):
        ####
        self.waste_tab_6 = QWidget()
        self.waste_tab_6.setStyleSheet("")
        self.waste_tab_6.setObjectName("waste_tab_6")
        self.verticalLayout = QVBoxLayout(self.waste_tab_6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.waste_detail_tabWidget = QTabWidget(self.waste_tab_6)
        self.waste_detail_tabWidget.setObjectName("waste_detail_tabWidget")
        self.add_tabs()
        self.verticalLayout.addWidget(self.waste_detail_tabWidget)

        ##signals and slotts && other stuffs
        # self.mainwindow = Ui_MainWindow  # just for the ease of finding the attributes in pycharm
        self.waste_detail_tabWidget.currentChanged.connect(self.change_focus)
        self.waste_tab_6.setFocusPolicy(Qt.StrongFocus)
        self.waste_tab_6.focusInEvent = self.change_focus

    def add_tabs(self):
        """
        :return: adds new tabs
        """
        dish = WasteDish()
        self.waste_detail_tabWidget.addTab(dish.wastedetail_tab_1,
                                           "Dish Waste")
        item = WasteItems()
        self.waste_detail_tabWidget.addTab(item.wastedetail_tab_1,
                                           "Item Waste")

    def change_focus(self, event=None):
        """captures focus to inititate the events for the coprresponding tab"""
        wid = self.waste_detail_tabWidget.currentWidget()
        if wid.isVisible():
            wid.setFocus()
Example #22
0
 def initUI(self):
     textEdit1 = QkLineView(sample=10)
     textEdit2 = QkLineView(sample=100)
     textEdit3 = QkLineView(sample=200)
     tabs = QTabWidget()
     tabs.addTab(textEdit1, "TAB1")
     tabs.addTab(textEdit2, "TAB2")
     tabs.addTab(textEdit3, "TAB3")
     tabs.setMovable(True)
     self.setCentralWidget(tabs)
     exitAct = QAction(QIcon(":pics/exit.PNG"), self.tr("Exit"), self)
     exitAct.setShortcut('Ctrl+Q')
     exitAct.setStatusTip(self.tr('Exit application'))
     exitAct.triggered.connect(self.close)
     self.statusBar()
     menubar = self.menuBar()
     fileMenu = menubar.addMenu(self.tr('&File'))
     fileMenu.addAction(exitAct)
     toolbar = self.addToolBar(self.tr('Exit'))
     toolbar.addAction(exitAct)
     toolbar.addAction(exitAct)
     self.setGeometry(300, 300, 350, 250)
     self.setWindowTitle(self.tr('binkeul main window'))
     self.show()
    def __init__(self, parent, settings):
        QDialog.__init__( self, parent )

        self.settings = settings

        tabWidget = QTabWidget()

        #Representations
        self.repWidget = RepresentationPane(self.settings.get_rep_settings())

        tabWidget.addTab(self.repWidget,'Representations')


        #Network Tab

        self.networkWidget = NetworkPane(self.settings.get_network_settings())
        tabWidget.addTab(self.networkWidget, 'Network')


        self.specWidget = SpecgramPane(self.settings.get_specgram_settings())
        tabWidget.addTab(self.specWidget,'Spectrogram')


        layout = QVBoxLayout()
        layout.addWidget(tabWidget)

        #Accept cancel
        self.acceptButton = QPushButton('Ok')
        self.cancelButton = QPushButton('Cancel')

        self.acceptButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

        hbox = QHBoxLayout()
        hbox.addWidget(self.acceptButton)
        hbox.addWidget(self.cancelButton)
        ac = QWidget()
        ac.setLayout(hbox)
        layout.addWidget(ac)

        self.setLayout(layout)

        self.network_changed = False
        self.rep_changed = False
        self.specgram_changed = False
Example #24
0
    def __init__(self):
        super(Caerus, self).__init__()

        self.exit_cb = None

        self.status_bar = self.statusBar()

        self.exit_app = QAction(self.tr("Exit"), self)

        self.file_menu = self.menuBar().addMenu("&File")
        self.file_menu.addAction(self.exit_app)

        self.employers = Employers(self,
                                   [self.tr("ID"),
                                    self.tr("Name"),
                                    self.tr("Street Address"),
                                    self.tr("City"),
                                    self.tr("State"),
                                    self.tr("Zip Code"),
                                    self.tr("Phone Number"),
                                    self.tr("E-mail Address"),
                                    self.tr("Contact Person")])

        self.employees = Employees(self,
                                   [self.tr("ID"),
                                    self.tr("First Name"),
                                    self.tr("Last Name"),
                                    self.tr("E-mail Address"),
                                    self.tr("Phone Number"),
                                    self.tr("Cell Number"),
                                    self.tr("Street Address"),
                                    self.tr("City"),
                                    self.tr("State"),
                                    self.tr("Zip Code")])

        self.reports = Reports(self)

        context = QTabWidget(self)

        context.addTab(self.employers, self.tr("Workplaces"))
        context.addTab(self.employees, self.tr("Employees"))
        context.addTab(self.reports,   self.tr("Reports"))

        self.setCentralWidget(context)
Example #25
0
class Report():
    """
    The Basic Report Module Class
    """
    def __init__(self):
        ####
        self.report_tab_5 = QWidget()
        self.report_tab_5.setStyleSheet("")
        self.report_tab_5.setObjectName("report_tab_5")
        self.horizontalLayout_8 = QHBoxLayout(self.report_tab_5)
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.report_detail_tabWidget = QTabWidget(self.report_tab_5)
        self.report_detail_tabWidget.setObjectName("report_detail_tabWidget")
        self.add_tabs()
        self.horizontalLayout_8.addWidget(self.report_detail_tabWidget)
        ###signals and slots && other stuffs
        # self.mainwindow = Ui_MainWindow  # just for the ease of finding the attributes in pycharm
        self.report_detail_tabWidget.currentChanged.connect(self.change_focus)
        self.report_tab_5.setFocusPolicy(Qt.StrongFocus)
        self.report_tab_5.focusInEvent = self.change_focus

    def add_tabs(self):
        """
        add new tabs to the table
        """
        employee = EmployeeNew()
        hygiene = Hygiene()
        report = Stock()
        self.report_detail_tabWidget.addTab(employee.employeedetail_tab_1,
                                            'Employee')
        self.report_detail_tabWidget.addTab(hygiene.reporthygiene_tab_2,
                                            'Hygiene')
        self.report_detail_tabWidget.addTab(report.stock_tab_1, 'Stock')

    def change_focus(self, event=None):
        """
        sets focus for the  child widgets
        """
        wid = self.report_detail_tabWidget.currentWidget()
        if wid.isVisible():
            wid.setFocus()
    def __init__(self, client, method):
        super(Tab, self).__init__(None)

        self.client = client
        self.method = method

        horiz = QHBoxLayout(self)
        
        left = QWidget()
        
        horiz.addWidget(left)
        
        layout = QFormLayout(left)
        
        self.fields = []
        for param in method[1]:
            field = QLineEdit()
            self.fields.append(field)
            layout.addRow(param[0], field)

        button = QPushButton("Execute Web Service")
        button.clicked.connect(self.execute)
        layout.addWidget(button)
        
        display = QTabWidget()
        
        self.result = QTextBrowser()
        display.addTab(self.result, "Result")
        
        self.request = QTextBrowser()
        display.addTab(self.request, "Request", )
        
        self.response = QTextBrowser()
        display.addTab(self.response, "Response")
        
        horiz.addWidget(display)
Example #27
0
class StartView(QMainWindow):

    def __init__(self):

        super(StartView, self).__init__()

        self.setWindowTitle("hello")
        self.resize(1024, 768)

        # Menu
        main_menu = self.menuBar()

        self.create = main_menu.addMenu('&Create')
        self.run = main_menu.addMenu('&Run')
        self.report = main_menu.addMenu('&Report')
        self.help = main_menu.addMenu('&Help')

        action_batch = self.create.addAction('&Batch')
        action_case = self.create.addAction('&Case')
        action_data = self.create.addAction('&Data')
        action_web = self.create.addAction('&Web')
        action_run = self.run.addAction('&Run')
        action_test = self.run.addAction('&Test')
        action_report = self.report.addAction('&Report')

        self.connect(action_batch, SIGNAL('triggered()'), self.open_batch)
        self.connect(action_case, SIGNAL('triggered()'), self.open_case)
        self.connect(action_test, SIGNAL('triggered()'), self.open_test)
        self.connect(action_data, SIGNAL('triggered()'), self.open_data)
        self.connect(action_web, SIGNAL('triggered()'), self.open_web_object)
        self.connect(action_run, SIGNAL('triggered()'), self.open_run)
        self.connect(action_report, SIGNAL('triggered()'), self.open_report)

        # Dock
        self.dock_category = DockCategory()  # category widget
        self.dock_log = DockBottom()  # log widget
        self.dock_detail = DockDetail()  # detail widget

        self.__dock_displayed = False

        # center widget
        self.__wid_center = QTabWidget()
        self.setCentralWidget(self.__wid_center)

        self.__wid_center.setStyleSheet(get_theme("TabViewMain"))

        self.__wid_center.setTabsClosable(True)
        self.connect(self.__wid_center, SIGNAL("tabCloseRequested(int)"), self.close_tab)

    def close_tab(self):
        index = self.__wid_center.currentIndex()
        self.__wid_center.removeTab(index)

    def open_data(self):
        _view = ViewDataMag()
        self.__add_tab(_view)

    def open_batch(self):
        _view = ViewBatchDefMag()
        _view.sig_batch_det[dict].connect(self.open_case_select)
        self.__add_tab(_view)

    def open_case(self):
        _view = ViewCaseDefMag()
        _view.sig_case_det[dict].connect(self.open_step)
        self.__add_tab(_view)

    def open_case_select(self, p_data):
        _view = ViewBatchDetMag(p_data)
        self.__add_tab(_view)

    def open_step(self, p_data):
        _view = StepContainer(p_data)
        self.__add_tab(_view)

    def open_web_object(self):
        _view = ViewWebMain()
        self.__add_tab(_view)

    def open_run(self):
        _view = ViewRunMain()
        self.__add_tab(_view)

    def open_report(self):
        _view = ViewReportMain()
        self.__add_tab(_view)

    def open_test(self):
        self.__show_dock()

    def __add_tab(self, p_view):

        self.__wid_center.addTab(p_view, p_view.title)
        self.__wid_center.setCurrentWidget(p_view)

    def __show_dock(self):

        if not self.__dock_displayed:

            self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_log)
            # self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_category)
            # self.addDockWidget(Qt.RightDockWidgetArea, self.dock_detail)
            pass
Example #28
0
class RenderPropWidget(QWidget):
    """
	RenderPropWidget is a widget that is displayed under the render widgets. It
	contains a tabwidget in which information of the data can be displayed and
	in which visualization parameters can be shown. One of the tabs is a
	RenderParameterWidget object.
	"""
    def __init__(self, renderController, parent=None):
        super(RenderPropWidget, self).__init__(parent=parent)

        # Three tabs: Visualization, data info and slices
        self.visParamTabWidget = RenderParameterWidget(renderController)
        self.dataInfoTabWidget = RenderInfoWidget()
        self.slicesTabWidget = RenderSlicerParamWidget(renderController)

        # Create the load dataset widget
        self.loadDataWidget = QWidget()
        self.loadDataButton = QPushButton()
        self.loadDataButton.setText("Load a dataset")

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.loadDataButton)
        self.loadDataWidget.setLayout(layout)

        # Create the tab widget
        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.visParamTabWidget, "Visualization")
        self.tabWidget.addTab(self.slicesTabWidget, "Slices")
        self.tabWidget.addTab(self.dataInfoTabWidget, "Data info")

        self.currentTabIndex = 0
        self.extraTabWidget = None
        self.tabWidget.currentChanged.connect(self.tabIndexChanged)

        layout = QVBoxLayout()
        layout.addWidget(self.loadDataWidget)
        self.setLayout(layout)

    def setFileChangedSignal(self, signal):
        """
		:param signal: Signal that is connected to some file-loading slots.
		:type signal: SIGNAL
		"""
        self.signal = signal
        self.signal.connect(self.setFile)
        self.signal.connect(self.dataInfoTabWidget.setFile)

    def setLoadDataSlot(self, slot):
        """
		The button is connected to the given slot. The slot action should load
		a dataset from disk.

		:type slot: Slot
		"""
        self.loadDataButton.clicked.connect(slot)

    @Slot(basestring)
    def setFile(self, fileName):
        """
		When a file is loaded, the 'load data' button is removed from the widget
		and the actual tabs with parameters are put on screen.
		"""
        layout = self.layout()
        if fileName is None:
            if layout.indexOf(self.tabWidget) != -1:
                # Remove the parameter widgets
                layout.removeWidget(self.tabWidget)
                self.tabWidget.setParent(None)
                # Show the load data button
                layout.addWidget(self.loadDataWidget)
                self.setLayout(layout)
        else:
            if layout.indexOf(self.loadDataWidget) != -1:
                # Remove the load data button
                layout.removeWidget(self.loadDataWidget)
                self.loadDataWidget.setParent(None)
                # Add the parameter widgets
                layout.addWidget(self.tabWidget)
                self.setLayout(layout)

    @Slot(int)
    def tabIndexChanged(self, index):
        transformIndex = self.tabWidget.indexOf(self.extraTabWidget)
        if index != transformIndex:
            self.currentTabIndex = index

    def addTabWidget(self, widget, name):
        self.extraTabWidget = widget
        self.tabWidget.addTab(widget, name)
        self.tabWidget.setCurrentWidget(self.extraTabWidget)

    def removeTabWidget(self):
        if self.extraTabWidget is None:
            return

        index = self.tabWidget.indexOf(self.extraTabWidget)
        if index >= 0:
            # Restore the last tab index that wasn't the transform tab
            self.tabWidget.setCurrentIndex(self.currentTabIndex)
            self.tabWidget.removeTab(index)

        self.extraTabWidget = None
Example #29
0
class FormWidget(FormPage):
    instanceAssigned = Signal(str)
    instanceDeleted = Signal(str)
    instanceSaved = Signal(str)
    exception = Signal(str)

    def __init__(self, parent = None, buttons = FormButtons.EditButtons):
        super(FormWidget, self).__init__(parent)
        self.buildButtonBox(buttons)
        self.tabs = None
        self._tabs = {}

    def buildButtonBox(self, buttons):
        buttonWidget = QGroupBox()
        self.buttonbox = QHBoxLayout(buttonWidget)
        if buttons & FormButtons.DeleteButton:
            self.deletebutton = QPushButton("Delete", self)
            self.deletebutton.clicked.connect(self.deleteInstance)
            self.buttonbox.addWidget(self.deletebutton)
        self.buttonbox.addStretch(1)
        if buttons & FormButtons.ResetButton:
            self.resetbutton = QPushButton("Reset", self)
            self.resetbutton.clicked.connect(self.setInstance)
            self.buttonbox.addWidget(self.resetbutton)
        if buttons & FormButtons.SaveButton:
            self.savebutton = QPushButton("Save", self)
            self.savebutton.clicked.connect(self.save)
            self.buttonbox.addWidget(self.savebutton)
        self.layout().addWidget(buttonWidget)

    def addWidgetToButtonBox(self, widget, *args):
        self.buttonbox.insertWidget(0, widget, *args)

    def addTab(self, widget, title):
        if self.tabs is None:
            self.tabs = QTabWidget(self)
            self.tabs.currentChanged[int].connect(self.tabChanged)

            # Remove stretch at the bottom:
            self._removeStretch()
            self.vbox.addWidget(self.tabs, 1)
        if isinstance(widget, FormPage):
            self.form.addSubLayout(widget.form)
        self.tabs.addTab(widget, title)
        self._tabs[title] = widget
        return widget

    def count(self):
        return self.tabs and self.tabs.count()

    def setTab(self, tab):
        if self.tabs and tab <= self.tabs.count():
            self.tabs.setCurrentIndex(tab)

    def tabChanged(self, ix):
        w = self.tabs.currentWidget()
        if hasattr(w, "selected"):
            w.selected()

    def save(self):
        try:
            self.form.retrieve(self.instance())
            if hasattr(self, "retrieve") and callable(self.retrieve):
                self.retrieve(self.instance())
            self.instanceSaved.emit(str(self.instance.key()))
            self.statusMessage.emit("Saved")
        except:
            self.exception.emit("Save failed...")
        self.setInstance()

    def instance(self):
        return self._instance

    def setInstance(self, instance = None):
        if instance:
            self._instance = instance
        self.form.apply(self.instance())
        if hasattr(self, "assign") and callable(self.assign):
            self.assign(self.instance())
        self.instanceAssigned.emit(str(self.instance().key()))

    def confirmDelete(self):
        return QMessageBox.warning(self, "Are you sure?",
                                   "Are you sure you want to delete this?",
                                    QMessageBox.Cancel | QMessageBox.Ok,
                                    QMessageBox.Cancel) == QMessageBox.Ok

    def onDelete(self):
        try:
            with gripe.db.Tx.begin():
                key = str(self.instance().key())
                if grumble.model.delete(self.instance()):
                    self.instanceDeleted.emit(key)
        except:
            traceback.print_exc()
            self.exception.emit("Delete failed...")

    def deleteInstance(self):
        if self.instance() and self.confirmDelete():
            self.onDelete()
Example #30
0
class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Cobaya input generator for Cosmology")
        self.setGeometry(0, 0, 1500, 1000)
        self.move(
            QApplication.desktop().screenGeometry().center() - self.rect().center())
        self.show()
        # Main layout
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.layout_left = QVBoxLayout()
        self.layout.addLayout(self.layout_left)
        self.layout_output = QVBoxLayout()
        self.layout.addLayout(self.layout_output)
        # LEFT: Options
        self.options = QWidget()
        self.layout_options = QVBoxLayout()
        self.options.setLayout(self.layout_options)
        self.options_scroll = QScrollArea()
        self.options_scroll.setWidget(self.options)
        self.options_scroll.setWidgetResizable(True)
        self.layout_left.addWidget(self.options_scroll)
        titles = odict([
            ["Presets", odict([["preset", "Presets"]])],
            ["Cosmological Model", odict([
                ["theory", "Theory code"],
                ["primordial", "Primordial perturbations"],
                ["geometry", "Geometry"],
                ["hubble", "Hubble parameter constraint"],
                ["matter", "Matter sector"],
                ["neutrinos", "Neutrinos and other extra matter"],
                ["dark_energy", "Lambda / Dark energy"],
                ["bbn", "BBN"],
                ["reionization", "Reionization history"]])],
            ["Data sets", odict([
                ["like_cmb", "CMB experiments"],
                ["like_bao", "BAO experiments"],
                ["like_sn", "SN experiments"],
                ["like_H0", "Local H0 measurements"]])],
            ["Sampler", odict([["sampler", "Samplers"]])]])
        self.combos = odict()
        for group, fields in titles.items():
            group_box = QGroupBox(group)
            self.layout_options.addWidget(group_box)
            group_layout = QVBoxLayout(group_box)
            for a, desc in fields.items():
                self.combos[a] = QComboBox()
                if len(fields) > 1:
                    label = QLabel(desc)
                    group_layout.addWidget(label)
                group_layout.addWidget(self.combos[a])
                self.combos[a].addItems(
                    [text(k, v) for k, v in getattr(input_database, a).items()])
        # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED
        #                if a == "theory":
        #                    # Add Planck-naming checkbox
        #                    self.planck_names = QCheckBox(
        #                        "Keep common parameter names "
        #                        "(useful for fast CLASS/CAMB switching)")
        #                    group_layout.addWidget(self.planck_names)
        # Connect to refreshers -- needs to be after adding all elements
        for field, combo in self.combos.items():
            if field == "preset":
                combo.currentIndexChanged.connect(self.refresh_preset)
            else:
                combo.currentIndexChanged.connect(self.refresh)
        #        self.planck_names.stateChanged.connect(self.refresh_keep_preset)
        # RIGHT: Output + buttons
        self.display_tabs = QTabWidget()
        self.display = {}
        for k in ["yaml", "python", "citations"]:
            self.display[k] = QTextEdit()
            self.display[k].setLineWrapMode(QTextEdit.NoWrap)
            self.display[k].setFontFamily("mono")
            self.display[k].setCursorWidth(0)
            self.display[k].setReadOnly(True)
            self.display_tabs.addTab(self.display[k], k)
        self.layout_output.addWidget(self.display_tabs)
        # Buttons
        self.buttons = QHBoxLayout()
        self.save_button = QPushButton('Save', self)
        self.copy_button = QPushButton('Copy to clipboard', self)
        self.buttons.addWidget(self.save_button)
        self.buttons.addWidget(self.copy_button)
        self.save_button.released.connect(self.save_file)
        self.copy_button.released.connect(self.copy_clipb)
        self.layout_output.addLayout(self.buttons)
        self.save_dialog = QFileDialog()
        self.save_dialog.setFileMode(QFileDialog.AnyFile)
        self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)

    def create_input(self):
        return create_input(
            get_comments=True,
            #           planck_names=self.planck_names.isChecked(),
            **{field: list(getattr(input_database, field).keys())[combo.currentIndex()]
               for field, combo in self.combos.items() if field is not "preset"})

    @Slot()
    def refresh_keep_preset(self):
        self.refresh_display(self.create_input())

    @Slot()
    def refresh(self):
        self.combos["preset"].blockSignals(True)
        self.combos["preset"].setCurrentIndex(0)
        self.combos["preset"].blockSignals(False)
        self.refresh_display(self.create_input())

    @Slot()
    def refresh_preset(self):
        preset = list(getattr(input_database, "preset").keys())[
            self.combos["preset"].currentIndex()]
        info = create_input(
            get_comments=True,
            #            planck_names=self.planck_names.isChecked(),
            preset=preset)
        self.refresh_display(info)
        # Update combo boxes to reflect the preset values, without triggering update
        for k, v in input_database.preset[preset].items():
            if k in [input_database._desc]:
                continue
            self.combos[k].blockSignals(True)
            self.combos[k].setCurrentIndex(
                self.combos[k].findText(
                    text(v, getattr(input_database, k).get(v))))
            self.combos[k].blockSignals(False)

    def refresh_display(self, info):
        try:
            comments = info.pop(input_database._comment, None)
            comments_text = "\n# " + "\n# ".join(comments)
        except (TypeError,  # No comments
                AttributeError):  # Failed to generate info (returned str instead)
            comments_text = ""
        self.display["python"].setText(
            "from collections import OrderedDict\n\ninfo = " +
            pformat(info) + comments_text)
        self.display["yaml"].setText(yaml_dump(info) + comments_text)
        self.display["citations"].setText(prettyprint_citation(citation(info)))

    @Slot()
    def save_file(self):
        ftype = next(k for k, w in self.display.items()
                     if w is self.display_tabs.currentWidget())
        ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)",
                   "citations": "(*.txt)"}[ftype]
        fsuffix = {"yaml": ".yaml", "python": ".py", "citations": ".txt"}[ftype]
        fname, path = self.save_dialog.getSaveFileName(
            self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd())
        if not fname.endswith(fsuffix):
            fname += fsuffix
        with open(fname, "w+") as f:
            f.write(self.display_tabs.currentWidget().toPlainText())

    @Slot()
    def copy_clipb(self):
        self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())
    def __init__(self):
        super(HighwaySimulatorGui, self).__init__()
        centralTab = QTabWidget()
        mainWidget = QWidget()
        self.resultsWidget = HighwayAnalyzeWidget()
        centralTab.addTab(mainWidget, 'Run')
        centralTab.addTab(self.resultsWidget, 'Analyze')
        self.setCentralWidget(centralTab)
        centralLayout = QVBoxLayout()
        #centralLayout.setSpacing(0)
        centralLayout.setAlignment(Qt.AlignTop)
        gridWidget = QWidget()
        gridLayout = QGridLayout()
        gridLayout.setSpacing(0)
        gridWidget.setLayout(gridLayout)
        mainWidget.setLayout(centralLayout)
        self.options = dict()
        # GENERAL
        generalGroup = QGroupBox('General Settings')
        generalGroup.setLayout(QVBoxLayout())
        generalGroup.layout().setSpacing(0)
        self.pathOption = SimpleOption('path','Output Path','/home/thomas/Dropbox/Keio/research/results/')
        generalGroup.layout().addWidget(self.pathOption)
        self.scenarioOption = SimpleComboboxOption('scenario','Scenario',1, False, 'vanet-highway-test-thomas','vanet-highway-scenario2')
        self.scenarioOption.combo.currentIndexChanged[int].connect(self.scenarioChanged)
        generalGroup.layout().addWidget(self.scenarioOption)
        self.options['time'] = SimpleSpinOption('time','Simulation Time (sec.)',1500,True)
        self.options['time'].setRange(0,3000)
        self.options['mix'] = SimpleSpinOption('mix','Percentage of cars compare to trucks (%)',80,True)
        self.options['mix'].setRange(0,100)
        self.options['gap'] = SimpleSpinOption('gap','Average Gap (m.)',5)
        self.options['gap'].setRange(1,2000)
        self.options['lane'] = SimpleSpinOption('lane','Number of Lanes',2,True)
        self.options['lane'].setRange(2,4)
        self.options['spl'] = SimpleSpinOption('spl','Speed Limit (km/h)',130,True)
        self.options['spl'].setRange(1,200)
        for widget in ('time','mix','gap','lane','spl'):
            generalGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(generalGroup,0,0)
        # TRAFFIC
        trafficGroup = QGroupBox('Traffic Settings')
        trafficGroup.setLayout(QVBoxLayout())
        trafficGroup.layout().setSpacing(0)
        # m/s = (km/h)*1000/3600
        self.options['vel1'] = SimpleSpinOption('vel1','Average Speed (km/h)',105,True)
        self.options['vel1'].setRange(5,150)
        self.options['dis'] = SimpleComboboxOption('dis','Speed Distribution Model',3, False, 'Uniform','Exponential','Normal','Log Normal')
        self.options['spstd'] = SimpleSpinOption('spstd','Speed Distribution Variance',1.0)
        self.options['spstd'].setRange(0,50)
        self.options['flow1'] = SimpleSpinOption('flow1','Traffic Flow Mean (veh/s)',1.0)
        self.options['flow1'].setRange(0.1,50.0)
        self.options['std1'] = SimpleSpinOption('std1','Traffic Flow Variance',0.8)
        self.options['std1'].setRange(0.1,50.0)
        self.options['maxflow'] = SimpleSpinOption('maxflow','Traffic Maximum Flow (veh/s)',5)
        self.options['maxflow'].setRange(0.1,50.0)
        # Scenar 2
        self.options['avgdist'] = SimpleSpinOption('avgdist','Average Distance (m)',100)
        self.options['avgdist'].setRange(1,10000)
        self.options['avgspeed'] = SimpleSpinOption('avgspeed','Average Speed (km/h)',105)
        self.options['avgspeed'].setRange(1,10000)
        self.options['despeed'] = SimpleSpinOption('despeed','Desired Speed (km/h)',130)
        self.options['despeed'].setRange(1,10000)
        self.options['ambumaxspeed'] = SimpleSpinOption('ambumaxspeed','Ambu Max Speed (km/h)',165)
        self.options['ambumaxspeed'].setRange(1,10000)
        self.options['ambuinitspeed'] = SimpleSpinOption('ambuinitspeed','Ambu Initial Speed (km/h)',130)
        self.options['ambuinitspeed'].setRange(1,10000)
        for widget in ('vel1','dis','spstd','flow1','std1','maxflow',
                       'avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed'):
            trafficGroup.layout().addWidget(self.options[widget])
        self.scenarioChanged(self.scenarioOption.combo.currentIndex())
        gridLayout.addWidget(trafficGroup,0,1)
        # VANET
        vanetGroup = QGroupBox('VANET Settings')
        vanetGroup.setLayout(QVBoxLayout())
        vanetGroup.layout().setSpacing(0)
#        self.options['prate'] = SimpleSpinOption('prate','Penetration Rate of VANET (%)',100,True)
#        self.options['prate'].setRange(0,100)
        self.options['prate'] = 0 # start with 0
        self.options['pw'] = SimpleSpinOption('pw','Transmission Power (dBm)',21.5)
        self.options['pw'].setRange(10,50)
        #for widget in ('prate','pw'):
        for widget in ('pw',):
            vanetGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(vanetGroup,1,0)
        # BATCH SETTINGS
        batchGroup = QGroupBox("Batch Settings")
        batchGroup.setLayout(QVBoxLayout())
        self.gapPrateOption = SimpleSpinOption('gapPrate', 'VANET percentage rate gap', 10, integer=True)
        self.sameSimuTimesOption = SimpleSpinOption('sameSimuTimes', 'How many times the same simulation', 100, integer=True)
        batchGroup.layout().setSpacing(0)
        batchGroup.layout().addWidget(self.gapPrateOption)
        batchGroup.layout().addWidget(self.sameSimuTimesOption)
        gridLayout.addWidget(batchGroup,1,1)
        # START SIMU
        centralLayout.addWidget(gridWidget)
        self.startButton = QPushButton('START')
        self.startButton.clicked.connect(self.startSimu)
        centralLayout.addWidget(self.startButton)
        self.progressBar    = QProgressBar()
        centralLayout.addWidget(self.progressBar)
        self.shutdownWhenDone = QCheckBox('Shutdown when done')
        self.actionWhenDone = QComboBox()
        self.actionWhenDone.addItems(['When finished... do nothing', 'When finished... shutdown the computer', 'When finished... Re-run the simulations!'])
        self.actionWhenDone.setCurrentIndex(int(QSettings().value('actionWhenDone', 0)))
        centralLayout.addWidget(self.actionWhenDone)
        self.infoLabel = QLabel()
        centralLayout.addWidget(self.infoLabel)
        # LOG
        self.logText = QTextBrowser()
        self.logText.setFont(QFont('Century Gothic', 7))
        centralLayout.addWidget(self.logText)
        self.setWindowTitle('Nishimura Lab | Highway Simulation')
        #self.resize(520,len(self.options)*60+100)
        #self.resultFile = open('/home/thomas/Dropbox/Keio/research/results/summary.txt', 'a')
        #self.resultFile = os.path.join(self.pathOption.getValue(), 'summary.txt')
        self.logFile = os.path.join(self.pathOption.getValue(), 'results_'+os.uname()[1]+'.log')
Example #32
0
class TableFrame(ModuleFrame):
    """This is the Frame class of the TableModule.
    """

    def __init__(self, parent, parent_frame = None, title = None):
        """Like all subclasses of ModuleFrame, the constructor requires:

            parent
                The GUI parent of this frame.

            parent_frame
                The ModuleFrame that is logically the parent to this one.

           Optionally, a title can be passed, but this is not yet in use.

           The Boxfish system handles the creation of ModuleFrames and will
           pass these values and only these values to any ModuleFrame.
        """
        super(TableFrame, self).__init__(parent, parent_frame, title)

        self.selected = []

        self.droppedDataSignal.connect(self.droppedData)
        self.agent.tableUpdateSignal.connect(self.updateTables)
        self.agent.highlightUpdateSignal.connect(self.updateSelection)


    def createView(self):
        """This required function creates the main view container for
           this module, in this case a QTabWidget to hold all the table
           views. The rest of the GUI is handled by the superclass.
        """
        self.tabs = QTabWidget()
        return self.tabs


    @Slot(list, str)
    def droppedData(self, indexList):
        """Overrides the superclass method to send the agent the dropped
           data indices.
        """
        self.agent.addDataIndices(indexList)


    @Slot(list, list, list, list, list)
    def updateTables(self, tables, runs, ids, headers, values):
        """Creates table views.

           tables
               A list of tables for which we have data.

           ids
               A list of lists of the corresponding SubDomain ids for
               each row of each table's returned values.

           headers
               A list of lists of the column names that go with the
               given values for each table.

           values
              A list of list of lists, one for each column of each table.
        """

        # We need to save tables, id_lists for selection later
        self.tables = tables
        self.id_lists = ids

        if tables is None:
            return

        self.tabs.clear() # Get rid of old data

        # For each table, create a table view and populate it with the
        # given values for that table
        for table, run, ids_list, header_list, value_lists \
            in zip(tables, runs, ids, headers, values):
            tableWidget = TableTab(table, run, ids_list, header_list, value_lists)
            tableWidget.idsChanged.connect(self.selectionChanged)
            self.tabs.addTab(tableWidget, table)

    @Slot(list)
    def updateSelection(self, table_highlights):
        """Highlight the given table ids.

           table_highlights
               A list of lists of ids, one per table
        """
        for i, ids in enumerate(table_highlights):
            table = self.tabs.widget(i)
            table.selectRows(ids)


    @Slot(str, str, set)
    def selectionChanged(self, table, run, ids):
        """Pass along the selection information to the agent."""
        self.agent.changeHighlights(table, run, ids)
Example #33
0
class Form(QDialog):

    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.config = Config()
        enable = bool(self.state.model)
        if enable:
            self.config = self.state.model.configs()
        self.setWindowTitle("Options — {}".format(
                            QApplication.applicationName()))
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        for widget in (self.generalPanel.thisLanguageComboBox,
                       self.rulesPanel.thisSortAsRulesBox,
                       self.rulesPanel.thisPageRangeRulesBox):
            widget.setEnabled(enable)
        settings = QSettings()
        self.updateToolTips(bool(int(settings.value(
            Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))


    def createWidgets(self):
        self.generalPanel = OptionsPanels.General.Panel(self.state,
                                                        self.config, self)
        self.rulesPanel = OptionsPanels.Rules.Panel(self.state,
                                                    self.config, self)
        self.displayPanel = OptionsPanels.Display.Panel(self.state,
                                                        self.config, self)
        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.generalPanel, "&1  General")
        self.tabWidget.addTab(self.rulesPanel, "&2  Rules")
        self.tabWidget.addTab(self.displayPanel, "&3  Display")
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append((self.helpButton,
                              "Help on the Options dialog"))
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"),
                                       "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Close</b></p>
<p>Close the dialog, and apply any changes to the index.</p>"""))


    def layoutWidgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.tabWidget)
        layout.addStretch()
        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        buttonBox.addButton(self.closeButton, QDialogButtonBox.AcceptRole)
        layout.addWidget(buttonBox)
        self.setLayout(layout)


    def createConnections(self):
        self.helpButton.clicked.connect(self.help)
        self.closeButton.clicked.connect(self.accept)


    def help(self):
        self.state.help("xix_ref_dlg_options.html")


    def accept(self, *args):
        self.setEnabled(False)
        config = self._acceptOptions()
        if bool(self.state.model):
            model = self.state.model
            model.setConfigs(config)
        super().accept(*args)


    def _acceptOptions(self): # No need to restore focus widget
        config = Config()
        settings = QSettings()

        creator = self.generalPanel.creatorLineEdit.text().strip()
        settings.setValue(Gopt.Key.Creator, creator)
        config.Creator = creator

        initials = self.generalPanel.initialsLineEdit.text().strip()
        settings.setValue(Gopt.Key.Initials, initials)
        config.Initials = initials

        config.PadDigits = self.rulesPanel.thisPadDigitsSpinBox.value()
        config.IgnoreSubFirsts = bool(
            self.rulesPanel.thisIgnoreSubFirstsCheckBox.isChecked())
        config.SuggestSpelled = bool(
            self.rulesPanel.thisSuggestSpelledCheckBox.isChecked())

        highest = self.config.get(Gconf.Key.HighestPageNumber)
        config.HighestPageNumber = (
            self.generalPanel.highestPageSpinBox.value())
        largest = self.config.get(Gconf.Key.LargestPageRange)
        config.LargestPageRange = (
            self.generalPanel.largestPageRangeSpinBox.value())
        most = self.config.get(Gconf.Key.MostPages)
        config.MostPages = self.generalPanel.mostPagesSpinBox.value()

        index = self.rulesPanel.thisSortAsRulesBox.currentIndex()
        name = self.rulesPanel.thisSortAsRulesBox.itemData(index)
        if self.rulesPanel.thisSortAsRules != name:
            with Lib.DisableUI(self):
                self.state.setSortAsRules(name, "Updating Sort As texts",
                                          self.state.window.reportProgress)

        index = self.rulesPanel.thisPageRangeRulesBox.currentIndex()
        name = self.rulesPanel.thisPageRangeRulesBox.itemData(index)
        if self.rulesPanel.thisPageRangeRules != name:
            with Lib.DisableUI(self):
                self.state.setPageRangeRules(
                    name, "Updating Pages texts",
                    self.state.window.reportProgress)

        if (highest != config.HighestPageNumber or
                largest != config.LargestPageRange or
                most != config.MostPages):
            self.state.viewFilteredPanel.requery()

        return config
Example #34
0
class AboutDialog(QDialog):
    """
    Subclass of `QDialog`_

    About Dialog for Embroidermodder.

    .. sphinx_generate_methods_summary::
       AboutDialog
    """
    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(AboutDialog, self).__init__(parent)

        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        if parent:
            self.gImgDir = parent.gImgDir
            self.gIconDir = parent.gIconDir
        elif __name__ == '__main__':
            self.gImgDir = gAppDir + os.sep + 'images'
            self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default'

        # The tiled theme background texture.
        self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png')
        self.bgBrush = QBrush(self.bgLogo)
        self.setWhatsThis(
            self.tr("""\
The background is a tiled image of an actual design that was stitched out during the pre-alpha stage.
It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software.
They have graciously allowed us to use it for the project in whichever way we wish.
We thought it looked so good, that it has become the new theme for Embroidermodder 2.
To check out some of the more interesting embroidery projects they are working on,
visit http://blog.ninapaley.com/"""))

        self.imgLbl = EmbroidermodderLogo(self)

        aboutLbl = QTextBrowser(self)
        aboutLbl.setReadOnly(True)
        aboutLbl.setOpenExternalLinks(True)

        aboutLbl.setText('<b>%s</b>' % '<br>'.join(ABOUT.split('\n')))
        aboutLbl.setWhatsThis(
            self.
            tr('This is the AWESOME people that brought Embroidermodder 2 to life.'
               ))

        # We want very slight opacity of the white background
        # so the seamless texture shows slightly through.
        opacityStyleSheet = """\
        QTextEdit:read-only {
            color: rgb(50, 50, 50);
            font-size: 12px;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 240);
            border: 1px solid rgba(0, 0, 0, 255);
            }
            """

        aboutLbl.setStyleSheet(opacityStyleSheet)
        op = QGraphicsOpacityEffect(aboutLbl)
        op.setOpacity(0.95)
        aboutLbl.setGraphicsEffect(op)

        self.notebook = QTabWidget(self)
        self.notebook.setMinimumWidth(500)
        self.notebook.addTab(aboutLbl, self.tr('About'))
        self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png'))
        self.notebook.setTabIcon(
            1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png'))

        notebookStyleSheet = """\
            QTabWidget::pane { /* The tab widget frame */
                border-top: 1px solid #000000;
                position: absolute;
                top: -0.5em;
            }

            QTabWidget::tab-bar {
                alignment: center;
            }

            /* Style the tab using the tab sub-control. Note that
                it reads QTabBar _not_ QTabWidget */
            QTabBar::tab {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                            stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                            stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
                border: 1px solid #000000;
                /* border-bottom-color: #C2C7CB; */ /* same as the pane color */
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                min-width: 40ex;
                min-height: 5ex;
                padding: 3px;
            }

            QTabBar::tab:selected {
                margin-top: 0px;
                font-size: 16px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #0C6AB0, stop: 0.15 #55C4E6,
                                            stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6,
                                            stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0);
                border: 1px solid #000000;
            }

            QTabBar::tab:!selected:hover {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #888888, stop: 0.15 #BBBBBB,
                                            stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB,
                                            stop: 0.85 #BBBBBB, stop: 1.0 #888888);
                border: 1px solid #000000;
            }

            QTabBar::tab:selected {
                border-color: #000000;
                border-bottom-color: #000000; /* same as pane color */
            }
            """

        self.notebook.setStyleSheet(notebookStyleSheet)
        self.notebook.currentChanged.connect(self.CurrentTabChanged)

        buttonbox = QDialogButtonBox(Qt.Horizontal, self)
        button = QPushButton(self)
        button.setText(self.tr("Oh, Yeah!"))
        button.setWhatsThis(
            self.tr('This is the Oh, Yeah! button!') + '\n' +
            self.tr('Oh, Yeah!'))
        buttonbox.addButton(button, QDialogButtonBox.AcceptRole)
        buttonbox.setCenterButtons(True)
        buttonbox.accepted.connect(self.accept)

        hbLayout1 = QHBoxLayout()
        hbLayout2 = QHBoxLayout()
        vbLayout = QVBoxLayout()
        hbLayout1.addStretch()
        hbLayout1.addWidget(self.imgLbl)
        hbLayout1.addStretch()
        hbLayout2.addStretch()
        hbLayout2.addWidget(self.notebook)
        hbLayout2.addStretch()
        vbLayout.addLayout(hbLayout1)
        vbLayout.addLayout(hbLayout2)
        vbLayout.addWidget(buttonbox)
        self.setLayout(vbLayout)

        self.setWindowTitle(self.tr('About Embroidermodder Version 2.0'))

        QApplication.restoreOverrideCursor(
        )  # TODO/???/PORT# don't mess with the window resize cursors.

    # def __del__(self):
    # """Class destructor"""
    # QApplication.restoreOverrideCursor()

    def CurrentTabChanged(self):
        tt = self.notebook.tabText(self.notebook.currentIndex())
        if tt == self.tr('About'):
            self.imgLbl.paintThisText = 'About'
        elif tt == self.tr('Supporters'):
            self.imgLbl.paintThisText = 'Kickstarter'
        self.imgLbl.repaint()

    def paintEvent(self, event):
        """
        Handles the ``paintEvent`` event for :class:`AboutDialog`.

        :param `event`: A `QPaintEvent`_ to be processed.
        """
        rect = self.rect()

        painter = QPainter(self)
        painter.setRenderHint(painter.SmoothPixmapTransform)

        # Always fill with a solid color first
        painter.fillRect(rect, Qt.white)

        # Then overlay the texture
        painter.fillRect(rect, self.bgBrush)
Example #35
0
class CfdBoundaryWidget(QWidget):
    """ QWidget for adding fluid boundary """
    def __init__(self,
                 object,
                 boundarySettings,
                 physics_model,
                 material_objs,
                 parent=None):
        super(CfdBoundaryWidget, self).__init__(parent)  # for both py2 and py3

        #todo: add title to the task paenl
        self.obj = object
        if self.obj:
            self.BoundarySettings = self.obj.BoundarySettings
        else:  # None, if it is not used in FreeCADGui mode
            self.BoundarySettings = boundarySettings
        # todo
        thermalSettings = {}
        turbulenceSettings = {}

        if within_FreeCADGui:
            self.physics_model = physics_model  # approx solver_object, but slightly different
            if 'Turbulence' not in self.obj.PropertiesList:  # Qingfeng Xia's Cfd module
                self.turbModel = 'kOmegaSST'  # physics_model.TurbulenceModel
            else:  # CfdOF fork
                self.turbModel = (physics_model.TurbulenceModel
                                  if physics_model.Turbulence == 'RANS' or
                                  physics_model.Turbulence == 'LES' else None)

            # compatibility workaround
            if 'Thermal' in self.physics_model.PropertiesList:
                self.hasHeatTransfer = self.physics_model.Thermal != 'None'
            else:  # Qingfeng's Cfd
                if 'HeatTransfering' in self.physics_model.PropertiesList:
                    self.hasHeatTransfer = self.physics_model.HeatTransfering
                else:
                    self.hasHeatTransfer = True

        self.material_objs = material_objs  # volume faction of multiphase flow, should accept None
        """
        ui_path = os.path.join(os.path.dirname(__file__), "TaskPanelCfdFluidBoundary.ui")
        ui_path = os.path.join(os.path.dirname(__file__), "TaskPanelFemConstraintFluidBoundary.ui")
        #self.form = QtUiTools.QUiLoader().load(ui_path)
        self.form = FreeCADGui.PySideUic.loadUi(ui_path)
        """

        self.comboBoundaryType = QComboBox()
        self.comboSubtype = QComboBox()
        self.form = self

        _layout = QVBoxLayout()
        _layout.addWidget(self.comboBoundaryType)
        _layout.addWidget(self.comboSubtype)
        self.labelHelpText = QLabel(
            self.tr('select a proper subtype and input a value'), self)
        self.labelHelpText.setWordWrap(True)
        _layout.addWidget(self.labelHelpText)

        self.tabWidget = QTabWidget()
        self.tabBasicBoundary = QWidget()
        self.tabWidget.addTab(self.tabBasicBoundary, "Basic")
        self.tabTurbulenceBoundary = InputWidget(turbulenceSettings,
                                                 TURBULENCE_CONFIG)
        self.tabWidget.addTab(self.tabTurbulenceBoundary, "Turbulence")
        self.tabThermalBoundary = InputWidget(thermalSettings, THERMAL_CONFIG)
        self.tabWidget.addTab(self.tabThermalBoundary, "Thermal")

        # these 2 are value widgets
        _valueLayout = QHBoxLayout()
        self.inputBoundaryValue = _createInputField()
        self.labelBoundaryValue = QLabel()
        _valueLayout.addWidget(self.labelBoundaryValue)
        _valueLayout.addWidget(self.inputBoundaryValue)
        self.vectorInputWidget = VectorInputWidget([0, 0, 0], self.obj)
        _widgetLayout = QVBoxLayout()
        _widgetLayout.addLayout(_valueLayout)
        _widgetLayout.addWidget(self.vectorInputWidget)
        self.tabBasicBoundary.setLayout(_widgetLayout)

        _layout.addWidget(self.tabWidget)
        self.setLayout(_layout)

        self.form.comboBoundaryType.currentIndexChanged.connect(
            self.comboBoundaryTypeChanged)
        self.form.comboSubtype.currentIndexChanged.connect(
            self.comboSubtypeChanged)

        self.setBoundarySettings(self.BoundarySettings)

    def _getCurrentValueUnit(self):
        bType = BOUNDARY_TYPES[self.form.comboBoundaryType.currentIndex()]
        si = self.form.comboSubtype.currentIndex()
        return SUBTYPE_UNITS[bType][si]

    def boundarySettings(self):
        self.onValueChange(
        )  # currently value change signal has no slot connected
        bc = self.BoundarySettings.copy()
        return bc

    def onValueChange(self):
        if not self.vectorInputWidget.isVisible():
            self.BoundarySettings['BoundaryValue'] = _getInputField(
                self.inputBoundaryValue, self.BoundarySettings['Unit'])
        else:
            self.BoundarySettings[
                'BoundaryValue'] = self.vectorInputWidget.vector()

    def setBoundarySettings(self, settings):
        """ Populate UI, update view from settings"""
        self.form.comboBoundaryType.addItems(BOUNDARY_NAMES)
        _boundaryType = settings['BoundaryType']
        bi = indexOrDefault(BOUNDARY_TYPES, _boundaryType, 0)
        self.form.comboBoundaryType.setCurrentIndex(bi)

        si = indexOrDefault(SUBTYPES[_boundaryType],
                            settings['BoundarySubtype'], 0)
        self.form.comboSubtype.setCurrentIndex(si)

        if 'BoundaryValue' in settings:
            if not hasattr(
                    settings['BoundaryValue'], "__len__"
            ):  # support numpy.array, array, list, tuple, but also string
                self.inputBoundaryValue.setValue(settings['BoundaryValue'])
        else:
            if 'ValueVector' in settings:  # DirectionVector + BoundaryValue
                self.vectorInputWidget.setVector(settings['ValueVector'])
            else:
                self.vectorInputWidget.setVector(settings['BoundaryValue'])

        self.updateValueUi()

    def updateValueUi(self):
        # set value label and unit
        self.labelBoundaryValue.setVisible(False)
        self.inputBoundaryValue.setVisible(False)
        self.vectorInputWidget.setVisible(False)
        unit = self._getCurrentValueUnit()
        bType = BOUNDARY_TYPES[self.form.comboBoundaryType.currentIndex()]
        si = self.form.comboSubtype.currentIndex()
        unit = SUBTYPE_UNITS[bType][si]
        valueName = SUBTYPE_VALUE_NAMES[bType][si]
        if unit == '':
            pass
        elif unit == 'm/s':
            self.vectorInputWidget.setVisible(True)
        else:  # any scalar
            self.labelBoundaryValue.setText("{} [{}]".format(valueName, unit))
            self.inputBoundaryValue.setVisible(True)

    def comboBoundaryTypeChanged(self):
        index = self.form.comboBoundaryType.currentIndex()
        _bType = BOUNDARY_TYPES[index]
        self.form.comboSubtype.clear()
        self.form.comboSubtype.addItems(SUBTYPE_NAMES[_bType])
        self.form.comboSubtype.setCurrentIndex(0)
        self.BoundarySettings['BoundaryType'] = _bType

        if self.obj:
            # Change the color of the boundary condition as the selection is made
            self.obj.BoundarySettings = self.BoundarySettings.copy()
            doc_name = str(self.obj.Document.Name)
            FreeCAD.getDocument(doc_name).recompute()

    def comboSubtypeChanged(self):
        index = self.form.comboBoundaryType.currentIndex()
        _bType = BOUNDARY_TYPES[index]
        subtype_index = self.form.comboSubtype.currentIndex()
        self.form.labelHelpText.setText(
            SUBTYPES_HELPTEXTS[_bType][subtype_index])
        self.BoundarySettings['BoundarySubtype'] = SUBTYPES[_bType][
            subtype_index]
        self.BoundarySettings['Unit'] = self._getCurrentValueUnit()
        #self.BoundarySettings['QuantityName'] = SUBTYPE_NAMES[_bType][subtype_index]
        self.updateValueUi()
Example #36
0
class DetectorsWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        # Variables
        self._tabs = {}
        self._widgets = {}
        self._readonly = False

        # Widgets
        self._wdg_tab = QTabWidget()

        # Layouts
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._wdg_tab)
        self.setLayout(layout)

    def addDetector(self, key, detector):
        if key in self._tabs:
            raise ValueError('Detector with key %s already added' % key)

        clasz = detector.__class__
        wdg_detector = get_widget_class(clasz)()
        wdg_detector.setValue(detector)
        wdg_detector.setReadOnly(self._readonly)
        self._widgets[key] = wdg_detector

        lbl_class = QLabel(clasz.__name__)
        lbl_class.setAlignment(Qt.AlignRight)
        font = lbl_class.font()
        font.setItalic(True)
        lbl_class.setFont(font)

        layout = QVBoxLayout()
        layout.addWidget(lbl_class)
        layout.addWidget(wdg_detector, 1)

        widget = QWidget()
        widget.setLayout(layout)
        index = self._wdg_tab.addTab(widget, key)
        self._tabs[key] = index

    def addDetectors(self, detectors):
        for key in sorted(detectors.keys()):
            self.addDetector(key, detectors[key])

    def removeDetector(self, key):
        index = self._tabs.pop(key)
        self._wdg_tab.removeTab(index)
        del self._widgets[key]

    def clear(self):
        self._wdg_tab.clear()
        self._tabs.clear()
        self._widgets.clear()

    def setReadOnly(self, state):
        self._readonly = state
        for widget in self._widgets.values():
            widget.setReadOnly(state)

    def isReadOnly(self):
        return self._readonly
Example #37
0
class AboutDialog(QDialog):
    """
    About Dialog for Embroidermodder.
    """
    def __init__(self, parent=None):
        """Default class constructor."""
        super(AboutDialog, self).__init__(parent)

        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        if parent:
            self.gImgDir = parent.gImgDir
            self.gIconDir = parent.gIconDir
        elif __name__ == '__main__':
            self.gImgDir = gAppDir + os.sep + 'images'
            self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default'

        # The tiled theme background texture.
        self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png')
        self.bgBrush = QBrush(self.bgLogo)
        self.setWhatsThis(self.tr("""\
The background is a tiled image of an actual design that was stitched out during the pre-alpha stage.
It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software.
They have graciously allowed us to use it for the project in whichever way we wish.
We thought it looked so good, that it has become the new theme for Embroidermodder 2.
To check out some of the more interesting embroidery projects they are working on,
visit http://blog.ninapaley.com/"""))

        self.imgLbl = EmbroidermodderLogo(self)

        aboutLbl = QTextBrowser(self)
        aboutLbl.setReadOnly(True)
        aboutLbl.setOpenExternalLinks(True)
        aboutLbl.setText('<b>%s</b>' % '<br>'.join(__doc__.split('\n')))
        aboutLbl.setWhatsThis(self.tr('This is the AWESOME people that brought Embroidermodder 2 to life.'))

        # We want very slight opacity of the white background
        # so the seamless texture shows slightly through.
        opacityStyleSheet = """\
        QTextEdit:read-only {
            color: rgb(50, 50, 50);
            font-size: 12px;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 240);
            border: 1px solid rgba(0, 0, 0, 255);
            }
            """

        aboutLbl.setStyleSheet(opacityStyleSheet)
        op = QGraphicsOpacityEffect(aboutLbl)
        op.setOpacity(0.95)
        aboutLbl.setGraphicsEffect(op)

        self.notebook = QTabWidget(self)
        self.notebook.setMinimumWidth(500)
        self.notebook.addTab(aboutLbl, self.tr('About'))
        self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png'))
        self.notebook.setTabIcon(1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png'))

        notebookStyleSheet = """\
            QTabWidget::pane { /* The tab widget frame */
                border-top: 1px solid #000000;
                position: absolute;
                top: -0.5em;
            }

            QTabWidget::tab-bar {
                alignment: center;
            }

            /* Style the tab using the tab sub-control. Note that
                it reads QTabBar _not_ QTabWidget */
            QTabBar::tab {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                            stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                            stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
                border: 1px solid #000000;
                /* border-bottom-color: #C2C7CB; */ /* same as the pane color */
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                min-width: 40ex;
                min-height: 5ex;
                padding: 3px;
            }

            QTabBar::tab:selected {
                margin-top: 0px;
                font-size: 16px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #0C6AB0, stop: 0.15 #55C4E6,
                                            stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6,
                                            stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0);
                border: 1px solid #000000;
            }

            QTabBar::tab:!selected:hover {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #888888, stop: 0.15 #BBBBBB,
                                            stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB,
                                            stop: 0.85 #BBBBBB, stop: 1.0 #888888);
                border: 1px solid #000000;
            }

            QTabBar::tab:selected {
                border-color: #000000;
                border-bottom-color: #000000; /* same as pane color */
            }
            """

        self.notebook.setStyleSheet(notebookStyleSheet)
        self.notebook.currentChanged.connect(self.CurrentTabChanged)

        buttonbox = QDialogButtonBox(Qt.Horizontal, self)
        button = QPushButton(self)
        button.setText(self.tr("Oh, Yeah!"))
        button.setWhatsThis(self.tr('This is the Oh, Yeah! button!') + '\n' + self.tr('Oh, Yeah!'))
        buttonbox.addButton(button, QDialogButtonBox.AcceptRole)
        buttonbox.setCenterButtons(True)
        buttonbox.accepted.connect(self.accept)

        hbLayout1 = QHBoxLayout()
        hbLayout2 = QHBoxLayout()
        vbLayout = QVBoxLayout()
        hbLayout1.addStretch()
        hbLayout1.addWidget(self.imgLbl)
        hbLayout1.addStretch()
        hbLayout2.addStretch()
        hbLayout2.addWidget(self.notebook)
        hbLayout2.addStretch()
        vbLayout.addLayout(hbLayout1)
        vbLayout.addLayout(hbLayout2)
        vbLayout.addWidget(buttonbox)
        self.setLayout(vbLayout)

        self.setWindowTitle(self.tr('About Embroidermodder Version 2.0'))

        QApplication.restoreOverrideCursor() # TODO/???/PORT# don't mess with the window resize cursors.

    # def __del__(self):
        # """Class destructor"""
        # QApplication.restoreOverrideCursor()

    def CurrentTabChanged(self):
        tt = self.notebook.tabText(self.notebook.currentIndex())
        if tt == self.tr('About'):
            self.imgLbl.paintThisText = 'About'
        elif tt == self.tr('Supporters'):
            self.imgLbl.paintThisText = 'Kickstarter'
        self.imgLbl.repaint()

    def paintEvent(self, event):
        """
        Handles the ``paintEvent`` event for :class:`AboutDialog`.

        :param `event`: a `QPaintEvent` event to be processed.
        """
        rect = self.rect()

        painter = QPainter(self)
        painter.setRenderHint(painter.SmoothPixmapTransform)

        # Always fill with a solid color first
        painter.fillRect(rect, Qt.white)

        # Then overlay the texture
        painter.fillRect(rect, self.bgBrush)
Example #38
0
class Truss(QMainWindow):
    def __init__(self, parent=None):
        super(Truss, self).__init__(parent)
        self.resize(800, 600)
        self.filename = None
        self.filetuple = None
        self.dirty = False  # Refers to Data Page only.
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        self.tabWidget = QTabWidget(centralwidget)
        self.tab = QWidget()
        font = QFont()
        font.setFamily("Courier 10 Pitch")
        font.setPointSize(12)
        self.tab.setFont(font)
        gridLayout_3 = QGridLayout(self.tab)
        self.plainTextEdit = QPlainTextEdit(self.tab)
        gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QWidget()
        self.tab_2.setFont(font)
        gridLayout_2 = QGridLayout(self.tab_2)
        self.plainTextEdit_2 = QPlainTextEdit(self.tab_2)
        gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 800, 29))
        menu_File = QMenu(menubar)
        self.menu_Solve = QMenu(menubar)
        self.menu_Help = QMenu(menubar)
        self.setMenuBar(menubar)
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.action_New = QAction(self)
        self.actionSave_As = QAction(self)
        self.action_Save = QAction(self)
        self.action_Open = QAction(self)
        self.action_Quit = QAction(self)
        self.action_About = QAction(self)
        self.actionShow_CCPL = QAction(self)
        self.action_Solve = QAction(self)
        self.action_CCPL = QAction(self)
        self.action_Help = QAction(self)
        menu_File.addAction(self.action_New)
        menu_File.addAction(self.action_Open)
        menu_File.addAction(self.actionSave_As)
        menu_File.addAction(self.action_Save)
        menu_File.addSeparator()
        menu_File.addAction(self.action_Quit)
        self.menu_Solve.addAction(self.action_Solve)
        self.menu_Help.addAction(self.action_About)
        self.menu_Help.addAction(self.action_CCPL)
        self.menu_Help.addAction(self.action_Help)
        menubar.addAction(menu_File.menuAction())
        menubar.addAction(self.menu_Solve.menuAction())
        menubar.addAction(self.menu_Help.menuAction())
        self.setWindowTitle("Main Window")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\
                                   "Data Page")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\
                                   "Solution Page")
        menu_File.setTitle("&File")
        self.menu_Solve.setTitle("&Solve")
        self.menu_Help.setTitle("&Help")
        self.tabWidget.setCurrentIndex(0)
        self.action_New.setText("&New")
        self.action_Open.setText("&Open")
        self.actionSave_As.setText("Save &As")
        self.action_Save.setText("&Save")
        self.action_Quit.setText("&Quit")
        self.action_Solve.setText("&Solve")
        self.action_About.setText("&About")
        self.action_CCPL.setText("&CCPL")
        self.action_Help.setText("&Help")
        self.action_Quit.triggered.connect(self.close)
        allToolBar = self.addToolBar("AllToolBar")
        allToolBar.setObjectName("AllToolBar")
        self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\
                        self.action_Save, self.action_Solve,\
                        self.action_Quit ))
        self.action_New.triggered.connect(self.fileNew)
        self.action_Open.triggered.connect(self.fileOpen)
        self.actionSave_As.triggered.connect(self.fileSaveAs)
        self.action_Save.triggered.connect(self.fileSave)
        self.action_Solve.triggered.connect(self.trussSolve)
        self.action_About.triggered.connect(self.aboutBox)
        self.action_CCPL.triggered.connect(self.displayCCPL)
        self.action_Help.triggered.connect(self.help)
        self.plainTextEdit.textChanged.connect(self.setDirty)
        self.action_New = self.editAction(self.action_New, None,\
                            'ctrl+N', 'filenew', 'New File.')
        self.action_Open = self.editAction(self.action_Open, None, 'ctrl+O',
                                           'fileopen', 'Open File.')
        self.actionSave_As = self.editAction(self.actionSave_As,\
                            None, 'ctrl+A', 'filesaveas',\
                            'Save and Name File.')
        self.action_Save = self.editAction(self.action_Save, None, 'ctrl+S',
                                           'filesave', 'Save File.')
        self.action_Solve = self.editAction(self.action_Solve, None, 'ctrl+L',
                                            'solve', 'Solve Structure.')
        self.action_About = self.editAction(self.action_About, None, 'ctrl+B',
                                            'about', 'Pop About Box.')
        self.action_CCPL = self.editAction(self.action_CCPL, None, 'ctrl+G',
                                           'licence', 'Show Licence')
        self.action_Help = self.editAction(self.action_Help, None, 'ctrl+H',
                                           'help', 'Show Help Page.')
        self.action_Quit = self.editAction(self.action_Quit, None, 'ctrl+Q',
                                           'quit', 'Quit the program.')
        self.plainTextEdit_2.setReadOnly(True)

    def setDirty(self):
        '''On change of text in textEdit window, set the flag
        "dirty" to True'''
        index = self.tabWidget.currentIndex()
        if index is not 0:
            return
        if self.dirty:
            return True
        self.dirty = True
        self.updateStatus('self.dirty set to True')

    def clearDirty(self):
        'Clear dirty flag'
        self.dirty = False

    def fileNew(self):
        '''Clear both Data Page and Solution Page.'''
        self.plainTextEdit.setPlainText(' ')
        self.plainTextEdit_2.setPlainText(' ')
        self.clearDirty(self)

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(
                self, "Data Loader - Unsaved Changes", "Save unsaved changes?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                self.clearDirty()
                return self.fileSave()
        return True

    def okRead(self):
        'Pop-up a warning message.'
        reply = QMessageBox.warning(
            self, "Warning",
            '''\nFile Open and Save is possible only in Data Page!
\n\(Use SaveAs for Solution Page)''', QMessageBox.Ok)
        return True

    def fileOpen(self):
        '''Open a file in Data Page (with index == 0)'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        self.filetuple = QFileDialog.getOpenFileName(self,\
                        "Open File", dir, \
                        "Data (*.dat *.txt)\nAll Files (*.*)")
        self.filename = self.filetuple[0]
        fname = self.filename
        #  QFileDialog returns a tuple x with x[0] = file name and
        #  x[1] = type of filter.
        if fname:
            self.loadFile(fname)
            self.filename = fname
            self.updateStatus('New file opened.')

    def loadFile(self, fname=None):
        fl = open(fname)
        text = fl.read()
        self.plainTextEdit.setPlainText(text)
        self.dirty = False

    def fileSave(self):
        '''Save file with current file name.'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return
        if self.filename is None:
            return self.fileSaveAs()
        else:
            flname = self.filename
            if flname:
                try:
                    with open(flname, 'w') as fl:
                        fl.write(tempText)
                    self.dirty = False
                    self.updateStatus('File saved.')
                except IOError:
                    self.dirty = True
                    self.updateStatus('File not saved.')
                    return False
                return True
            else:
                self.updateStatus('Failed to save... ')
                return False
        self.filename = None
        self.dirty = False

    def fileSaveAs(self):
        '''Save file with a new name.'''
        qpr = self.qprintline
        fname = self.filename if self.filename is not None else\
        "NoName"
        self.filetuple = QFileDialog.getSaveFileName(
            self, "Truss program - Save File", fname, "Data File (*.*)")
        flname = self.filetuple[0]
        index = self.tabWidget.currentIndex()
        if index == 0:
            self.filename = flname
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit.toPlainText()
                fl.write(tempText)
                fl.close()
                self.dirty = False
                self.updateStatus('File saved.')
        elif index == 1:
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit_2.toPlainText()
                fl.write(tempText)
                fl.close()

    def trussSolve(self):
        '''Solve a statically determinate truss, specified in
        Data Page and display the results in the Solution Page.
        To start, make a copy of the Data Page with a header all
        shown on the Data Page.'''
        printline = self.qprintline
        dataBall = self.plainTextEdit.toPlainText()
        self.plainTextEdit_2.clear()
        printline('================================')
        flbase = os.path.basename(self.filename)
        printline('SOLUTION FOR ' + flbase)
        printline('================================')
        dataBall = self.plainTextEdit.toPlainText()
        ncrunch.main(printline, self.filename, dataBall)

    def aboutBox(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PySide, Platform and the like",
                """<b>Part of Structural Analysis.</b> v %s
                <p>Copyright &copy; 2011 Algis Kabaila. 
                All rights reserved in accordance with
                Creative Commons Attribution Licence (CCPL) v3
                or later - NO WARRANTIES!
                <p>This progam finds bar forces in 
                statically determinate trusses.                
                <p>Python %s -  PySide version %s - Qt version %s on\
                %s""" % (__version__, platform.python_version(),\
                PySide.__version__,  PySide.QtCore.__version__,
                platform.system()))

    def displayCCPL(self):
        '''Read and display CCPL licence.'''
        self.plainTextEdit.setPlainText(open('CCPL.txt').read())
        self.dirty = False
        self.filename = 'COPYING.txt'
        self.updateStatus('CCPL displayed.')

    def help(self):
        '''Read and display a help file- currently the README.txt.'''
        self.plainTextEdit.setPlainText(open('README.md').read())
        self.dirty = False
        self.filename = 'README.txt'
        self.updateStatus('README displayed.')

    def addActions(self, target, actions):
        '''Actions are added to Tool Bar.'''
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def editAction(self,
                   action,
                   slot=None,
                   shortcut=None,
                   icon=None,
                   tip=None):
        '''This method adds to action: icon, shortcut, ToolTip,\
        StatusTip and can connect triggered action to slot '''
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % (icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        return action

    def qreadline(self, lineNo):
        '''Read one line from Data Page (lineNo starts with 0)'''
        return str(self.plainTextEdit.document().\
            findBlockByLineNumber(lineNo).text()).rstrip()

    def qprintline(self, line):
        '''Append one line to Solution Page.'''
        self.plainTextEdit_2.appendPlainText(line.rstrip())

    def updateStatus(self, message):
        '''Keep status current.'''
        if self.filename is not None:
            flbase = os.path.basename(self.filename)
            self.setWindowTitle(str("Truss Analysis - " +\
                                         flbase + "[*]") )
            self.statusBar().showMessage(message, 5000)
            self.setWindowModified(self.dirty)
class RenderPropWidget(QWidget):
    """
	RenderPropWidget is a widget that is displayed under the render widgets. It
	contains a tabwidget in which information of the data can be displayed and
	in which visualization parameters can be shown. One of the tabs is a
	RenderParameterWidget object.
	"""

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

        # Three tabs: Visualization, data info and slices
        self.visParamTabWidget = RenderParameterWidget(renderController)
        self.dataInfoTabWidget = RenderInfoWidget()
        self.slicesTabWidget = RenderSlicerParamWidget(renderController)

        # Create the load dataset widget
        self.loadDataWidget = QWidget()
        self.loadDataButton = QPushButton()
        self.loadDataButton.setText("Load a dataset")

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.loadDataButton)
        self.loadDataWidget.setLayout(layout)

        # Create the tab widget
        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.visParamTabWidget, "Visualization")
        self.tabWidget.addTab(self.dataInfoTabWidget, "Data info")
        self.tabWidget.addTab(self.slicesTabWidget, "Slices")

        layout = QVBoxLayout()
        layout.addWidget(self.loadDataWidget)
        self.setLayout(layout)

    def setFileChangedSignal(self, signal):
        """
		:param signal: Signal that is connected to some file-loading slots.
		:type signal: SIGNAL
		"""
        self.signal = signal
        self.signal.connect(self.setFile)
        self.signal.connect(self.dataInfoTabWidget.setFile)

    def setLoadDataSlot(self, slot):
        """
		The button is connected to the given slot. The slot action should load
		a dataset from disk.

		:type slot: Slot
		"""
        self.loadDataButton.clicked.connect(slot)

    @Slot(basestring)
    def setFile(self, fileName):
        """
		When a file is loaded, the 'load data' button is removed from the widget
		and the actual tabs with parameters are put on screen.
		"""
        layout = self.layout()
        if fileName is None:
            if layout.indexOf(self.tabWidget) != -1:
                # Remove the parameter widgets
                layout.removeWidget(self.tabWidget)
                self.tabWidget.setParent(None)
                # Show the load data button
                layout.addWidget(self.loadDataWidget)
                self.setLayout(layout)
        else:
            if layout.indexOf(self.loadDataWidget) != -1:
                # Remove the load data button
                layout.removeWidget(self.loadDataWidget)
                self.loadDataWidget.setParent(None)
                # Add the parameter widgets
                layout.addWidget(self.tabWidget)
                self.setLayout(layout)
Example #40
0
class STMainWindow(QMainWindow):
    def __init__(self):
        super(STMainWindow, self).__init__()
        self.createActions()
        self.createMenus()
        layout = QVBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.setTabPosition(QTabWidget.West)
        self.tabs.currentChanged[int].connect(self.tabChanged)
        self.sessiontab = sweattrails.qt.sessiontab.SessionTab(self)
        self.tabs.addTab(self.sessiontab, "Sessions")
        self.tabs.addTab(sweattrails.qt.fitnesstab.FitnessTab(self),
                         "Fitness")
        self.tabs.addTab(sweattrails.qt.profiletab.ProfileTab(self),
                         "Profile")
        self.usertab = sweattrails.qt.usertab.UserTab(self)
        self.tabs.addTab(self.usertab, "Users")
        self.usertab.hide()
        layout.addWidget(self.tabs)
        w = QWidget(self)
        w.setLayout(layout)
        self.setCentralWidget(w)
        self.statusmessage = QLabel()
        self.statusmessage.setMinimumWidth(200)
        self.statusBar().addPermanentWidget(self.statusmessage)
        self.progressbar = QProgressBar()
        self.progressbar.setMinimumWidth(100)
        self.progressbar.setMinimum(0)
        self.progressbar.setMaximum(100)
        self.statusBar().addPermanentWidget(self.progressbar)
        self.setWindowTitle("SweatTrails")
        self.setWindowIconText("SweatTrails")
        icon = QPixmap("image/sweatdrops.png")
        self.setWindowIcon(QIcon(icon))
        QCoreApplication.instance().refresh.connect(self.userSet)


    def createActions(self):
        self.switchUserAct = QAction("&Switch User", self, shortcut = "Ctrl+U", statusTip = "Switch User", triggered = self.switch_user)
        self.importFileAct = QAction("&Import", self, shortcut = "Ctrl+I", statusTip = "Import Session", triggered = self.file_import)
        self.downloadAct = QAction("&Download", self, shortcut = "Ctrl+D",
                                   statusTip = "Download activities from device",
                                   triggered = QCoreApplication.instance().download)
        self.downloadAct = QAction("&Withings", self,
                                   statusTip = "Download Withings data",
                                   triggered = QCoreApplication.instance().withings)
        self.exitAct = QAction("E&xit", self, shortcut = "Ctrl+Q", statusTip = "Exit SweatTrails", triggered = self.close)

        self.aboutAct = QAction("&About", self, triggered = self.about)
        self.aboutQtAct = QAction("About &Qt", self, triggered = QApplication.aboutQt)


    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
        self.fileMenu.addAction(self.switchUserAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.importFileAct)
        self.fileMenu.addAction(self.downloadAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        self.helpMenu.addAction(self.aboutQtAct)


    def show(self):
        super(QMainWindow, self).show()
        if self.select_user():
            t = sweattrails.qt.imports.BackgroundThread.get_thread()
            t.jobStarted.connect(self.status_message)
            t.jobFinished.connect(self.status_message)
            t.jobError.connect(self.status_message)
        else:
            self.close()

    def switch_user(self):
        pass

    def select_user(self):
        ret = False
        if QCoreApplication.instance().user:
            return True
        elif QCoreApplication.instance().has_users():
            dialog = SelectUser(self)
            dialog.select()
            ret = QCoreApplication.instance().is_authenticated()
            if ret:
                self.refresh()
        else:
            dialog = CreateUser(self)
            dialog.exec_()
            ret = QCoreApplication.instance().is_authenticated()
            if ret:
                self.refresh()
        return ret

    #
    # FILE IMPORT
    #

    def file_import(self):
        (fileNames, _) = QFileDialog.getOpenFileNames(self,
                               "Open Activity File",
                               "",
                               "Activity Files (*.tcx *.fit *.csv)")
        if fileNames:
            QCoreApplication.instance().import_files(*fileNames)

    def file_import_started(self, filename):
        self.switchUserAct.setEnabled(False)

    def file_imported(self, filename):
        self.switchUserAct.setEnabled(True)
        self.refresh()

    def file_import_error(self, filename, msg):
        self.switchUserAct.setEnabled(True)
        self.refresh()

    #
    # END FILE IMPORT
    #

    # =====================================================================
    # S I G N A L  H A N D L E R S
    # =====================================================================

    def refresh(self):
        QCoreApplication.instance().refresh.emit()
        self.status_message("")

    def tabChanged(self, tabix):
        w = self.tabs.currentWidget()
        if hasattr(w, "activate"):
            w.activate(0)
        if hasattr(w, "setValues"):
            w.setValues()

    def setSession(self, session):
        self.tabs.setCurrentIndex(0)
        self.sessiontab.setSession(session)

    def setTab(self, tab):
        t = self.tabs.currentWidget()
        if t and hasattr(t, "setTab"):
            t.setTab(tab)

    def userSet(self):
        user = QCoreApplication.instance().user
        if user.is_admin():
            self.usertab.show()

    def status_message(self, msg, *args):
        self.statusmessage.setText(msg.format(*args))

    def progress_init(self, msg, *args):
        self.progressbar.setValue(0)
        self.status_message(msg, *args)

    def progress(self, percentage):
        self.progressbar.setValue(percentage)

    def progress_done(self):
        self.progressbar.reset()

    def about(self):
        QMessageBox.about(self, "About SweatTrails",
                          "SweatTrails is a training log application")
Example #41
0
class LimitsWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        # Variables
        self._tabs = {}
        self._widgets = {}
        self._readonly = False

        # Widgets
        self._wdg_tab = QTabWidget()

        # Layouts
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._wdg_tab)
        self.setLayout(layout)

    def addLimit(self, limit):
        clasz = limit.__class__
        if clasz in self._tabs:
            raise ValueError('Limit (%s) already added' % clasz.__name__)

        wdg_limit = get_widget_class(clasz)()
        wdg_limit.setValue(limit)
        wdg_limit.setReadOnly(self._readonly)
        self._widgets[clasz] = wdg_limit

        layout = QVBoxLayout()
        layout.addWidget(wdg_limit, 1)

        widget = QWidget()
        widget.setLayout(layout)

        class_name = camelcase_to_words(clasz.__name__)
        index = self._wdg_tab.addTab(widget, class_name)
        self._tabs[clasz] = index

    def addLimits(self, limits):
        for limit in limits:
            self.addLimit(limit)

    def removeLimit(self, limit):
        clasz = limit.__class__
        index = self._tabs.pop(clasz)
        self._wdg_tab.removeTab(index)
        del self._widgets[clasz]

    def clear(self):
        self._wdg_tab.clear()
        self._tabs.clear()
        self._widgets.clear()

    def setReadOnly(self, state):
        self._readonly = state
        for widget in self._widgets.values():
            widget.setReadOnly(state)

    def isReadOnly(self):
        return self._readonly
Example #42
0
class MainWindowNurse(QMainWindow):
    def __init__(self, user, parent=None):
        QMainWindow.__init__(self, None)
        self.nurse_app = Nurse.NurseApplication()
        self.parent = parent
        self.user = user
        self.initUI()
        self.initLayout()

    def initUI(self):
        posX, posY, sizeW, sizeH = Setting.GEOMETRY_MAINWIDOW
        self.setGeometry(posX, posY, sizeW, sizeH)
        self.setWindowTitle("Nurse window")
        self.setTab()
        self.show()

    def initLayout(self):
        layout = QGridLayout()
        layout.addWidget(self.tabWidget)
        centralWidget = QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

    def setTab(self):
        self.tabWidget = QTabWidget()
        self.tabWidget.setStyleSheet(Setting.SS_TabWidget)
        self.tab1 = Tab1_PatientClass.Tab1Patient(self.user, self)
        self.tabWidget.addTab(self.tab1, "Patient")

    def getPatientByAN(self, AN):
        return self.nurse_app.getPatientByAN(AN)

    def getAppointmentByAN(self, AN):
        return self.nurse_app.getAppointmentByAN(AN)

    def deleteButtonPressed(self, AN):
        title = "Confirm deleting"
        text_info = "Delete this Patient"
        question = "Do you sure to delete " + str(AN)
        dialog = ConfirmMsgClass.ConfirmYesNo(title, text_info, question)
        if dialog.ans:
            patients = self.nurse_app.getPatientFromDatabase()
            appointments = self.nurse_app.getAppointmentFromDatabase()
            for patient in patients:
                if patient.AN == AN:
                    patients.remove(patient)
                    self.nurse_app.updatePatientDatabase(patients)
                    self.tab1.updateTable()
                    break
            for appointment in appointments:
                if appointment.patient.AN == AN:
                    appointments.remove(appointment)
                    self.nurse_app.updateAppointmentDatabase(appointments)
                    break
        else:
            pass

    def updatePatient(self, patient):
        return self.nurse_app.editPatient(patient)

    def createHistory(self, new_history_report):
        self.nurse_app.createHistory(new_history_report)
Example #43
0
class MainWindow(QtGui.QMainWindow):
    _instance = None
    tabPanel = None
    
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle('Portfolio Viewer')
        self.resize(1300, 900)
        self.createMenu()
        self.setCentralWidget(self.createTabWidget()) 
        self.show()
         
    def createTabWidget(self):
        self.tabPanel = QTabWidget()
        self.tabPanel.addTab(self.createPositionPanel(), "Position")
        self.tabPanel.addTab(self.createCorporateEventPanel(), "Corporate Event")
        self.tabPanel.addTab(self.createPnLPanel(), "PnL")
        self.tabPanel.addTab(self.createReportMovementPanel(), "Report Movement")
        self.tabPanel.addTab(self.createImporterMovementPanel(), "Import Movement")
        return self.tabPanel
    
    def createCorporateEventPanel(self):
        self.corpEventPanel = CorporateEventPanel()
        return self.corpEventPanel
        
    def createPositionPanel(self):
        self.positionPanel = PositionPanel()
        return self.positionPanel
        
    def createPnLPanel(self):
        self.pnLPanel = PnLPanel()
        return self.pnLPanel
    
    def createReportMovementPanel(self):
        self.reportMovementPanel = ReportMovementPanel()
        return self.reportMovementPanel
    
    def createImporterMovementPanel(self):
        self.importerMovement = ImportMovementPanel()
        return self.importerMovement
    
    def createMenu(self):
        self.fileMenu = self.menuBar().addMenu("&Add")
        self.actionOpenMovementEditor = QtGui.QAction("&Add movement", self, checkable=True,
            shortcut="Ctrl+M", statusTip="Add movement",
            triggered=self.openMovementEditor)
        self.fileMenu.addAction(self.actionOpenMovementEditor)
        self.actionOpenCorporateEventEditor = QtGui.QAction("&Add corporate event", self, checkable=True,
            shortcut="Ctrl+E", statusTip="Add movement",
            triggered=self.openCorporateEventEditor)
        self.fileMenu.addAction(self.actionOpenCorporateEventEditor)
        self.fileMenu = self.menuBar().addMenu("&Dump")
        self.actionExportDump = QtGui.QAction("&Export Dump", self, checkable=True,
            statusTip="Export Dumpt",
            triggered=self.exportAllDump)
        self.fileMenu.addAction(self.actionExportDump)

    def openMovementEditor(self):
        self.movementEditor = MovementEditor()
        self.movementEditor.show()
    
    def openCorporateEventEditor(self):
        self.corporateEditor = CorporateEventEditor()
        self.corporateEditor.show()
        
    def exportAllDump(self):
        DumpExporter.exportAllDump(self)
        
    def clearTable(self):
        self.positionPanel.clearTables()

    ################################### RENDERS #########################################

    def renderSubtotal(self, positionDict, assetType ,isSIC):
        self.positionPanel.renderSubtotal(positionDict, assetType, isSIC)
    
    def renderPositions(self, positionDict, assetType ,isSIC):  
        self.positionPanel.renderPositions(positionDict, assetType, isSIC) 
        
    def renderSummary(self, summaryDict):  
        self.positionPanel.renderSummary(summaryDict)   
    
    def renderCorpEvent(self, corporateEventPositionDictAsset):  
        self.corpEventPanel.renderCorpEvent(corporateEventPositionDictAsset) 
        
    def renderGeneralInfoPanel(self, usdMXNvalue):  
        self.positionPanel.renderGeneralInfoPanel(usdMXNvalue) 
Example #44
0
class MainWindowDoctor(QMainWindow):
    def __init__(self, user, parent=None):
        QMainWindow.__init__(self, None)
        self.crtlDatabase = Doctor.DoctorApplication()
        self.parent = parent
        self.user = user
        self.initUI()
        self.initLayout()

    def initUI(self):
        posX, posY, sizeW, sizeH = Setting.GEOMETRY_MAINWIDOW
        self.setGeometry(posX, posY, sizeW, sizeH)
        self.setWindowTitle("Doctor window")
        self.setTab()
        self.show()

    def initLayout(self):
        layout = QGridLayout()
        layout.addWidget(self.tabWidget)
        centralWidget = QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

    def setTab(self):
        self.tabWidget = QTabWidget()
        self.tabWidget.setStyleSheet(Setting.SS_TabWidget)
        self.tab1 = Tab1_CalendarClass.Tab1Calendar(self.user, self)
        self.tab2 = Tab2_PatientClass.Tab2Patient(self.user, self)
        self.tab3 = Tab3_AppointmentClass.Tab3Appointment(self.user, self)
        self.tabWidget.addTab(self.tab1, "Dashboard")
        self.tabWidget.addTab(self.tab2, "Patient")
        self.tabWidget.addTab(self.tab3, "Appointment")

    def updateTable(self, tab):
        if tab == 'Appointment':
            self.tab3.updateTable()
        elif tab == 'Patient':
            self.tab2.updateTable()
        else:
            raise TypeError

    """-----------------------------DOCTOR APP---------------------------------------"""
    """-----PATIENT-----"""

    def getCurrentCaseID(self):
        return self.crtlDatabase.getCurrentCaseID()

    def addNewPatient(self, newPatient):
        self.crtlDatabase.addNewPatient(newPatient)

    def editPatient(self, oldPatient):
        self.crtlDatabase.editPatient(oldPatient)

    def patientValid(self, AN):
        return self.crtlDatabase.patientValid(AN)

    def oldPatientValid(self, AN, patient_name):
        return self.crtlDatabase.oldPatientValid(AN, patient_name)

    def deleteButtonPressed(self, AN):
        title = "Confirm deleting"
        text_info = "Delete this Patient"
        question = "Do you sure to delete " + str(AN)
        dialog = ConfirmMsgClass.ConfirmYesNo(title, text_info, question)
        if dialog.ans:
            patients = self.crtlDatabase.getPatientFromDatabase()
            appointments = self.crtlDatabase.getAppointmentFromDatabase()
            for patient in patients:
                if patient.AN == AN:
                    patients.remove(patient)
                    self.crtlDatabase.updatePatientDatabase(patients)
                    self.tab2.updateTable()
                    break
            for appointment in appointments:
                if appointment.patient.AN == AN:
                    appointments.remove(appointment)
                    self.crtlDatabase.updateAppointmentDatabase(appointments)
                    self.tab3.updateTable()
                    break
        else:
            pass

    """-----APPOINTMENT----"""

    def getAppointment(self):
        return self.crtlDatabase.getAppointmentByDoctor(self.user.id)

    def addNewAppointment(self, newAppointment):
        self.crtlDatabase.addNewAppointment(newAppointment)

    def appointmentValid(self, date, time, doctor):
        return self.crtlDatabase.appointmentValid(date, time, doctor)

    def getPatientByCaseId(self, case_id):
        return self.crtlDatabase.getPatientByCaseId(case_id, self.user.id)

    def getAppointmentByAN(self, AN):
        return self.crtlDatabase.getAppointmentByAN(AN)

    def getHistoryReportByAN(self, AN):
        return self.crtlDatabase.getHistoryReportByAN(AN)
Example #45
0
File: guiv2.py Project: dylziez/SMG
class UiMain(QMainWindow):

    """ The main gui interface, invokes all windows and ties everything
     together
    """

    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()
        
    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""")
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(self.start_btn, SIGNAL("clicked()"),
                        lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL
                       ("clicked()"), self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off, SIGNAL
                       ("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)")
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(
                    target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
Example #46
0
class uiManager(QMainWindow):
	def __init__(self):
		super(uiManager, self).__init__()

		self.setMinimumSize(900,500)
		self.setWindowTitle("Manage")

		self.aFileModel = FileModel() # Add files
		self.sFileModel = FileModel() # Queried files
		self.eFileModel = FileModel() # Editing files

		self.tabWidget = QTabWidget()
		self.setCentralWidget(self.tabWidget)

		self.defActions()

		self.addTab()
		self.searchTab()
		self.editTab()
		self.testtab()

		self.statusBar().showMessage("Hi.")


	def defActions(self):
		self.findAct = QAction("+", self, triggered=self.findFilesDlg)
		self.dropAddTabAct = QAction("-", self, shortcut="Delete",
			triggered=self.dropAddTabRows)
		self.dropEditTabAct = QAction("-", self, shortcut="Delete",
			triggered=self.dropEditTabRows)


	def dropEditTabRows(self):
		self.dropFiles(self.eFileTable, self.eFileModel)


	def dropAddTabRows(self):
		self.dropFiles(self.aFileTable, self.aFileModel)


	def testtab(self):
		self.test = QWidget()
		self.tabWidget.addTab(self.test, "WORDS")
		self.tabWidget.setCornerWidget(self.test)


	def addTab(self):

		self.aFileTable = QTableView()
		self.aFileTable.setModel(self.aFileModel)
		self.aFileTable.setSelectionBehavior(QAbstractItemView.SelectRows)

		self.setColumnsWidths(self.aFileTable)

		self.addWidget = QWidget()

		vLayout = QVBoxLayout()
		vLayout.addWidget(self.aFileTable)

		addBtn = QToolButton()
		addBtn.setDefaultAction(self.findAct)
		# addBtn.clicked.connect(self.findFilesDlg)

		dropBtn = QToolButton()
		dropBtn.setDefaultAction(self.dropAddTabAct)
		# rmvBtn.clicked.connect(self.rmvFiles)

		insBtn = QPushButton("Track")
		insBtn.clicked.connect(self.insert)

		hLayout = QHBoxLayout()

		hLayout.addWidget(addBtn)
		hLayout.addWidget(dropBtn)
		hLayout.addStretch(1)		
		hLayout.addWidget(insBtn)

		vLayout.addLayout(hLayout)

		self.addWidget.setLayout(vLayout)

		self.tabWidget.addTab(self.addWidget, u"Add")


	def searchTab(self):

		# sFileModel + view tab
		self.sFileTable = QTableView()
		self.sFileTable.setModel(self.sFileModel)
		self.sFileTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.sFileTable.setSelectionBehavior(QAbstractItemView.SelectRows)

		self.setColumnsWidths(self.sFileTable)

		self.searchWidget = QWidget()

		# Horizontal layout
		# Button, Line Edit, Button
		hLayout = QHBoxLayout()
		self.searchBox = QLineEdit()
		self.searchBox.returnPressed.connect(self.searchdb)
		hLayout.addWidget(self.searchBox)

		searchBtn = QPushButton("Search")
		searchBtn.clicked.connect(self.searchdb)
		hLayout.addWidget(searchBtn)

		# Vertical Layout
		vLayout = QVBoxLayout()
		vLayout.addLayout(hLayout)
		vLayout.addWidget(self.sFileTable)

		# sub horiz box
		subHLayout = QHBoxLayout()
		subHLayout.addStretch(1)
		
		editBtn = QPushButton("Edit -->")
		editBtn.clicked.connect(self.addToEditTab)

		subHLayout.addWidget(editBtn)
		vLayout.addLayout(subHLayout)

		self.searchWidget.setLayout(vLayout)
		self.tabWidget.addTab(self.searchWidget, u"Retrieve")


	def editTab(self):
		
		self.eFileTable = QTableView()
		self.eFileTable.setModel(self.eFileModel)
		self.eFileTable.setSelectionBehavior(QAbstractItemView.SelectRows)

		self.setColumnsWidths(self.eFileTable)

		self.editWidget = QWidget()

		vLayout = QVBoxLayout()
		vLayout.addWidget(self.eFileTable)

		dropBtn = QToolButton()
		dropBtn.setDefaultAction(self.dropEditTabAct)

		undBtn = QPushButton("Undo Delete")
		undBtn.clicked.connect(self.undeleteFiles)

		rmvBtn = QPushButton("Delete")
		rmvBtn.clicked.connect(self.deleteFiles)

		cmtBtn = QPushButton("Update")
		cmtBtn.clicked.connect(self.update)

		hLayout = QHBoxLayout()
		hLayout.addWidget(dropBtn)
		hLayout.addStretch(1)
		hLayout.addWidget(undBtn)
		hLayout.addWidget(rmvBtn)
		hLayout.addWidget(cmtBtn)

		vLayout.addLayout(hLayout)

		self.editWidget.setLayout(vLayout)

		self.tabWidget.addTab(self.editWidget, u"Edit")


	def setColumnsWidths(self, table):
		table.setColumnWidth(0, 438)
		table.horizontalHeader().setStretchLastSection(True)


	def undeleteFiles(self):
		delfiles = self.eFileModel.delfiles
		for file in delfiles:
			path, tags = file.path, file.tags
			self.addToModel(self.eFileModel, path, tags, True)
		self.eFileModel.delfiles = []


	# Adds files to the models delete list
	# for removal from the DB on next update()
	def deleteFiles(self):
		indexes = self.getSRIndexes(self.eFileTable)

		for index in indexes:
			self.eFileModel.delList(index.row())
			self.eFileModel.removeRows(index.row())
		self.statusBar().showMessage("Pending Changes")


	# Drop files from a table and model
	def dropFiles(self, table, model):
		indexes = self.getSRIndexes(table)

		for index in indexes:
			model.removeRows(index.row())


	# Inserts files into the DB from the add model
	def insert(self):
		p = self.aFileModel.insert()
		if p:
			msgDuplBox = QMessageBox()
			msgDuplBox.setText('\n'.join(p) + 
				"\n\n...file(s) already being tracked.")
			msgDuplBox.exec_()


	def update(self):
		self.eFileModel.update()

	
	''' Order of user selection matters in the view. As a user
	selects an item it is entered into the list of selected rows.
	To remove the correct items first you have to sort the list,
	then reverse it to remove items from the bottom up to prevent
	a row number pointing at the wrong entry because an entry
	above it was already removed.'''
	def getSRIndexes(self, table):
		indexes = table.selectionModel().selectedRows()
		indexes.sort()
		indexes.reverse()
		return indexes


	def findFilesDlg(self):
		finder = getFilesDlg(self)
		finder.sendPaths.connect(self.addToAddTab)
		finder.show()


	@Slot(list)
	def addToAddTab(self, list):
		for path in list:

			if self.colCheck(self.aFileModel, path):

				self.addToModel(self.aFileModel, path)


	def addToSearchTab(self, qresults):
		if qresults:

			self.sFileModel.reset()

			for file in qresults:

				path,tags = file
				self.addToModel(self.sFileModel, path, tags)


	def addToEditTab(self):
		# Need to make sure what they are adding isn't already
		# present in the edit model's files or delfiles lists
		indexes = self.getSRIndexes(self.sFileTable)

		# save original path as update reference for db
		oldpath = True

		for index in indexes:

			path, tags = self.sFileModel.dataTuple(index)

			if self.colCheck(self.eFileModel, path):
			
				self.addToModel(self.eFileModel, path, tags, oldpath)

				self.sFileModel.removeRows(index.row())


	def addToModel(self, model, path, tags=None, oldpath=False):

			model.insertRows(0)

			ix = model.index(0, 0, QModelIndex())
			model.setData(ix, path, Qt.EditRole, oldpath)

			ix = model.index(0, 1, QModelIndex())
			model.setData(ix, tags, Qt.EditRole, oldpath)


	def colCheck(self, model, path):
		# THIS IS REALLY SLOW
		# Linear search, 
		if model.files:
			for file in model.files:
				if path == file.path:
					return False
		return True


	def searchdb(self):
		thedb = myDB()
		query = thedb.query(self.searchBox.text())
		self.addToSearchTab(query)
Example #47
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.config = Config()
        if bool(self.state.model):
            self.config = self.state.model.configs()
        self.setWindowTitle("Output Options — {}".format(
            QApplication.applicationName()))
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.tabWidget = QTabWidget()
        self.generalOutputPanel = OutputPanels.GeneralOutput.Panel(
            self.state, self.config, self)
        self.entryXRefOutputPanel = OutputPanels.EntryXRefOutput.Panel(
            self.state, self.config, self)
        self.subentryXRefOutputPanel = (OutputPanels.SubentryXRefOutput.Panel(
            self.state, self.config, self))
        self.specificOutputPanel = OutputPanels.SpecificOutput.Panel(
            self.state, self.config, self)
        self.tabWidget.addTab(self.generalOutputPanel, "&1 General")
        self.tabWidget.addTab(self.entryXRefOutputPanel,
                              "&2 Entry Cross-references")
        self.tabWidget.addTab(self.subentryXRefOutputPanel,
                              "&3 Subentry Cross-references")
        self.tabWidget.addTab(self.specificOutputPanel, "&4 Format Specific")
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Output Options dialog"))
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Close</b></p>
<p>Close the dialog.</p>"""))

    def layoutWidgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.tabWidget)
        layout.addStretch()
        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        buttonBox.addButton(self.closeButton, QDialogButtonBox.AcceptRole)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def createConnections(self):
        self.helpButton.clicked.connect(self.help)
        self.closeButton.clicked.connect(self.accept)

    def help(self):
        self.state.help("xix_ref_dlg_output.html")

    def accept(self, *args):
        self.setEnabled(False)
        self._acceptOptions()
        if bool(self.state.model):
            self._acceptConfig()
        super().accept(*args)

    def _acceptOptions(self):
        settings = QSettings()
        size = PaperSizeKind.A4
        if self.specificOutputPanel.letterRadioButton.isChecked():
            size = PaperSizeKind.LETTER
        settings.setValue(Gopt.Key.PaperSize, int(size))
        if self.state.printer is not None:
            self.state.printer.setPaperSize(
                QPrinter.A4 if size is PaperSizeKind.A4 else QPrinter.Letter)

    def _acceptConfig(self):
        model = self.state.model
        config = Config()
        config.Title = self.generalOutputPanel.titleTextEdit.toHtml()
        config.Note = self.generalOutputPanel.noteTextEdit.toHtml()
        config.SectionPreLines = (
            self.generalOutputPanel.blankBeforeSpinBox.value())
        config.SectionPostLines = (
            self.generalOutputPanel.blankAfterSpinBox.value())
        config.SectionTitles = (
            self.generalOutputPanel.sectionTitlesCheckBox.isChecked())
        config.MonoFontAsStrikeout = (
            self.generalOutputPanel.monoFontAsStrikeoutCheckbox.isChecked())
        index = self.generalOutputPanel.styleComboBox.currentIndex()
        config.Style = StyleKind(
            self.generalOutputPanel.styleComboBox.itemData(index))
        config.RunInSeparator = (
            self.generalOutputPanel.runInSepTextEdit.toHtml())
        config.SectionSpecialTitle = (
            self.generalOutputPanel.sectionSpecialTitleTextEdit.toHtml())
        config.TermPagesSeparator = (
            self.generalOutputPanel.termPagesSepTextEdit.toHtml())
        config.SeePrefix = (
            self.entryXRefOutputPanel.seePrefixTextEdit.toHtml())
        config.See = self.entryXRefOutputPanel.seeTextEdit.toHtml()
        config.SeeSeparator = (
            self.entryXRefOutputPanel.seeSepTextEdit.toHtml())
        config.SeeSuffix = (
            self.entryXRefOutputPanel.seeSuffixTextEdit.toHtml())
        config.SeeAlsoPrefix = (
            self.entryXRefOutputPanel.seeAlsoPrefixTextEdit.toHtml())
        config.SeeAlso = self.entryXRefOutputPanel.seeAlsoTextEdit.toHtml()
        config.SeeAlsoSeparator = (
            self.entryXRefOutputPanel.seeAlsoSepTextEdit.toHtml())
        config.SeeAlsoSuffix = (
            self.entryXRefOutputPanel.seeAlsoSuffixTextEdit.toHtml())
        index = (
            self.entryXRefOutputPanel.seeAlsoPositionComboBox.currentIndex())
        config.SeeAlsoPosition = (
            self.entryXRefOutputPanel.seeAlsoPositionComboBox.itemData(index))
        config.GenericConjunction = (
            self.entryXRefOutputPanel.genericConjunctionTextEdit.toHtml())
        index = (
            self.entryXRefOutputPanel.xrefToSubentryComboBox.currentIndex())
        config.XRefToSubentry = (
            self.entryXRefOutputPanel.xrefToSubentryComboBox.itemData(index))
        config.SubSeePrefix = (
            self.subentryXRefOutputPanel.seePrefixTextEdit.toHtml())
        config.SubSee = self.subentryXRefOutputPanel.seeTextEdit.toHtml()
        config.SubSeeSeparator = (
            self.subentryXRefOutputPanel.seeSepTextEdit.toHtml())
        config.SubSeeSuffix = (
            self.subentryXRefOutputPanel.seeSuffixTextEdit.toHtml())
        config.SubSeeAlsoPrefix = (
            self.subentryXRefOutputPanel.seeAlsoPrefixTextEdit.toHtml())
        config.SubSeeAlso = (
            self.subentryXRefOutputPanel.seeAlsoTextEdit.toHtml())
        config.SubSeeAlsoSeparator = (
            self.subentryXRefOutputPanel.seeAlsoSepTextEdit.toHtml())
        config.SubSeeAlsoSuffix = (
            self.subentryXRefOutputPanel.seeAlsoSuffixTextEdit.toHtml())
        index = (self.subentryXRefOutputPanel.seeAlsoPositionComboBox.
                 currentIndex())
        config.SubSeeAlsoPosition = (self.subentryXRefOutputPanel.
                                     seeAlsoPositionComboBox.itemData(index))
        model.setConfigs(config)
Example #48
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(598, 450)
        self.icon = QIcon(":/icons/uglytheme/48x48/polibeepsync.png")
        Form.setWindowIcon(self.icon)
        Form.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(Form)
        self.tabWidget.setObjectName("tabWidget")

        # Tab General Settings
        self.tab = QWidget()
        self.tab.setObjectName("tab")
        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self.tab)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
        self.label = QLabel(self.tab)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.password = QLineEdit(self.tab)
        self.password.setMaximumSize(QSize(139, 16777215))
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setObjectName("password")
        self.gridLayout.addWidget(self.password, 3, 1, 1, 1)
        self.userCode = QLineEdit(self.tab)
        self.userCode.setMaximumSize(QSize(139, 16777215))
        self.userCode.setText("")
        self.userCode.setObjectName("userCode")
        self.gridLayout.addWidget(self.userCode, 1, 1, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 1, 2, 1, 1)
        self.verticalLayout_2.addLayout(self.gridLayout)
        self.trylogin = QPushButton(self.tab)
        self.trylogin.setMaximumSize(QSize(154, 16777215))
        self.trylogin.setObjectName("trylogin")
        self.verticalLayout_2.addWidget(self.trylogin)
        self.login_attempt = QLabel(self.tab)
        self.login_attempt.setText("Logging in, please wait.")
        self.login_attempt.setStyleSheet("color: rgba(0, 0, 0, 0);")
        self.login_attempt.setObjectName("login_attempt")
        self.verticalLayout_2.addWidget(self.login_attempt)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem1)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QLabel(self.tab)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.rootfolder = QLineEdit(self.tab)
        self.rootfolder.setMinimumSize(QSize(335, 0))
        self.rootfolder.setMaximumSize(QSize(335, 16777215))
        self.rootfolder.setInputMask("")
        self.rootfolder.setReadOnly(True)
        self.rootfolder.setObjectName("rootfolder")
        self.horizontalLayout_3.addWidget(self.rootfolder)
        self.changeRootFolder = QPushButton(self.tab)
        self.changeRootFolder.setObjectName("changeRootFolder")
        self.horizontalLayout_3.addWidget(self.changeRootFolder)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_5 = QLabel(self.tab)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_5.addWidget(self.label_5)
        self.timerMinutes = QSpinBox(self.tab)
        self.timerMinutes.setObjectName("timerMinutes")
        self.horizontalLayout_5.addWidget(self.timerMinutes)
        self.label_6 = QLabel(self.tab)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_5.addWidget(self.label_6)
        self.syncNow = QPushButton(self.tab)
        self.syncNow.setObjectName("syncNow")
        self.horizontalLayout_5.addWidget(self.syncNow)
        spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
        self.addSyncNewCourses = QCheckBox(self.tab)
        self.addSyncNewCourses.setObjectName("addSyncNewCourses")
        self.verticalLayout_2.addWidget(self.addSyncNewCourses)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")

        # Tab Courses
        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_2 = QHBoxLayout(self.tab_2)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.refreshCourses = QPushButton(self.tab_2)
        self.refreshCourses.setObjectName("refreshCourses")
        self.horizontalLayout_6.addWidget(self.refreshCourses)
        spacerItem4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem4)
        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.coursesView = CoursesListView(self.tab_2)
        self.coursesView.setObjectName("coursesView")
        self.verticalLayout_3.addWidget(self.coursesView)
        self.horizontalLayout_2.addLayout(self.verticalLayout_3)
        self.tabWidget.addTab(self.tab_2, "")

        # Tab Status
        self.tab_3 = QWidget()
        self.tab_3.setObjectName("tab_3")
        self.horizontalLayout_7 = QHBoxLayout(self.tab_3)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_8 = QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.about = QPushButton(self.tab_3)
        self.about.setObjectName("about")
        self.horizontalLayout_8.addWidget(self.about)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_8.addItem(spacerItem5)
        self.verticalLayout_4.addLayout(self.horizontalLayout_8)
        self.status = QTextEdit(self.tab_3)
        self.status.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                            | Qt.TextSelectableByMouse)
        self.status.setObjectName("status")
        self.verticalLayout_4.addWidget(self.status)
        self.horizontalLayout_7.addLayout(self.verticalLayout_4)
        self.tabWidget.addTab(self.tab_3, "")

        self.tab_4 = QWidget()
        self.tab_4.setObjectName("tab_4")
        self.verticalLayout.addWidget(self.tabWidget)

        self.okButton = QDialogButtonBox(Form)
        self.okButton.setStandardButtons(QDialogButtonBox.Ok)
        self.okButton.setObjectName("okButton")
        self.okButton.clicked.connect(self.hide)
        self.verticalLayout.addWidget(self.okButton)

        self.statusLabel = QLabel(Form)
        self.statusLabel.setObjectName("statusLabel")
        self.verticalLayout.addWidget(self.statusLabel)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle("poliBeePsync")
        if pysideVersion == '1.2.2':
            self.label_2.setText(
                QApplication.translate("Form", "Password", None,
                                       QApplication.UnicodeUTF8))
            self.label.setText(
                QApplication.translate("Form", "User code", None,
                                       QApplication.UnicodeUTF8))
            self.trylogin.setText(
                QApplication.translate("Form", "Try login credentials", None,
                                       QApplication.UnicodeUTF8))
            self.login_attempt.setText(
                QApplication.translate("Form", "Login successful", None,
                                       QApplication.UnicodeUTF8))
            self.label_4.setText(
                QApplication.translate("Form", "Root folder", None,
                                       QApplication.UnicodeUTF8))
            self.changeRootFolder.setText(
                QApplication.translate("Form", "Change", None,
                                       QApplication.UnicodeUTF8))
            self.label_5.setText(
                QApplication.translate("Form", "Sync every", None,
                                       QApplication.UnicodeUTF8))
            self.label_6.setText(
                QApplication.translate("Form", "minutes", None,
                                       QApplication.UnicodeUTF8))
            self.syncNow.setText(
                QApplication.translate("Form", "Sync now", None,
                                       QApplication.UnicodeUTF8))
            self.addSyncNewCourses.setText(
                QApplication.translate(
                    "Form", "Automatically add and sync new available courses",
                    None, QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab),
                QApplication.translate("Form", "General settings", None,
                                       QApplication.UnicodeUTF8))
            self.refreshCourses.setText(
                QApplication.translate("Form", "Refresh list", None,
                                       QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_2),
                QApplication.translate("Form", "Courses", None,
                                       QApplication.UnicodeUTF8))
            self.about.setText(
                QApplication.translate("Form", "About", None,
                                       QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_3),
                QApplication.translate("Form", "Status", None,
                                       QApplication.UnicodeUTF8))
        else:
            self.label_2.setText(
                QApplication.translate("Form", "Password", None))
            self.label.setText(
                QApplication.translate("Form", "User code", None))
            self.trylogin.setText(
                QApplication.translate("Form", "Try login credentials", None))
            self.login_attempt.setText(
                QApplication.translate("Form", "Login successful", None))
            self.label_4.setText(
                QApplication.translate("Form", "Root folder", None))
            self.changeRootFolder.setText(
                QApplication.translate("Form", "Change", None))
            self.label_5.setText(
                QApplication.translate("Form", "Sync every", None))
            self.label_6.setText(
                QApplication.translate("Form", "minutes", None))
            self.syncNow.setText(
                QApplication.translate("Form", "Sync now", None))
            self.addSyncNewCourses.setText(
                QApplication.translate(
                    "Form", "Automatically add and sync new available courses",
                    None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab),
                QApplication.translate("Form", "General settings", None))
            self.refreshCourses.setText(
                QApplication.translate("Form", "Refresh list", None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_2),
                QApplication.translate("Form", "Courses", None))
            self.about.setText(QApplication.translate("Form", "About", None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_3),
                QApplication.translate("Form", "Status", None))
Example #49
0
class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Cobaya input generator for Cosmology")
        self.setGeometry(0, 0, 1500, 1000)
        self.move(
            QApplication.desktop().screen().rect().center() - self.rect().center())
        self.show()
        # Main layout
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.layout_left = QVBoxLayout()
        self.layout.addLayout(self.layout_left)
        self.layout_output = QVBoxLayout()
        self.layout.addLayout(self.layout_output)
        # LEFT: Options
        self.options = QWidget()
        self.layout_options = QVBoxLayout()
        self.options.setLayout(self.layout_options)
        self.options_scroll = QScrollArea()
        self.options_scroll.setWidget(self.options)
        self.options_scroll.setWidgetResizable(True)
        self.layout_left.addWidget(self.options_scroll)
        self.atoms = odict()
        titles = odict([
            ["preset", "Presets"],
            ["theory", "Theory code"],
            ["primordial", "Primordial perturbations"],
            ["geometry", "Geometry"],
            ["hubble", "Constaint on hubble parameter"],
            ["baryons", "Baryon sector"],
            ["dark_matter", "Dark matter"],
            ["dark_energy", "Lambda / Dark energy"],
            ["neutrinos", "Neutrinos and other extra matter"],
            ["bbn", "BBN"],
            ["reionization", "Reionization history"],
            ["cmb_lensing", "CMB lensing"],
            ["cmb", "CMB experiments"],
            ["sampler", "Samplers"]])
        for a in titles:
            self.atoms[a] = {
                "group": QGroupBox(titles[a]),
                "combo": QComboBox()}
            self.layout_options.addWidget(self.atoms[a]["group"])
            self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"])
            self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"])
            self.atoms[a]["combo"].addItems(
                [text(k,v) for k,v in getattr(input_database, a).items()])
        # Connect to refreshers -- needs to be after adding all elements
        for a in self.atoms:
            if a == "preset":
                self.atoms["preset"]["combo"].currentIndexChanged.connect(
                    self.refresh_preset)
                continue
            self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh)
        # Add Planck-naming checkbox and connect to refresher too
        self.planck_names = QCheckBox("Keep common names")
        self.atoms["theory"]["layout"].addWidget(self.planck_names)
        self.planck_names.stateChanged.connect(self.refresh)
        # RIGHT: Output + buttons
        self.display_tabs = QTabWidget()
        self.display = {}
        for k in ["yaml", "python"]:
            self.display[k] = QTextEdit()
            self.display[k].setLineWrapMode(QTextEdit.NoWrap)
            self.display[k].setFontFamily("mono")
            self.display[k].setCursorWidth(0)
            self.display[k].setReadOnly(True)
            self.display_tabs.addTab(self.display[k], k)
        self.layout_output.addWidget(self.display_tabs)
        # Buttons
        self.buttons = QHBoxLayout()
        self.save_button = QPushButton('Save', self)
        self.copy_button = QPushButton('Copy to clipboard', self)
        self.buttons.addWidget(self.save_button)
        self.buttons.addWidget(self.copy_button)
        self.save_button.released.connect(self.save_file)
        self.copy_button.released.connect(self.copy_clipb)
        self.layout_output.addLayout(self.buttons)
        self.save_dialog = QFileDialog()
        self.save_dialog.setFileMode(QFileDialog.AnyFile)
        self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)
        # Select first preset, by default
#        print(self.atoms["preset"]["combo"].itemText(0))

    @Slot()
    def refresh(self):
        info = create_input(planck_names=self.planck_names.isChecked(), **{
            k:str(self.atoms[k]["combo"].currentText().split(_separator)[0])
            for k in self.atoms if k is not "preset"})
        self.refresh_display(info)

    @Slot()
    def refresh_preset(self):
        preset = self.atoms["preset"]["combo"].currentText().split(_separator)[0]
        info = create_input(preset=preset)
        self.refresh_display(info)
        # Update combo boxes to reflect the preset values, without triggering update
        for k,v in input_database.preset[preset].items():
            if k in [input_database._desc, "derived"]:
                continue
            self.atoms[k]["combo"].blockSignals(True)
            self.atoms[k]["combo"].setCurrentIndex(
                self.atoms[k]["combo"].findText(
                    text(v,getattr(input_database, k).get(v))))
            self.atoms[k]["combo"].blockSignals(False)

    def refresh_display(self, info):
        self.display["python"].setText(
            "from collections import OrderedDict\n\ninfo = " + pformat(info))
        self.display["yaml"].setText(yaml_dump(info))

    @Slot()
    def save_file(self):
        ftype = next(k for k,w in self.display.items()
                     if w is self.display_tabs.currentWidget())
        ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)"}[ftype]
        fsuffix = {"yaml": ".yaml", "python": ".py"}[ftype]
        fname, path = self.save_dialog.getSaveFileName(
            self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd())
        if not fname.endswith(fsuffix):
            fname += fsuffix
        with open(fname, "w+") as f:
            f.write(self.display_tabs.currentWidget().toPlainText())

    @Slot()
    def copy_clipb(self):
        self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())
Example #50
0
class UiMain(QMainWindow):
    """ The main gui interface, invokes all windows and ties everything
     together
    """
    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()

        # self.update()
        CheckUpdateThread = Thread(target=self.update)
        CheckUpdateThread.setName('CheckUpdateThread')
        CheckUpdateThread.run()

    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>"""
            )
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(
            self.start_btn, SIGNAL("clicked()"),
            lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"),
                        self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off,
                        SIGNAL("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)"
        )
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
Example #51
0
class Truss(QMainWindow):
    def __init__(self, parent=None):
        super(Truss, self).__init__(parent)        
        self.resize(800, 600)
        self.filename  = None
        self.filetuple = None
        self.dirty = False  # Refers to Data Page only.
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        self.tabWidget = QTabWidget(centralwidget)
        self.tab = QWidget()
        font = QFont()
        font.setFamily("Courier 10 Pitch")
        font.setPointSize(12)
        self.tab.setFont(font)
        gridLayout_3 = QGridLayout(self.tab)
        self.plainTextEdit = QPlainTextEdit(self.tab)
        gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QWidget()
        self.tab_2.setFont(font)
        gridLayout_2 = QGridLayout(self.tab_2)
        self.plainTextEdit_2 = QPlainTextEdit(self.tab_2)
        gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 800, 29))
        menu_File = QMenu(menubar)
        self.menu_Solve = QMenu(menubar)
        self.menu_Help = QMenu(menubar)
        self.setMenuBar(menubar)
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.action_New = QAction(self)
        self.actionSave_As = QAction(self)
        self.action_Save = QAction(self)
        self.action_Open = QAction(self)
        self.action_Quit = QAction(self)
        self.action_About = QAction(self)
        self.actionShow_CCPL = QAction(self)
        self.action_Solve = QAction(self)
        self.action_CCPL = QAction(self)
        self.action_Help = QAction(self)
        menu_File.addAction(self.action_New)
        menu_File.addAction(self.action_Open)
        menu_File.addAction(self.actionSave_As)
        menu_File.addAction(self.action_Save)
        menu_File.addSeparator()
        menu_File.addAction(self.action_Quit)
        self.menu_Solve.addAction(self.action_Solve)
        self.menu_Help.addAction(self.action_About)
        self.menu_Help.addAction(self.action_CCPL)
        self.menu_Help.addAction(self.action_Help)
        menubar.addAction(menu_File.menuAction())
        menubar.addAction(self.menu_Solve.menuAction())
        menubar.addAction(self.menu_Help.menuAction())        
        self.setWindowTitle("Main Window")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\
                                   "Data Page")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\
                                   "Solution Page")        
        menu_File.setTitle("&File")        
        self.menu_Solve.setTitle("&Solve")
        self.menu_Help.setTitle("&Help")
        self.tabWidget.setCurrentIndex(0)
        self.action_New.setText("&New") 
        self.action_Open.setText("&Open")       
        self.actionSave_As.setText("Save &As")
        self.action_Save.setText("&Save")
        self.action_Quit.setText("&Quit")        
        self.action_Solve.setText("&Solve")
        self.action_About.setText("&About")
        self.action_CCPL.setText("&CCPL")
        self.action_Help.setText("&Help")
        self.action_Quit.triggered.connect(self.close)
        allToolBar = self.addToolBar("AllToolBar") 
        allToolBar.setObjectName("AllToolBar") 
        self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\
                        self.action_Save, self.action_Solve,\
                        self.action_Quit ))
        self.action_New.triggered.connect(self.fileNew)
        self.action_Open.triggered.connect(self.fileOpen)
        self.actionSave_As.triggered.connect(self.fileSaveAs)
        self.action_Save.triggered.connect(self.fileSave)
        self.action_Solve.triggered.connect(self.trussSolve)
        self.action_About.triggered.connect(self.aboutBox)
        self.action_CCPL.triggered.connect(self.displayCCPL)
        self.action_Help.triggered.connect(self.help)
        self.plainTextEdit.textChanged.connect(self.setDirty)
        self.action_New = self.editAction(self.action_New, None,\
                            'ctrl+N', 'filenew', 'New File.')   
        self.action_Open = self.editAction(self.action_Open, None, 
                            'ctrl+O', 'fileopen', 'Open File.')
        self.actionSave_As = self.editAction(self.actionSave_As,\
                            None, 'ctrl+A', 'filesaveas',\
                            'Save and Name File.')
        self.action_Save = self.editAction(self.action_Save, None, 
                            'ctrl+S', 'filesave', 'Save File.')
        self.action_Solve = self.editAction(self.action_Solve, None, 
                            'ctrl+L', 'solve', 'Solve Structure.')                                   
        self.action_About = self.editAction(self.action_About, None, 
                            'ctrl+B', 'about','Pop About Box.')                                  
        self.action_CCPL = self.editAction(self.action_CCPL, None, 
                            'ctrl+G', 'licence', 'Show Licence') 
        self.action_Help = self.editAction(self.action_Help, None, 
                            'ctrl+H', 'help', 'Show Help Page.')
        self.action_Quit =  self.editAction(self.action_Quit, None, 
                            'ctrl+Q', 'quit', 'Quit the program.')                                           
        self.plainTextEdit_2.setReadOnly(True)
    
    def setDirty(self):
        '''On change of text in textEdit window, set the flag
        "dirty" to True'''
        index = self.tabWidget.currentIndex()
        if index is not 0:
            return
        if self.dirty:
            return True
        self.dirty = True
        self.updateStatus('self.dirty set to True')    
    
    def clearDirty(self):
        'Clear dirty flag'
        self.dirty = False
    
    def fileNew(self):
        '''Clear both Data Page and Solution Page.'''
        self.plainTextEdit.setPlainText(' ')
        self.plainTextEdit_2.setPlainText(' ')
        self.clearDirty(self)

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(self,
                    "Data Loader - Unsaved Changes",
                    "Save unsaved changes?",
                    QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                self.clearDirty()
                return self.fileSave()
        return True
    
    def okRead(self):
        'Pop-up a warning message.'
        reply = QMessageBox.warning(self,
                "Warning",
                '''\nFile Open and Save is possible only in Data Page!
\n\(Use SaveAs for Solution Page)''', QMessageBox.Ok)
        return True

    def fileOpen(self):
        '''Open a file in Data Page (with index == 0)'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        self.filetuple = QFileDialog.getOpenFileName(self,\
                        "Open File", dir, \
                        "Data (*.dat *.txt)\nAll Files (*.*)")
        self.filename = self.filetuple[0] 
        fname = self.filename        
#  QFileDialog returns a tuple x with x[0] = file name and 
#  x[1] = type of filter.
        if fname:
            self.loadFile(fname)
            self.filename = fname
            self.updateStatus('New file opened.')
                
    def loadFile(self, fname=None):
        fl = open(fname)
        text = fl.read()
        self.plainTextEdit.setPlainText(text)
        self.dirty = False
    
    def fileSave(self):
        '''Save file with current file name.'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return        
        if self.filename is None:
            return self.fileSaveAs()
        else:
            flname = self.filename
            if flname:
                with open(flname, 'w') as fl:
                    fl.write(tempText)
                self.dirty = False
                self.updateStatus('File saved.')
                return True
            else:
                self.updateStatus('Failed to save... ')
                return False
        self.filename = None
        self.dirty = False

    def fileSaveAs(self):        
        '''Save file with a new name.'''
        qpr = self.qprintline
        fname = self.filename if self.filename is not None else\
        "NoName"
        self.filetuple = QFileDialog.getSaveFileName(self,
                "Truss program - Save File", fname, "Data File (*.*)")
        flname = self.filetuple[0]        
        index = self.tabWidget.currentIndex()
        if index == 0:
            self.filename = flname 
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit.toPlainText()
                fl.write(tempText)
                fl.close()
                self.dirty = False
                self.updateStatus('File saved.')   
        elif index == 1:
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit_2.toPlainText()
                fl.write(tempText)
                fl.close()

    def trussSolve(self):
        '''Solve a statically determinate truss, specified in
        Data Page and display the results in the Solution Page.
        To start, make a copy of the Data Page with a header all
        shown on the Data Page.'''
        printline = self.qprintline
        dataBall = self.plainTextEdit.toPlainText() 
        self.plainTextEdit_2.clear()
        printline('================================') 
        flbase = os.path.basename(self.filename)
        printline('SOLUTION FOR ' + flbase)
        printline('================================') 
        dataBall = self.plainTextEdit.toPlainText()
        ncrunch.main(printline, self.filename, dataBall)

    def aboutBox(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PySide, Platform and the like",
                """<b>Part of Structural Analysis.</b> v %s
                <p>Copyright &copy; 2011 Algis Kabaila. 
                All rights reserved in accordance with
                Creative Commons Attribution Licence (CCPL) v3
                or later - NO WARRANTIES!
                <p>This progam finds bar forces in 
                statically determinate trusses.                
                <p>Python %s -  PySide version %s - Qt version %s on\
                %s""" % (__version__, platform.python_version(),\
                PySide.__version__,  PySide.QtCore.__version__,
                platform.system()))
              
    def displayCCPL(self):
        '''Read and display CCPL licence.'''
        self.plainTextEdit.setPlainText(open('CCPL.txt').read())
        self.dirty = False
        self.filename = 'COPYING.txt'
        self.updateStatus('CCPL displayed.')

    def help(self):
        '''Read and display a help file- currently the README.txt.'''
        self.plainTextEdit.setPlainText(open('README.md').read())
        self.dirty = False
        self.filename = 'README.txt'
        self.updateStatus('README displayed.')
        
    def addActions(self, target, actions):
        '''Actions are added to Tool Bar.'''
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)
    
    def editAction(self, action, slot=None, shortcut=None, icon=None,
                     tip=None):
        '''This method adds to action: icon, shortcut, ToolTip,\
        StatusTip and can connect triggered action to slot '''
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % (icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)                        
        return action

    def qreadline(self, lineNo):
        '''Read one line from Data Page (lineNo starts with 0)'''
        return unicode(self.plainTextEdit.document().\
            findBlockByLineNumber(lineNo).text()).rstrip()

    def qprintline(self, line):        
        '''Append one line to Solution Page.'''
        self.plainTextEdit_2.appendPlainText(line.rstrip())

    def updateStatus(self, message):
        '''Keep status current.'''
        if self.filename is not None:
            flbase = os.path.basename(self.filename)
            self.setWindowTitle(unicode("Truss Analysis - " +\
                                         flbase + "[*]") )
            self.statusBar().showMessage(message, 5000)
            self.setWindowModified(self.dirty)
Example #52
0
class TableFrame(ModuleFrame):
    """This is the Frame class of the TableModule.
    """
    def __init__(self, parent, parent_frame=None, title=None):
        """Like all subclasses of ModuleFrame, the constructor requires:

            parent
                The GUI parent of this frame.

            parent_frame
                The ModuleFrame that is logically the parent to this one.

           Optionally, a title can be passed, but this is not yet in use.

           The Boxfish system handles the creation of ModuleFrames and will
           pass these values and only these values to any ModuleFrame.
        """
        super(TableFrame, self).__init__(parent, parent_frame, title)

        self.selected = []

        self.droppedDataSignal.connect(self.droppedData)
        self.agent.tableUpdateSignal.connect(self.updateTables)
        self.agent.highlightUpdateSignal.connect(self.updateSelection)

    def createView(self):
        """This required function creates the main view container for
           this module, in this case a QTabWidget to hold all the table
           views. The rest of the GUI is handled by the superclass.
        """
        self.tabs = QTabWidget()
        return self.tabs

    @Slot(list, str)
    def droppedData(self, indexList):
        """Overrides the superclass method to send the agent the dropped
           data indices.
        """
        self.agent.addDataIndices(indexList)

    @Slot(list, list, list, list, list)
    def updateTables(self, tables, runs, ids, headers, values):
        """Creates table views.

           tables
               A list of tables for which we have data.

           ids
               A list of lists of the corresponding SubDomain ids for
               each row of each table's returned values.

           headers
               A list of lists of the column names that go with the
               given values for each table.

           values
              A list of list of lists, one for each column of each table.
        """

        # We need to save tables, id_lists for selection later
        self.tables = tables
        self.id_lists = ids

        if tables is None:
            return

        self.tabs.clear()  # Get rid of old data

        # For each table, create a table view and populate it with the
        # given values for that table
        for table, run, ids_list, header_list, value_lists \
            in zip(tables, runs, ids, headers, values):
            tableWidget = TableTab(table, run, ids_list, header_list,
                                   value_lists)
            tableWidget.idsChanged.connect(self.selectionChanged)
            self.tabs.addTab(tableWidget, table)

    @Slot(list)
    def updateSelection(self, table_highlights):
        """Highlight the given table ids.

           table_highlights
               A list of lists of ids, one per table
        """
        for i, ids in enumerate(table_highlights):
            table = self.tabs.widget(i)
            table.selectRows(ids)

    @Slot(str, str, set)
    def selectionChanged(self, table, run, ids):
        """Pass along the selection information to the agent."""
        self.agent.changeHighlights(table, run, ids)
Example #53
0
class Cherry(QMainWindow):
	
	def __init__(self):
		super(Cherry, self).__init__() 
		self.initVars()
		self.initUI()
		self.initSamplesTab()
		self.initConnections()
		
	def initVars(self):
		self.path						= '~/cherrypicking'
		self.ignoreList					= ['','Population']
		self.markers					= []
		
	def initUI(self): 
		self.setWindowTitle('Cherry Picker')
		self.menubar					= MenuBar()
		self.setMenuBar(self.menubar)
		self.statusBar()
		self.tabs						= QTabWidget()
		self.tabs.setTabsClosable(True)
		self.setCentralWidget(self.tabs)
		self.showMaximized()
		
	def initSamplesTab(self):
		self.markers.append(Table('All Samples'))
		self.tabs.addTab(self.markers[0],self.markers[0].name)
		
	def initConnections(self):
		self.menubar.clearTableAction.triggered.connect(self.new)
		self.menubar.openAction.triggered.connect(self.openDialog)
		self.menubar.saveAction.triggered.connect(self.saveDialog)
		self.menubar.createSamplesAction.triggered.connect(self.createSamples)
		self.menubar.createSamplesFromExcelKeaAction.triggered.connect(self.createSamplesFromExcelKea)
		self.menubar.exitAction.triggered.connect(self.close)
		
		self.menubar.addMarkerAction.triggered.connect(self.addMarker)
		self.menubar.createPlateSheetsAction.triggered.connect(self.createPlateSheets)
		self.menubar.importLightcyclerFileAction.triggered.connect(self.importLightcyclerFile)
		self.menubar.setIncludesAction.triggered.connect(self.setIncludes)
		
		self.menubar.exportResultsAction.triggered.connect(self.exportResults)
		
		self.tabs.tabCloseRequested.connect(self.tabs.removeTab)
		self.tabs.tabCloseRequested.connect(lambda x: self.markers.pop(x))
		
########################################################################
##	Private Methods
	def __updateView(self):
		for marker in self.markers:
			marker.table						= marker.table[marker.columns]
			marker.setDataFrame(marker.table)
			
	def __clearAll(self):
		self.tabs.clear()
		self.markers							= []
		
	def __findMarker(self,findMarker):
		return next((marker for marker in self.markers if marker.name == findMarker), None)
########################################################################
##	File Menu Actions
	def new(self):
		'''Nukes self.markers['All Samples'] and starts again.'''
		self.__clearAll()
		self.initSamplesTab()
		
	def openDialog(self):
		'''Opens a saved .xls file.'''
		title									= 'Open a saved project file...'
		fileName,f								= QFileDialog.getOpenFileName(self,title,self.path)
		excelFile								= ExcelFile(fileName)
		self.__clearAll()
		[self.markers.append(Table(sheet,excelFile.parse(sheet))) for sheet in excelFile.sheet_names]
		[self.tabs.addTab(marker,marker.name) for marker in self.markers]
		self.__updateView()
		
	def saveDialog(self):
		'''Saves the project as an .xls file.'''
		title									= 'Save project as...'
		fileName,f								= QFileDialog.getSaveFileName(self,title,self.path)
		writer									= ExcelWriter(fileName+'.xls')
		for marker in self.markers:
			marker.table.to_excel(writer,marker.name)
		writer.save()
		
	def createSamples(self):
		'''Creates a given number of samples with no names or plant names.'''
		samples,ok								= CreateSamplesDialog.create(self)
		if ok:
			columns								= ['Origin plate','Origin well','Plant','Sample','From plate','From well',
													'Plate','Well','Experiment','Exp well','Result','Continues',]
			newSamplesDF						= DataFrame(samples,columns=columns)
			self.markers[0].table				= self.markers[0].table.append(newSamplesDF,ignore_index=True)
			self.__updateView()
		
	def createSamplesFromExcelKea(self):
		'''Opens a Kea Sample Batch spreadsheet and imports the samples.'''
		title									= 'Locate Kea sample batch spreadsheet...'
		fileName,f								= QFileDialog.getOpenFileName(self,title,self.path)
		excelFile								= ExcelFile(fileName)
		imported								= excelFile.parse('Data')
		imported								= imported[['PlantID','Sample ID','Plate No','Position on Plate(s)']]
		imported.columns						= ['Plant','Sample','Origin plate','Origin well']
		imported								= imported.dropna(how='all',subset=['Origin plate','Origin well'])
		imported['From plate']					= imported['Origin plate']
		imported['From well']					= imported['Origin well']
		imported['Plate']						= imported['Origin plate']
		imported['Well']						= imported['Origin well']
		self.markers[0].table					= self.markers[0].table.append(imported,ignore_index=True)
		self.__updateView()
		
########################################################################
##	Marker Menu Actions
	def addMarker(self):
		'''Prompts for marker name and samples, and adds a new tab containing
		the marker's information table.'''
		newMarker,includeAll,controls,ok	= NewMarkerDialog.run()
		if ok:
			marker							= self.tabs.currentWidget()
			samples							= marker.getContinues(getAll=includeAll)
			samples.columns					= ['Origin plate','Origin well','From plate','From well','Plant','Sample','Continues']
			newTable						= Table(newMarker,samples=samples)
			newTable.addPlateAndWell(controls,getAll=includeAll)
			self.markers.append(newTable)
			self.tabs.addTab(self.markers[-1],self.markers[-1].name)
			self.__updateView()
		
	def createPlateSheets(self):
		'''Generates platesheets for current marker.'''
		marker					= self.tabs.currentWidget().table
		if marker.loc[0,'From plate'] == marker.loc[0,'Plate']:
			text				= 'The source and destination plates are the same.'
			QMessageBox.information(self,'Unnecessary',text,QMessageBox.Ok)
		else:
			title					= 'Excel filename...'
			exportFileName,f		= QFileDialog.getSaveFileName(self,title,self.path)
			workBook				= PlateSheets()
			workBook.addPlateSheets(marker,'Destination','Plate','Well','From plate','From well')
			workBook.addPlateSheets(marker,'Source','From plate','From well','Plate','Well')
			workBook.save(exportFileName+'.xls')
		
	def importLightcyclerFile(self):
		'''Imports Lightcycler .txt files and adds the results, locating
		samples by plate name (taken from filename) and well.'''
		title							= 'Import LC file(s)...'
		filter_mask						= 'Lightcycler text files (*.txt)'	
		lightFileNames,f				= QFileDialog.getOpenFileNames(self,title,self.path,filter_mask)
		marker							= self.tabs.currentWidget()
		fileDataLists,ok				= LCDialog.importLC(lightFileNames)
		if ok:
			marker.addLCFiles(fileDataLists)
		self.__updateView()
	
	def setIncludes(self):
		'''Sets the Continues column on the current table.'''
		marker							= self.tabs.currentWidget()
		results							= marker.getResults()
		incResults,ok					= IncludeDialog.run(results)
		if ok:
			marker.setIncludes(incResults)
		self.__updateView()
	
########################################################################
##	Marker Menu Actions
	def exportResults(self):
		'''Exports all results to an excel sheet.''' 
		title							= 'Excel filename...'
		exportFileName,f				= QFileDialog.getSaveFileName(self,title,self.path)
		markers							= [marker.name for marker in self.markers[1:]]
		finalResult,ok					= ChooseMarkerDialog.run(markers)
		stats							= [(marker.name,marker.getStats()) for marker in self.markers]
		fullTable						= self.markers[0].prepareSamplesOutput()
		for m in self.markers[1:]:
			marker						= m.prepareMarkersOutput(finalResult)
			fullTable					= fullTable.join(marker)
		fullTable						= fullTable.reset_index()
		fullTable['Selected']			= fullTable[['Selected']].fillna(False)
		fullTable['Row']				= fullTable.index.values
		fullTable['Row']				= fullTable['Row'].map(lambda x: x+1).astype('int')
		fullTable						= fullTable.fillna('')
		workBook						= ResultBook()
		workBook.addStatsTable(stats)
		workBook.addResultTable(fullTable)
		workBook.addPlateSheets(fullTable,'Plate','Well','Plate','Well')
		workBook.save(exportFileName+'.xls')