def __init__(self, parent, modal=True, flags=Qt.WindowFlags(), caption="Select Tags", ok_button="Select"): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle(caption) lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # tag selector self.wtagsel = QListWidget(self) lo.addWidget(self.wtagsel) # self.wtagsel.setColumnMode(QListBox.FitToWidth) self.wtagsel.setSelectionMode(QListWidget.MultiSelection) QObject.connect(self.wtagsel, SIGNAL("itemSelectionChanged()"), self._check_tag) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton(ok_button, self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) self._tagnames = []
def __init__(self, parent, config_name=None, buttons=[], *args): """Creates dialog. 'config_name' is used to get/set default window size from Config object 'buttons' can be a list of names or (QPixmapWrapper,name[,tooltip]) tuples to provide custom buttons at the bottom of the dialog. When a button is clicked, the dialog emits SIGNAL("name"). A "Close" button is always provided, this simply hides the dialog. """ QDialog.__init__(self, parent, *args) self.setModal(False) lo = QVBoxLayout(self) # create viewer self.label = QLabel(self) self.label.setMargin(5) self.label.setWordWrap(True) lo.addWidget(self.label) self.label.hide() self.viewer = QTextBrowser(self) lo.addWidget(self.viewer) # self.viewer.setReadOnly(True) self.viewer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) QObject.connect(self.viewer, SIGNAL("anchorClicked(const QUrl &)"), self._urlClicked) self._source = None lo.addSpacing(5) # create button bar btnfr = QFrame(self) btnfr.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) # btnfr.setMargin(5) lo.addWidget(btnfr) lo.addSpacing(5) btnfr_lo = QHBoxLayout(btnfr) btnfr_lo.setMargin(5) # add user buttons self._user_buttons = {} for name in buttons: if isinstance(name, str): btn = QPushButton(name, btnfr) elif isinstance(name, (list, tuple)): if len(name) < 3: pixmap, name = name tip = None else: pixmap, name, tip = name btn = QPushButton(pixmap.icon(), name, btnfr) if tip: btn.setToolTip(tip) self._user_buttons[name] = btn btn._clicked = Kittens.utils.curry(self.emit, SIGNAL(name)) self.connect(btn, SIGNAL("clicked()"), btn._clicked) btnfr_lo.addWidget(btn, 1) # add a Close button btnfr_lo.addStretch(100) closebtn = QPushButton(pixmaps.grey_round_cross.icon(), "Close", btnfr) self.connect(closebtn, SIGNAL("clicked()"), self.hide) btnfr_lo.addWidget(closebtn, 1) # resize selves self.config_name = config_name or "html-viewer" width = Config.getint('%s-width' % self.config_name, 512) height = Config.getint('%s-height' % self.config_name, 512) self.resize(QSize(width, height))
def __init__(self, script="", parent=None): super(QTextEditCS, self).__init__(parent) self.resize(800, 600) self.script = script self.edit = QtGui.QTextEdit(self) # met une police de caractère même largeur pour tous les caractères font = QtGui.QFont() font.setFamily(u"DejaVu Sans Mono") # police de Qt4 font.setStyleHint(QtGui.QFont.Courier) # si la police est indisponible font.setPointSize(10) self.edit.setFont(font) # met en place la coloration syntaxique self.colorSyntax = ColorSyntax(self.edit.document()) # affiche le script colorisé self.setText(self.script) # positionne le QTextEdit dans la fenêtre layout = QHBoxLayout(self) layout.setMargin(0) layout.setSpacing(0) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.edit) layout.addWidget(self.number_bar) layout.addWidget(self.edit) self.setLayout(layout) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self)
def _createHeader(self, iconPath, title): """ Creates the Property Manager header, which contains an icon (a QLabel with a pixmap) and white text (a QLabel with text). @param iconPath: The relative path for the icon (PNG image) that appears in the header. @type iconPath: str @param title: The title that appears in the header. @type title: str """ # Heading frame (dark gray), which contains # a pixmap and (white) heading text. self.headerFrame = QFrame(self) self.headerFrame.setFrameShape(QFrame.NoFrame) self.headerFrame.setFrameShadow(QFrame.Plain) self.headerFrame.setPalette(QPalette(pmHeaderFrameColor)) self.headerFrame.setAutoFillBackground(True) # HBox layout for heading frame, containing the pixmap # and label (title). HeaderFrameHLayout = QHBoxLayout(self.headerFrame) # 2 pixels around edges -- HeaderFrameHLayout.setMargin(PM_HEADER_FRAME_MARGIN) # 5 pixel between pixmap and label. -- HeaderFrameHLayout.setSpacing(PM_HEADER_FRAME_SPACING) # PropMgr icon. Set image by calling setHeaderIcon(). self.headerIcon = QLabel(self.headerFrame) self.headerIcon.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed), QSizePolicy.Policy(QSizePolicy.Fixed))) self.headerIcon.setScaledContents(True) HeaderFrameHLayout.addWidget(self.headerIcon) # PropMgr header title text (a QLabel). self.headerTitle = QLabel(self.headerFrame) headerTitlePalette = self._getHeaderTitlePalette() self.headerTitle.setPalette(headerTitlePalette) self.headerTitle.setAlignment(PM_LABEL_LEFT_ALIGNMENT) # Assign header title font. self.headerTitle.setFont(self._getHeaderFont()) HeaderFrameHLayout.addWidget(self.headerTitle) self.vBoxLayout.addWidget(self.headerFrame) # Set header icon and title text. self.setHeaderIcon(iconPath) self.setHeaderTitle(title)
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Add FITS brick") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # file selector self.wfile = FileSelector(self, label="FITS filename:", dialog_label="FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile) lo.addWidget(self.wfile) # overwrite or add mode lo1 = QGridLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) lo1.addWidget(QLabel("Padding factor:", self), 0, 0) self.wpad = QLineEdit("2", self) self.wpad.setValidator(QDoubleValidator(self)) lo1.addWidget(self.wpad, 0, 1) lo1.addWidget(QLabel("Assign source name:", self), 1, 0) self.wname = QLineEdit(self) lo1.addWidget(self.wname, 1, 1) # OK/cancel buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) # signals QObject.connect(self.wfile, SIGNAL("filenameSelected"), self._fileSelected) # internal state self.qerrmsg = QErrorMessage(self)
def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = self.PlainTextEdit() self.number_bar = self.NumberBar(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.blockCountChanged.connect(self.number_bar.adjustWidth) self.edit.updateRequest.connect(self.number_bar.updateContents)
def pmAddHeader(propMgr): """Creates the Property Manager header, which contains a pixmap and white text label. """ # Heading frame (dark gray), which contains # a pixmap and (white) heading text. propMgr.header_frame = QFrame(propMgr) propMgr.header_frame.setFrameShape(QFrame.NoFrame) propMgr.header_frame.setFrameShadow(QFrame.Plain) header_frame_palette = propMgr.getPropMgrTitleFramePalette() propMgr.header_frame.setPalette(header_frame_palette) propMgr.header_frame.setAutoFillBackground(True) # HBox layout for heading frame, containing the pixmap # and label (title). HeaderFrameHLayout = QHBoxLayout(propMgr.header_frame) HeaderFrameHLayout.setMargin(pmHeaderFrameMargin) # 2 pixels around edges. HeaderFrameHLayout.setSpacing( pmHeaderFrameSpacing) # 5 pixel between pixmap and label. # PropMgr icon. Set image by calling setPropMgrIcon() at any time. propMgr.header_pixmap = QLabel(propMgr.header_frame) propMgr.header_pixmap.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed), QSizePolicy.Policy(QSizePolicy.Fixed))) propMgr.header_pixmap.setScaledContents(True) HeaderFrameHLayout.addWidget(propMgr.header_pixmap) # PropMgr title label propMgr.header_label = QLabel(propMgr.header_frame) header_label_palette = propMgr.getPropMgrTitleLabelPalette() propMgr.header_label.setPalette(header_label_palette) propMgr.header_label.setAlignment(pmLabelLeftAlignment) # PropMgr heading font (for label). propMgr.header_label.setFont(getHeaderFont()) HeaderFrameHLayout.addWidget(propMgr.header_label) propMgr.pmVBoxLayout.addWidget(propMgr.header_frame)
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Add Tag") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # tag selector lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setSpacing(5) self.wtagsel = QComboBox(self) self.wtagsel.setEditable(True) wtagsel_lbl = QLabel("&Tag:", self) wtagsel_lbl.setBuddy(self.wtagsel) lo1.addWidget(wtagsel_lbl, 0) lo1.addWidget(self.wtagsel, 1) QObject.connect(self.wtagsel, SIGNAL("activated(int)"), self._check_tag) QObject.connect(self.wtagsel, SIGNAL("editTextChanged(const QString &)"), self._check_tag_text) # value editor self.valedit = ValueTypeEditor(self) lo.addWidget(self.valedit) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384)
def pmAddHeader(propMgr): """Creates the Property Manager header, which contains a pixmap and white text label. """ # Heading frame (dark gray), which contains # a pixmap and (white) heading text. propMgr.header_frame = QFrame(propMgr) propMgr.header_frame.setFrameShape(QFrame.NoFrame) propMgr.header_frame.setFrameShadow(QFrame.Plain) header_frame_palette = propMgr.getPropMgrTitleFramePalette() propMgr.header_frame.setPalette(header_frame_palette) propMgr.header_frame.setAutoFillBackground(True) # HBox layout for heading frame, containing the pixmap # and label (title). HeaderFrameHLayout = QHBoxLayout(propMgr.header_frame) HeaderFrameHLayout.setMargin(pmHeaderFrameMargin) # 2 pixels around edges. HeaderFrameHLayout.setSpacing(pmHeaderFrameSpacing) # 5 pixel between pixmap and label. # PropMgr icon. Set image by calling setPropMgrIcon() at any time. propMgr.header_pixmap = QLabel(propMgr.header_frame) propMgr.header_pixmap.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed), QSizePolicy.Policy(QSizePolicy.Fixed))) propMgr.header_pixmap.setScaledContents(True) HeaderFrameHLayout.addWidget(propMgr.header_pixmap) # PropMgr title label propMgr.header_label = QLabel(propMgr.header_frame) header_label_palette = propMgr.getPropMgrTitleLabelPalette() propMgr.header_label.setPalette(header_label_palette) propMgr.header_label.setAlignment(pmLabelLeftAlignment) # PropMgr heading font (for label). propMgr.header_label.setFont(getHeaderFont()) HeaderFrameHLayout.addWidget(propMgr.header_label) propMgr.pmVBoxLayout.addWidget(propMgr.header_frame)
def __init__(self, main, interpreterLocals, ventana_interprete, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.editor = WidgetEditor(self, interpreterLocals, ventana_interprete) self.editor.setFrameStyle(QFrame.NoFrame) self.editor.setAcceptRichText(False) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.editor) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.editor) self.editor.installEventFilter(self) self.editor.viewport().installEventFilter(self)
def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextEdit() self.edit.setFrameStyle(QFrame.NoFrame) self.edit.setAcceptRichText(False) self.number_bar = NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self)
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Export Karma annotations") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # file selector self.wfile = FileSelector(self, label="Filename:", dialog_label="Karma annotations filename", default_suffix="ann", file_types="Karma annotations (*.ann)") lo.addWidget(self.wfile) # selected sources checkbox self.wsel = QCheckBox("selected sources only", self) lo.addWidget(self.wsel) # OK/cancel buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) # signals QObject.connect(self.wfile, SIGNAL("valid"), self.wokbtn.setEnabled) # internal state self.qerrmsg = QErrorMessage(self) self._model_filename = None
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Convert sources to FITS brick") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # file selector self.wfile = FileSelector(self, label="FITS filename:", dialog_label="Output FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile) lo.addWidget(self.wfile) # reference frequency lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) label = QLabel("Frequency, MHz:", self) lo1.addWidget(label) tip = """<P>If your sky model contains spectral information (such as spectral indices), then a brick may be generated for a specific frequency. If a frequency is not specified here, the reference frequency of the model sources will be assumed.</P>""" self.wfreq = QLineEdit(self) self.wfreq.setValidator(QDoubleValidator(self)) label.setToolTip(tip) self.wfreq.setToolTip(tip) lo1.addWidget(self.wfreq) # beam gain lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.wpb_apply = QCheckBox("Apply primary beam expression:", self) self.wpb_apply.setChecked(True) lo1.addWidget(self.wpb_apply) tip = """<P>If this option is specified, a primary power beam gain will be applied to the sources before inserting them into the brick. This can be any valid Python expression making use of the variables 'r' (corresponding to distance from field centre, in radians) and 'fq' (corresponding to frequency.)</P>""" self.wpb_exp = QLineEdit(self) self.wpb_apply.setToolTip(tip) self.wpb_exp.setToolTip(tip) lo1.addWidget(self.wpb_exp) # overwrite or add mode lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.woverwrite = QRadioButton("overwrite image", self) self.woverwrite.setChecked(True) lo1.addWidget(self.woverwrite) self.waddinto = QRadioButton("add into image", self) lo1.addWidget(self.waddinto) # add to model self.wadd = QCheckBox("Add resulting brick to sky model as a FITS image component", self) lo.addWidget(self.wadd) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.wpad = QLineEdit(self) self.wpad.setValidator(QDoubleValidator(self)) self.wpad.setText("1.1") lab = QLabel("...with padding factor:", self) lab.setToolTip("""<P>The padding factor determines the amount of null padding inserted around the image during the prediction stage. Padding alleviates the effects of tapering and detapering in the uv-brick, which can show up towards the edges of the image. For a factor of N, the image will be padded out to N times its original size. This increases memory use, so if you have no flux at the edges of the image anyway, then a pad factor of 1 is perfectly fine.</P>""") self.wpad.setToolTip(lab.toolTip()) QObject.connect(self.wadd, SIGNAL("toggled(bool)"), self.wpad.setEnabled) QObject.connect(self.wadd, SIGNAL("toggled(bool)"), lab.setEnabled) self.wpad.setEnabled(False) lab.setEnabled(False) lo1.addStretch(1) lo1.addWidget(lab, 0) lo1.addWidget(self.wpad, 1) self.wdel = QCheckBox("Remove from the sky model sources that go into the brick", self) lo.addWidget(self.wdel) # OK/cancel buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) # signals QObject.connect(self.wfile, SIGNAL("filenameSelected"), self._fileSelected) # internal state self.qerrmsg = QErrorMessage(self)
def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("My Main Window") self.setMinimumWidth(MAIN_WINDOW_SIZE[0]) self.setMinimumHeight(MAIN_WINDOW_SIZE[1]) self.statusbar = QtGui.QStatusBar(self) self.statusbar.showMessage("Status message") self.setStatusBar(self.statusbar) ################################################ self.menubar = self.menuBar() # Any menu action makes the status bar message disappear fileMenu = QtGui.QMenu(self.menubar) fileMenu.setTitle("File") self.menubar.addAction(fileMenu.menuAction()) newAction = QtGui.QAction("New", self) newAction.setIcon(QtGui.QtIcon(icons + '/GroupPropDialog_image0.png')) fileMenu.addAction(newAction) openAction = QtGui.QAction("Open", self) openAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image1")) fileMenu.addAction(openAction) saveAction = QtGui.QAction("Save", self) saveAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image2")) fileMenu.addAction(saveAction) self.connect(newAction,SIGNAL("activated()"),self.fileNew) self.connect(openAction,SIGNAL("activated()"),self.fileOpen) self.connect(saveAction,SIGNAL("activated()"),self.fileSave) for otherMenuName in ('Edit', 'View', 'Display', 'Select', 'Modify', 'NanoHive-1'): otherMenu = QtGui.QMenu(self.menubar) otherMenu.setTitle(otherMenuName) self.menubar.addAction(otherMenu.menuAction()) helpMenu = QtGui.QMenu(self.menubar) helpMenu.setTitle("Help") self.menubar.addAction(helpMenu.menuAction()) aboutAction = QtGui.QAction("About", self) aboutAction.setIcon(QtGui.QtIcon(icons + '/MainWindowUI_image0.png')) helpMenu.addAction(aboutAction) self.connect(aboutAction,SIGNAL("activated()"),self.helpAbout) ############################################## self.setMenuBar(self.menubar) centralwidget = QWidget() self.setCentralWidget(centralwidget) layout = QVBoxLayout(centralwidget) layout.setMargin(0) layout.setSpacing(0) middlewidget = QWidget() self.bigButtons = QWidget() bblo = QHBoxLayout(self.bigButtons) bblo.setMargin(0) bblo.setSpacing(0) self.bigButtons.setMinimumHeight(50) self.bigButtons.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) for name in ('Features', 'Sketch', 'Build', 'Dimension', 'Simulator'): btn = QPushButton(self.bigButtons) btn.setMaximumWidth(80) btn.setMinimumHeight(50) btn.setText(name) self.bigButtons.layout().addWidget(btn) self.bigButtons.hide() layout.addWidget(self.bigButtons) self.littleIcons = QWidget() self.littleIcons.setMinimumHeight(30) self.littleIcons.setMaximumHeight(30) lilo = QHBoxLayout(self.littleIcons) lilo.setMargin(0) lilo.setSpacing(0) pb = QPushButton(self.littleIcons) pb.setIcon(QIcon(icons + '/GroupPropDialog_image0.png')) self.connect(pb,SIGNAL("clicked()"),self.fileNew) lilo.addWidget(pb) for x in "1 2 4 5 6 7 8 18 42 10 43 150 93 94 97 137".split(): pb = QPushButton(self.littleIcons) pb.setIcon(QIcon(icons + '/MainWindowUI_image' + x + '.png')) lilo.addWidget(pb) layout.addWidget(self.littleIcons) layout.addWidget(middlewidget) self.layout = QGridLayout(middlewidget) self.layout.setMargin(0) self.layout.setSpacing(2) self.gridPosition = GridPosition() self.numParts = 0 self.show() explainWindow = AboutWindow("Select <b>Help->About</b>" " for instructions...", 200, 3)
class PM_ColorChooser(QWidget): """ The PM_ColorChooser widget provides a color chooser widget for a Property Manager group box. The PM_ColorChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QFrame and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_ColorChooser1.jpg) The user can color using Qt's color (chooser) dialog by clicking the "..." button. The selected color will be used as the color of the QFrame widget. The parent must make the following signal-slot connection to be notified when the user has selected a new color via the color chooser dialog: self.connect(pmColorChooser.colorFrame, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar setAsDefault: Determines whether to reset the value of the color to I{defaultColor} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar colorFrame: The Qt frame widget for this PM widget. @type colorFrame: U{B{QFrame}<http://doc.trolltech.com/4/qframe.html>} @cvar chooseButton: The Qt tool button widget for this PM widget. @type chooseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultColor = None setAsDefault = True hidden = False chooseButton = None customColorCount = 0 standardColorList = [white, black] def __init__( self, parentWidget, label='Color:', labelColumn=0, color=white, setAsDefault=True, spanWidth=False, ): """ Appends a color chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the color frame (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param color: initial color. White is the default. @type color: tuple of 3 floats (r, g, b) @param setAsDefault: if True, will restore L{color} when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @see: U{B{QColorDialog}<http://doc.trolltech.com/4/qcolordialog.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.color = color self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Create the color frame (color swath) and "..." button. self.colorFrame = QFrame() self.colorFrame.setFrameShape(QFrame.Box) self.colorFrame.setFrameShadow(QFrame.Plain) # Set browse button text and make signal-slot connection. self.chooseButton = QToolButton() self.chooseButton.setText("...") self.connect(self.chooseButton, SIGNAL("clicked()"), self.openColorChooserDialog) # Add a horizontal spacer to keep the colorFrame and "..." squeezed # together, even when the PM width changes. self.hSpacer = QSpacerItem(10, 10, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.colorFrame) self.hBoxLayout.insertWidget(-1, self.chooseButton) # Set this to False to make the colorFrame an expandable rectangle. COLORFRAME_IS_SQUARE = True if COLORFRAME_IS_SQUARE: squareSize = 20 self.colorFrame.setMinimumSize(QSize(squareSize, squareSize)) self.colorFrame.setMaximumSize(QSize(squareSize, squareSize)) self.hBoxLayout.addItem(self.hSpacer) self.setColor(color, default=setAsDefault) parentWidget.addPmWidget(self) return def setColor(self, color, default=False): """ Set the color. @param color: The color. @type color: tuple of 3 floats (r, g, b) @param default: If True, make I{color} the default color. Default is False. @type default: boolean """ if default: self.defaultColor = color self.setAsDefault = default self.color = color self._updateColorFrame() return def getColor(self): """ Return the current color. @return: The current r, g, b color. @rtype: Tuple of 3 floats (r, g, b) """ return self.color def getQColor(self): """ Return the current QColor. @return: The current color. @rtype: QColor """ return RGBf_to_QColor(self.color) def _updateColorFrame(self): """ Updates the color frame with the current color. """ colorframe = self.colorFrame try: qcolor = self.getQColor() palette = QPalette( ) # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here qcolorrole = QPalette.Window ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says: ## QPalette.Window 10 A general background color. palette.setColor(QPalette.Active, qcolorrole, qcolor) # used when window is in fg and has focus palette.setColor( QPalette.Inactive, qcolorrole, qcolor) # used when window is in bg or does not have focus palette.setColor(QPalette.Disabled, qcolorrole, qcolor) # used when widget is disabled colorframe.setPalette(palette) colorframe.setAutoFillBackground(True) except: print "data for following exception: ", print "colorframe %r has palette %r" % (colorframe, colorframe.palette()) pass def openColorChooserDialog(self): """ Prompts the user to choose a color and then updates colorFrame with the selected color. """ qcolor = RGBf_to_QColor(self.color) if not self.color in self.standardColorList: QColorDialog.setCustomColor(self.customColorCount, qcolor.rgb()) self.customColorCount += 1 c = QColorDialog.getColor(qcolor, self) if c.isValid(): self.setColor(QColor_to_RGBf(c)) self.colorFrame.emit(SIGNAL("editingFinished()")) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setColor(self.defaultColor) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return
class LetsShareBooksDialog(QDialog): def __init__(self, gui, icon, do_user_config, qaction, us): QDialog.__init__(self, gui) self.gui = gui self.do_user_config = do_user_config self.qaction = qaction self.us = us self.clip = QApplication.clipboard() self.main_gui = calibre_main() self.urllib_thread = UrlLibThread(self.us) self.kill_servers_thread = KillServersThread(self.us) self.us.check_finished = True self.pxmp = QPixmap() self.pxmp.load('images/icon_connected.png') self.icon_connected = QIcon(self.pxmp) self.setStyleSheet(""" QDialog { background-color: white; } QPushButton { font-size: 16px; border-style: solid; border-color: red; font-family:'BitstreamVeraSansMono',Consolas,monospace; text-transform: uppercase; } QPushButton#arrow { border-width: 16px; border-right-color:white; padding: -10px; color:red; } QPushButton#url { background-color: red; min-width: 460px; color: white; text-align: left; } QPushButton#url:hover { background-color: white; color: red; } QPushButton#share { background-color: red; color: white; margin-right: 10px; } QPushButton#share:hover { background-color: white; color: red; } QPushButton#url2 { color: #222; text-align: left; } QPushButton#url2:hover { color: red; } """) self.ll = QVBoxLayout() #self.ll.setSpacing(1) self.l = QHBoxLayout() self.l.setSpacing(0) self.l.setMargin(0) #self.l.setContentsMargins(0,0,0,0) self.w = QWidget() self.w.setLayout(self.l) self.setLayout(self.ll) self.setWindowIcon(icon) self.lets_share_button = QPushButton() self.lets_share_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.lets_share_button.setObjectName("share") self.lets_share_button.clicked.connect(self.lets_share) self.stop_share_button = QPushButton() self.stop_share_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.stop_share_button.setObjectName("share") self.stop_share_button.clicked.connect(self.stop_share) self.l.addWidget(self.lets_share_button) self.l.addWidget(self.stop_share_button) if self.us.button_state == "start": self.lets_share_button.show() self.stop_share_button.hide() self.lets_share_button.setText(self.us.share_button_text) else: self.lets_share_button.hide() self.stop_share_button.show() self.stop_share_button.setText(self.us.share_button_text) self.url_label = QPushButton() self.url_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.url_label.setObjectName("url") self.url_label.clicked.connect(self.open_url) self.l.addWidget(self.url_label) self.arrow_button = QPushButton("_____") self.arrow_button.setObjectName("arrow") self.l.addWidget(self.arrow_button) self.ll.addWidget(self.w) self.ll.addSpacing(10) self.chat_button = QPushButton("Chat room: https://chat.memoryoftheworld.org") #self.chat_button.hovered.connect(self.setCursorToHand) self.chat_button.setObjectName("url2") self.chat_button.setToolTip('Meetings every thursday at 23:59 (central eruopean time)') self.chat_button.clicked.connect(functools.partial(self.open_url2, "https://chat.memoryoftheworld.org")) self.ll.addWidget(self.chat_button) self.about_project_button = QPushButton('Public Library: http://www.memoryoftheworld.org') self.about_project_button.setObjectName("url2") self.about_project_button.setToolTip('When everyone is librarian, library is everywhere.') self.about_project_button.clicked.connect(functools.partial(self.open_url2, "http://www.memoryoftheworld.org")) self.ll.addWidget(self.about_project_button) self.debug_log = QListWidget() self.ll.addWidget(self.debug_log) self.debug_log.addItem("Initiatied!") self.metadata_thread = MetadataLibThread(self.debug_log) self.metadata_button = QPushButton("Get library metadata!") self.metadata_button.setObjectName("url2") self.metadata_button.setToolTip('Get library metadata!') self.metadata_button.clicked.connect(self.get_metadata) self.ll.addWidget(self.metadata_button) self.upgrade_button = QPushButton('Please download and upgrade from {0} to {1} version of plugin.'.format(self.us.running_version, self.us.latest_version)) self.upgrade_button.setObjectName("url2") self.upgrade_button.setToolTip('Running latest version you make developers happy') self.upgrade_button.clicked.connect(functools.partial(self.open_url2, self.us.plugin_url)) version_list = [self.us.running_version, self.us.latest_version] version_list.sort(key=lambda s: map(int, s.split('.'))) if self.us.running_version != self.us.latest_version: if self.us.running_version == version_list[0]: self.ll.addSpacing(20) self.ll.addWidget(self.upgrade_button) self.resize(self.sizeHint()) self.se = open("lsb.log", "w+b") self.so = self.se sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) os.dup2(self.so.fileno(), sys.stdout.fileno()) os.dup2(self.se.fileno(), sys.stderr.fileno()) self.timer = QTimer() self.timer.timeout.connect(self.check_and_render) self.timer_period = 300 self.timer.start(self.timer_period) self.error_log = "" def lets_share(self): self.lets_share_button.setEnabled(False) self.timer.stop() self.us.share_button_text = "Connecting..." #self.debug_log.addItem("Let's share!") self.us.counter = 0 self.us.lost_connection = False if not self.us.ssh_proc: self.main_gui.start_content_server() opts, args = server_config().option_parser().parse_args(['calibre-server']) self.calibre_server_port = opts.port if sys.platform == "win32": self.win_reg = subprocess.Popen("regedit /s .hosts.reg") self.us.win_port = int(random.random()*40000+10000) self.us.ssh_proc = subprocess.Popen("lsbtunnel.exe -N -T tunnel@{2} -R {0}:localhost:{1} -P 722".format(self.us.win_port, self.calibre_server_port, prefs['lsb_server']), shell=True) self.us.lsb_url = "https://www{0}.{1}".format(self.us.win_port, prefs['lsb_server']) #_dev_self.us.lsb_url = "http://www{0}.{1}".format(self.us.win_port, prefs['lsb_server']) self.us.lsb_url_text = "Go to: {0}".format(self.us.lsb_url) self.us.found_url = True else: self.us.ssh_proc = subprocess.Popen(['ssh', '-T', '-N', '-g', '-o', 'UserKnownHostsFile=.userknownhostsfile', '-o', 'TCPKeepAlive=yes', '-o', 'ServerAliveINterval=60', prefs['lsb_server'], '-l', 'tunnel', '-R', '0:localhost:{0}'.format(self.calibre_server_port), '-p', '722']) self.us.found_url = None self.qaction.setIcon(get_icon('images/icon_connected.png')) self.us.connecting = True self.us.connecting_now = datetime.datetime.now() self.timer.start(self.timer_period) def stop_share(self): self.stop_share_button.setEnabled(False) #self.debug_log.addItem("Stop Share!") self.timer.stop() self.us.lsb_url = 'nourl' self.us.urllib_result = '' self.us.disconnecting = True self.qaction.setIcon(get_icon('images/icon.png')) self.kill_servers_thread.start() self.timer.start(self.timer_period) def check_and_render(self): #self.show_debug() if self.us.button_state == "start": self.stop_share_button.hide() self.lets_share_button.show() self.lets_share_button.setText(self.us.share_button_text) else: self.lets_share_button.hide() self.stop_share_button.show() self.stop_share_button.setText(self.us.share_button_text) if self.us.disconnecting: self.us.share_button_text = "Disconnecting..." if self.us.lost_connection: self.us.lsb_url_text = 'Lost connection. Please start sharing again.' self.us.url_label_tooltip = '<<<< Click on Start sharing button again.' else: self.us.lsb_url_text = 'Be a librarian. Share your library.' self.us.url_label_tooltip = '<<<< Be a librarian. Click on Start sharing button.<<<<' if self.us.kill_finished: #self.debug_log.addItem("Let's share connect!") self.us.button_state = "start" self.us.share_button_text = "Start sharing" self.us.disconnecting = False self.us.kill_finished = False self.lets_share_button.setEnabled(True) elif self.us.connecting: if self.us.connecting_now: if (datetime.datetime.now() - self.us.connecting_now) > datetime.timedelta(seconds=10): #self.debug_log.addItem("Timeout!") self.us.http_error = None self.us.lost_connection = True self.us.connecting = False self.us.connecting_now = None self.stop_share() elif self.us.found_url: self.us.check_finished = False self.urllib_thread.start() if self.us.lsb_url == "nourl" and self.us.ssh_proc and sys.platform != "win32": #self.debug_log.addItem("Wait for Allocated port!") self.se.seek(0) result = self.se.readlines() for line in result: m = re.match("^Allocated port (.*) for .*", line) try: #self.debug_log.addItem(self.us.lsb_url) self.us.lsb_url = 'https://www{0}.{1}'.format(m.groups()[0], prefs['lsb_server']) #_dev_self.us.lsb_url = 'http://www{0}.{1}'.format(m.groups()[0], prefs['lsb_server']) self.us.lsb_url_text = "Go to: {0}".format(self.us.lsb_url) self.us.url_label_tooltip = 'Copy URL to clipboard and check it out in a browser!' self.us.http_error = None self.us.found_url = True except: pass elif self.us.urllib_result == 200: #self.debug_log.addItem("Finish Connecting State!") self.se.seek(0) self.se.truncate() self.us.share_button_text = "Stop sharing" self.us.button_state = "stop" self.stop_share_button.setEnabled(True) self.us.connecting = False self.us.connecting_now = None self.us.found_url = None elif self.us.http_error and self.us.button_state == "stop": #self.debug_log.addItem("Error!") self.us.http_error = None self.us.lost_connection = True self.stop_share() elif self.us.check_finished: #if self.debug_log.item(self.debug_log.count()-1).text()[:10] == "Finally Ca": # self.us.debug_counter = self.us.debug_counter + 1 #else: # self.debug_log.addItem("Finally Called Thread!({0})".format(self.us.debug_counter)) # self.us.debug_counter = 1 self.us.check_finished = False self.urllib_thread.start() if self.us.urllib_result == 200 and self.us.button_state == "stop": self.stop_share_button.setEnabled(True) if self.us.lsb_url == 'nourl' and self.us.button_state == "start": self.lets_share_button.setEnabled(True) self.setWindowTitle("{0} - {1}".format(self.us.window_title, self.us.lsb_url)) self.url_label.setToolTip(self.us.url_label_tooltip) self.url_label.setText(self.us.lsb_url_text) def open_url(self): if self.us.lsb_url == "nourl" and not self.us.http_error: self.us.url_label_tooltip = '<<<< Be a librarian. Click on Start sharing button.' self.us.lsb_url_text = '<<<< Be a librarian. Click on Start sharing button.' else: self.clip.setText(self.us.lsb_url) webbrowser.open(str(self.us.lsb_url)) if self.us.lsb_url != "nourl": self.us.lsb_url_text = "Library at: {0}".format(self.us.lsb_url) def open_url2(self, url): self.clip.setText(url) webbrowser.open(url) def get_metadata(self): self.metadata_thread.start() def show_debug(self): if self.us.debug_item: self.debug_log.addItem(str(self.us.debug_item)) self.us.debug_item = None self.debug_log.scrollToBottom() self.debug_log.repaint() def closeEvent(self, e): self.hide() #self.urllib_thread.stop() #self.kill_servers_thread.stop() def config(self): self.do_user_config(parent=self) self.label.setText(prefs['lsb_server'])
def _createTopRowBtns(self): """ Creates the Done, Cancel, Preview, Restore Defaults and What's This buttons row at the top of the Property Manager. """ # Main "button group" widget (but it is not a QButtonGroup). self.pmTopRowBtns = QHBoxLayout() # This QHBoxLayout is (probably) not necessary. Try using just the frame # for the foundation. I think it should work. Mark 2007-05-30 # Horizontal spacer horizontalSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) # Frame containing all the buttons. self.topRowBtnsFrame = QFrame() self.topRowBtnsFrame.setFrameShape(QFrame.NoFrame) self.topRowBtnsFrame.setFrameShadow(QFrame.Plain) # Create Hbox layout for main frame. topRowBtnsHLayout = QHBoxLayout(self.topRowBtnsFrame) topRowBtnsHLayout.setMargin(PM_TOPROWBUTTONS_MARGIN) topRowBtnsHLayout.setSpacing(PM_TOPROWBUTTONS_SPACING) topRowBtnsHLayout.addItem(horizontalSpacer) # Set button type. if 1: # Mark 2007-05-30 # Needs to be QToolButton for MacOS. Fine for Windows, too. buttonType = QToolButton # May want to use QToolButton.setAutoRaise(1) below. Mark 2007-05-29 else: buttonType = QPushButton # Do not use. # Done (OK) button. self.done_btn = buttonType(self.topRowBtnsFrame) self.done_btn.setIcon( geticon("ui/actions/Properties Manager/Done.png")) self.done_btn.setIconSize(QSize(22, 22)) self.connect(self.done_btn, SIGNAL("clicked()"), self.doneButtonClicked) self.done_btn.setToolTip("Done") topRowBtnsHLayout.addWidget(self.done_btn) # Cancel (Abort) button. self.cancel_btn = buttonType(self.topRowBtnsFrame) self.cancel_btn.setIcon( geticon("ui/actions/Properties Manager/Abort.png")) self.cancel_btn.setIconSize(QSize(22, 22)) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.cancelButtonClicked) self.cancel_btn.setToolTip("Cancel") topRowBtnsHLayout.addWidget(self.cancel_btn) #@ abort_btn deprecated. We still need it because modes use it. self.abort_btn = self.cancel_btn # Restore Defaults button. self.restore_defaults_btn = buttonType(self.topRowBtnsFrame) self.restore_defaults_btn.setIcon( geticon("ui/actions/Properties Manager/Restore.png")) self.restore_defaults_btn.setIconSize(QSize(22, 22)) self.connect(self.restore_defaults_btn, SIGNAL("clicked()"), self.restoreDefaultsButtonClicked) self.restore_defaults_btn.setToolTip("Restore Defaults") topRowBtnsHLayout.addWidget(self.restore_defaults_btn) # Preview (glasses) button. self.preview_btn = buttonType(self.topRowBtnsFrame) self.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview.png")) self.preview_btn.setIconSize(QSize(22, 22)) self.connect(self.preview_btn, SIGNAL("clicked()"), self.previewButtonClicked) self.preview_btn.setToolTip("Preview") topRowBtnsHLayout.addWidget(self.preview_btn) # What's This (?) button. self.whatsthis_btn = buttonType(self.topRowBtnsFrame) self.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis.png")) self.whatsthis_btn.setIconSize(QSize(22, 22)) self.connect(self.whatsthis_btn, SIGNAL("clicked()"), self.whatsThisButtonClicked) self.whatsthis_btn.setToolTip("Enter \"What's This\" help mode") topRowBtnsHLayout.addWidget(self.whatsthis_btn) topRowBtnsHLayout.addItem(horizontalSpacer) # Create Button Row self.pmTopRowBtns.addWidget(self.topRowBtnsFrame) self.vBoxLayout.addLayout(self.pmTopRowBtns) # Add What's This for buttons. self.done_btn.setWhatsThis("""<b>Done</b> <p> <img source=\"ui/actions/Properties Manager/Done.png\"><br> Completes and/or exits the current command.</p>""") self.cancel_btn.setWhatsThis("""<b>Cancel</b> <p> <img source=\"ui/actions/Properties Manager/Abort.png\"><br> Cancels the current command.</p>""") self.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b> <p><img source=\"ui/actions/Properties Manager/Restore.png\"><br> Restores the defaut values of the Property Manager.</p>""") self.preview_btn.setWhatsThis("""<b>Preview</b> <p> <img source=\"ui/actions/Properties Manager/Preview.png\"><br> Preview the structure based on current Property Manager settings. </p>""") self.whatsthis_btn.setWhatsThis("""<b>What's This</b> <p> <img source=\"ui/actions/Properties Manager/WhatsThis.png\"><br> This invokes \"What's This?\" help mode which is part of NanoEngineer-1's online help system, and provides users with information about the functionality and usage of a particular command button or widget. </p>""") return
class PM_FileChooser( QWidget ): """ The PM_FileChooser widget provides a file chooser widget for a Property Manager group box. The PM_FileChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QLineEdit and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_FileChooser1.jpg) The user can type the path name of a file into the line edit widget or select a file using Qt's file (chooser) dialog by clicking the "..." button. The path name of the selected file will be inserted into the line edit widget. The parent must make the following signal-slot connection to be notified when the user has selected a new file via the file chooser dialog: self.connect(pmFileChooser.lineEdit, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar defaultText: The default text (path) of the line edit widget. @type defaultText: string @cvar setAsDefault: Determines whether to reset the value of the lineedit to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar lineEdit: The Qt line edit widget for this PM widget. @type lineEdit: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} @cvar browseButton: The Qt tool button widget for this PM widget. @type browseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultText = "" setAsDefault = True hidden = False lineEdit = None browseButton = None def __init__(self, parentWidget, label = '', labelColumn = 0, text = '', setAsDefault = True, spanWidth = False, caption = "Choose file", directory = '', filter = "All Files (*.*)" ): """ Appends a file chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the file chooser lineedit (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: initial value of LineEdit widget. @type text: string @param setAsDefault: if True, will restore <val> when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @param caption: The caption used as the title of the file chooser dialog. "Choose file" is the default. @type caption: string @param directory: The directory that the file chooser dialog should open in when the "..." button is clicked. If blank or if directory does not exist, the current working directory is used. @type directory: string @param filter: The file type filters to use for the file chooser dialog. @type filter: string (a semicolon-separated list of file types) @see: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.text = text self.setAsDefault = setAsDefault self.spanWidth = spanWidth self.caption = caption self.directory = directory self.filter = filter if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) self.lineEdit = QLineEdit() self.browseButton = QToolButton() # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.lineEdit) self.hBoxLayout.insertWidget(-1, self.browseButton) # Set (QLineEdit) text self.setText(text) # Set browse button text and make signal-slot connection. self.browseButton.setText("...") self.connect(self.browseButton, SIGNAL("clicked()"), self.openFileChooserDialog) # Set default value self.defaultText = text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) return def setText(self, text): """ Set the line edit text. @param text: The text. @type text: string """ self.lineEdit.setText(text) self.text = text return def openFileChooserDialog(self): """ Prompts the user to choose a file from disk and inserts the full path into the lineEdit widget. """ _dir = getDefaultWorkingDirectory() if self.directory: if os.path.isdir(self.directory): _dir = self.directory fname = QFileDialog.getOpenFileName(self, self.caption, _dir, self.filter) if fname: self.setText(fname) self.lineEdit.emit(SIGNAL("editingFinished()")) return def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return # End of PM_FileChooser ############################
class PM_ColorChooser( QWidget ): """ The PM_ColorChooser widget provides a color chooser widget for a Property Manager group box. The PM_ColorChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QFrame and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_ColorChooser1.jpg) The user can color using Qt's color (chooser) dialog by clicking the "..." button. The selected color will be used as the color of the QFrame widget. The parent must make the following signal-slot connection to be notified when the user has selected a new color via the color chooser dialog: self.connect(pmColorChooser.colorFrame, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar setAsDefault: Determines whether to reset the value of the color to I{defaultColor} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar colorFrame: The Qt frame widget for this PM widget. @type colorFrame: U{B{QFrame}<http://doc.trolltech.com/4/qframe.html>} @cvar chooseButton: The Qt tool button widget for this PM widget. @type chooseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultColor = None setAsDefault = True hidden = False chooseButton = None customColorCount = 0 standardColorList = [white, black] def __init__(self, parentWidget, label = 'Color:', labelColumn = 0, color = white, setAsDefault = True, spanWidth = False, ): """ Appends a color chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the color frame (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param color: initial color. White is the default. @type color: tuple of 3 floats (r, g, b) @param setAsDefault: if True, will restore L{color} when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @see: U{B{QColorDialog}<http://doc.trolltech.com/4/qcolordialog.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.color = color self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Create the color frame (color swath) and "..." button. self.colorFrame = QFrame() self.colorFrame.setFrameShape(QFrame.Box) self.colorFrame.setFrameShadow(QFrame.Plain) # Set browse button text and make signal-slot connection. self.chooseButton = QToolButton() self.chooseButton.setText("...") self.connect(self.chooseButton, SIGNAL("clicked()"), self.openColorChooserDialog) # Add a horizontal spacer to keep the colorFrame and "..." squeezed # together, even when the PM width changes. self.hSpacer = QSpacerItem(10, 10, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.colorFrame) self.hBoxLayout.insertWidget(-1, self.chooseButton) # Set this to False to make the colorFrame an expandable rectangle. COLORFRAME_IS_SQUARE = True if COLORFRAME_IS_SQUARE: squareSize = 20 self.colorFrame.setMinimumSize(QSize(squareSize, squareSize)) self.colorFrame.setMaximumSize(QSize(squareSize, squareSize)) self.hBoxLayout.addItem(self.hSpacer) self.setColor(color, default = setAsDefault) parentWidget.addPmWidget(self) return def setColor(self, color, default = False): """ Set the color. @param color: The color. @type color: tuple of 3 floats (r, g, b) @param default: If True, make I{color} the default color. Default is False. @type default: boolean """ if default: self.defaultColor = color self.setAsDefault = default self.color = color self._updateColorFrame() return def getColor(self): """ Return the current color. @return: The current r, g, b color. @rtype: Tuple of 3 floats (r, g, b) """ return self.color def getQColor(self): """ Return the current QColor. @return: The current color. @rtype: QColor """ return RGBf_to_QColor(self.color) def _updateColorFrame(self): """ Updates the color frame with the current color. """ colorframe = self.colorFrame try: qcolor = self.getQColor() palette = QPalette() # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here qcolorrole = QPalette.Window ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says: ## QPalette.Window 10 A general background color. palette.setColor(QPalette.Active, qcolorrole, qcolor) # used when window is in fg and has focus palette.setColor(QPalette.Inactive, qcolorrole, qcolor) # used when window is in bg or does not have focus palette.setColor(QPalette.Disabled, qcolorrole, qcolor) # used when widget is disabled colorframe.setPalette(palette) colorframe.setAutoFillBackground(True) except: print "data for following exception: ", print "colorframe %r has palette %r" % (colorframe, colorframe.palette()) pass def openColorChooserDialog(self): """ Prompts the user to choose a color and then updates colorFrame with the selected color. """ qcolor = RGBf_to_QColor(self.color) if not self.color in self.standardColorList: QColorDialog.setCustomColor(self.customColorCount, qcolor.rgb()) self.customColorCount += 1 c = QColorDialog.getColor(qcolor, self) if c.isValid(): self.setColor(QColor_to_RGBf(c)) self.colorFrame.emit(SIGNAL("editingFinished()")) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setColor(self.defaultColor) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return
def _createTopRowBtns(self): """ Creates the Done, Cancel, Preview, Restore Defaults and What's This buttons row at the top of the Property Manager. """ topBtnSize = QSize(22, 22) # button images should be 16 x 16, though. # Main "button group" widget (but it is not a QButtonGroup). self.pmTopRowBtns = QHBoxLayout() # This QHBoxLayout is (probably) not necessary. Try using just the frame # for the foundation. I think it should work. Mark 2007-05-30 # Horizontal spacer horizontalSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) # Widget containing all the buttons. self.topRowBtnsContainer = QWidget() # Create Hbox layout for main frame. topRowBtnsHLayout = QHBoxLayout(self.topRowBtnsContainer) topRowBtnsHLayout.setMargin(PM_TOPROWBUTTONS_MARGIN) topRowBtnsHLayout.setSpacing(PM_TOPROWBUTTONS_SPACING) # Set to True to center align the buttons in the PM if False: # Left aligns the buttons. topRowBtnsHLayout.addItem(horizontalSpacer) # Done (OK) button. self.done_btn = QToolButton(self.topRowBtnsContainer) self.done_btn.setIcon( geticon("ui/actions/Properties Manager/Done_16x16.png")) self.done_btn.setIconSize(topBtnSize) self.done_btn.setAutoRaise(True) self.connect(self.done_btn, SIGNAL("clicked()"), self.doneButtonClicked) self.done_btn.setToolTip("Done") topRowBtnsHLayout.addWidget(self.done_btn) # Cancel (Abort) button. self.cancel_btn = QToolButton(self.topRowBtnsContainer) self.cancel_btn.setIcon( geticon("ui/actions/Properties Manager/Abort_16x16.png")) self.cancel_btn.setIconSize(topBtnSize) self.cancel_btn.setAutoRaise(True) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.cancelButtonClicked) self.cancel_btn.setToolTip("Cancel") topRowBtnsHLayout.addWidget(self.cancel_btn) #@ abort_btn deprecated. We still need it because modes use it. self.abort_btn = self.cancel_btn # Restore Defaults button. self.restore_defaults_btn = QToolButton(self.topRowBtnsContainer) self.restore_defaults_btn.setIcon( geticon("ui/actions/Properties Manager/Restore_16x16.png")) self.restore_defaults_btn.setIconSize(topBtnSize) self.restore_defaults_btn.setAutoRaise(True) self.connect(self.restore_defaults_btn, SIGNAL("clicked()"), self.restoreDefaultsButtonClicked) self.restore_defaults_btn.setToolTip("Restore Defaults") topRowBtnsHLayout.addWidget(self.restore_defaults_btn) # Preview (glasses) button. self.preview_btn = QToolButton(self.topRowBtnsContainer) self.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview_16x16.png")) self.preview_btn.setIconSize(topBtnSize) self.preview_btn.setAutoRaise(True) self.connect(self.preview_btn, SIGNAL("clicked()"), self.previewButtonClicked) self.preview_btn.setToolTip("Preview") topRowBtnsHLayout.addWidget(self.preview_btn) # What's This (?) button. self.whatsthis_btn = QToolButton(self.topRowBtnsContainer) self.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis_16x16.png")) self.whatsthis_btn.setIconSize(topBtnSize) self.whatsthis_btn.setAutoRaise(True) self.connect(self.whatsthis_btn, SIGNAL("clicked()"), self.whatsThisButtonClicked) self.whatsthis_btn.setToolTip("Enter \"What's This\" help mode") topRowBtnsHLayout.addWidget(self.whatsthis_btn) topRowBtnsHLayout.addItem(horizontalSpacer) # Create Button Row self.pmTopRowBtns.addWidget(self.topRowBtnsContainer) self.vBoxLayout.addLayout(self.pmTopRowBtns) # Add What's This for buttons. self.done_btn.setWhatsThis("""<b>Done</b> <p> <img source=\"ui/actions/Properties Manager/Done_16x16.png\"><br> Completes and/or exits the current command.</p>""") self.cancel_btn.setWhatsThis("""<b>Cancel</b> <p> <img source=\"ui/actions/Properties Manager/Abort_16x16.png\"><br> Cancels the current command.</p>""") self.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b> <p><img source=\"ui/actions/Properties Manager/Restore_16x16.png\"><br> Restores the defaut values of the Property Manager.</p>""") self.preview_btn.setWhatsThis("""<b>Preview</b> <p> <img source=\"ui/actions/Properties Manager/Preview_16x16.png\"><br> Preview the structure based on current Property Manager settings. </p>""") self.whatsthis_btn.setWhatsThis("""<b>What's This</b> <p> <img source=\"ui/actions/Properties Manager/WhatsThis_16x16.png\"><br> This invokes \"What's This?\" help mode which is part of NanoEngineer-1's online help system, and provides users with information about the functionality and usage of a particular command button or widget. </p>""") return
def pmAddTopRowButtons(propMgr, showFlags=pmAllButtons): """Creates the OK, Cancel, Preview, and What's This buttons row at the top of the Property Manager <propMgr>. <showFlags> is an enum that can be used to show only certain Property Manager buttons, where: pmDoneButton = 1 pmCancelButton = 2 pmRestoreDefaultsButton = 4 pmPreviewButton = 8 pmWhatsThisButton = 16 pmAllButtons = 31 These flags are defined in PropMgr_Constants.py. This subroutine is used by the following Property Managers (which are still not using the PropMgrBaseClass): - Build Atoms - Build Crystal - Extrude - Move - Movie Player - Fuse Chunks Note: This subrouting is temporary. It will be removed after the PropMgrs in this list are converted to the PropMgrBaseClass. Mark 2007-06-24 """ # The Top Buttons Row includes the following widgets: # # - propMgr.pmTopRowBtns (Hbox Layout containing everything:) # # - frame # - hbox layout "frameHboxLO" (margin=2, spacing=2) # - Done (OK) button # - Abort (Cancel) button # - Restore Defaults button # - Preview button # - What's This button # - right spacer (10x10) # Main "button group" widget (but it is not a QButtonGroup). propMgr.pmTopRowBtns = QHBoxLayout() # Horizontal spacer HSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) # Frame containing all the buttons. propMgr.TopRowBtnsFrame = QFrame() propMgr.TopRowBtnsFrame.setFrameShape(QFrame.NoFrame) propMgr.TopRowBtnsFrame.setFrameShadow(QFrame.Plain) # Create Hbox layout for main frame. TopRowBtnsHLayout = QHBoxLayout(propMgr.TopRowBtnsFrame) TopRowBtnsHLayout.setMargin(pmTopRowBtnsMargin) TopRowBtnsHLayout.setSpacing(pmTopRowBtnsSpacing) TopRowBtnsHLayout.addItem(HSpacer) # Set button type. buttonType = QToolButton # May want to use QToolButton.setAutoRaise(1) below. Mark 2007-05-29 # OK (Done) button. propMgr.done_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.done_btn.setIcon( geticon("ui/actions/Properties Manager/Done.png")) propMgr.done_btn.setIconSize(QSize(22,22)) propMgr.connect(propMgr.done_btn, SIGNAL("clicked()"), propMgr.ok_btn_clicked) propMgr.done_btn.setToolTip("Done") TopRowBtnsHLayout.addWidget(propMgr.done_btn) # Cancel (Abort) button. propMgr.abort_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.abort_btn.setIcon( geticon("ui/actions/Properties Manager/Abort.png")) propMgr.abort_btn.setIconSize(QSize(22,22)) propMgr.connect(propMgr.abort_btn, SIGNAL("clicked()"), propMgr.abort_btn_clicked) propMgr.abort_btn.setToolTip("Cancel") TopRowBtnsHLayout.addWidget(propMgr.abort_btn) # Restore Defaults button. propMgr.restore_defaults_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.restore_defaults_btn.setIcon( geticon("ui/actions/Properties Manager/Restore.png")) propMgr.restore_defaults_btn.setIconSize(QSize(22,22)) propMgr.connect(propMgr.restore_defaults_btn, SIGNAL("clicked()"), propMgr.restore_defaults_btn_clicked) propMgr.restore_defaults_btn.setToolTip("Restore Defaults") TopRowBtnsHLayout.addWidget(propMgr.restore_defaults_btn) # Preview (glasses) button. propMgr.preview_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview.png")) propMgr.preview_btn.setIconSize(QSize(22,22)) propMgr.connect(propMgr.preview_btn, SIGNAL("clicked()"), propMgr.preview_btn_clicked) propMgr.preview_btn.setToolTip("Preview") TopRowBtnsHLayout.addWidget(propMgr.preview_btn) # What's This (?) button. propMgr.whatsthis_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis.png")) propMgr.whatsthis_btn.setIconSize(QSize(22,22)) propMgr.connect(propMgr.whatsthis_btn, SIGNAL("clicked()"), QWhatsThis.enterWhatsThisMode) propMgr.whatsthis_btn.setToolTip("What\'s This Help") TopRowBtnsHLayout.addWidget(propMgr.whatsthis_btn) TopRowBtnsHLayout.addItem(HSpacer) # Create Button Row propMgr.pmTopRowBtns.addWidget(propMgr.TopRowBtnsFrame) propMgr.pmVBoxLayout.addLayout(propMgr.pmTopRowBtns) # Add What's This for buttons. propMgr.done_btn.setWhatsThis("""<b>Done</b> <p><img source=\"ui/actions/Properties Manager/Done.png\"><br> Completes and/or exits the current command.</p>""") propMgr.abort_btn.setWhatsThis("""<b>Cancel</b> <p><img source=\"ui/actions/Properties Manager/Abort.png\"><br> Cancels the current command.</p>""") propMgr.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b> <p><img source=\"ui/actions/Properties Manager/Restore.png\"><br> Restores the defaut values of the Property Manager.</p>""") propMgr.preview_btn.setWhatsThis("""<b>Preview</b> <p><img source=\"ui/actions/Properties Manager/Preview.png\"><br> Preview the structure based on current Property Manager settings.</p>""") propMgr.whatsthis_btn.setWhatsThis("""<b>What's This</b> <p><img source=\"ui/actions/Properties Manager/WhatsThis.png\"><br> Click this option to invoke a small question mark that is attached to the mouse pointer, then click on an object which you would like more information about. A pop-up box appears with information about the object you selected.</p>""") # Hide the buttons that shouldn't be displayed base on <showFlags>. if not showFlags & pmDoneButton: propMgr.done_btn.hide() if not showFlags & pmCancelButton: propMgr.abort_btn.hide() if not showFlags & pmRestoreDefaultsButton: propMgr.restore_defaults_btn.hide() if not showFlags & pmPreviewButton: propMgr.preview_btn.hide() if not showFlags & pmWhatsThisButton: propMgr.whatsthis_btn.hide() return
class PM_FileChooser(QWidget): """ The PM_FileChooser widget provides a file chooser widget for a Property Manager group box. The PM_FileChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QLineEdit and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_FileChooser1.jpg) The user can type the path name of a file into the line edit widget or select a file using Qt's file (chooser) dialog by clicking the "..." button. The path name of the selected file will be inserted into the line edit widget. The parent must make the following signal-slot connection to be notified when the user has selected a new file via the file chooser dialog: self.connect(pmFileChooser.lineEdit, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar defaultText: The default text (path) of the line edit widget. @type defaultText: string @cvar setAsDefault: Determines whether to reset the value of the lineedit to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar lineEdit: The Qt line edit widget for this PM widget. @type lineEdit: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} @cvar browseButton: The Qt tool button widget for this PM widget. @type browseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultText = "" setAsDefault = True hidden = False lineEdit = None browseButton = None def __init__(self, parentWidget, label='', labelColumn=0, text='', setAsDefault=True, spanWidth=False, caption="Choose file", directory='', filter="All Files (*.*)"): """ Appends a file chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the file chooser lineedit (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: initial value of LineEdit widget. @type text: string @param setAsDefault: if True, will restore <val> when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @param caption: The caption used as the title of the file chooser dialog. "Choose file" is the default. @type caption: string @param directory: The directory that the file chooser dialog should open in when the "..." button is clicked. If blank or if directory does not exist, the current working directory is used. @type directory: string @param filter: The file type filters to use for the file chooser dialog. @type filter: string (a semicolon-separated list of file types) @see: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.text = text self.setAsDefault = setAsDefault self.spanWidth = spanWidth self.caption = caption self.directory = directory self.filter = filter if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) else: # Create a dummy attribute for PM_GroupBox to see. This might have # needed to be fixed in PM_GroupBox, but it was done here to try to # avoid causing errors in other PM widgets. -Derrick 20080916 self.labelWidget = None self.lineEdit = QLineEdit() self.browseButton = QToolButton() # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.lineEdit) self.hBoxLayout.insertWidget(-1, self.browseButton) # Set (QLineEdit) text self.setText(text) # Set browse button text and make signal-slot connection. self.browseButton.setText("...") self.connect(self.browseButton, SIGNAL("clicked()"), self.openFileChooserDialog) # Set default value self.defaultText = text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) return def setText(self, text): """ Set the line edit text. @param text: The text. @type text: string """ self.lineEdit.setText(text) self.text = text return def openFileChooserDialog(self): """ Prompts the user to choose a file from disk and inserts the full path into the lineEdit widget. """ _dir = getDefaultWorkingDirectory() if self.directory: if os.path.isdir(self.directory): _dir = self.directory fname = QFileDialog.getOpenFileName(self, self.caption, _dir, self.filter) if fname: self.setText(fname) self.lineEdit.emit(SIGNAL("editingFinished()")) return def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return # End of PM_FileChooser ############################
class LetsShareBooksDialog(QDialog): def __init__(self, gui, icon, do_user_config, qaction, us): QDialog.__init__(self, gui) self.gui = gui self.do_user_config = do_user_config self.qaction = qaction self.us = us self.clip = QApplication.clipboard() self.main_gui = calibre_main() self.urllib_thread = UrlLibThread(self.us) self.kill_servers_thread = KillServersThread(self.us) self.us.check_finished = True self.pxmp = QPixmap() self.pxmp.load('images/icon_connected.png') self.icon_connected = QIcon(self.pxmp) self.setStyleSheet(""" QDialog { background-color: white; } QPushButton { font-size: 16px; border-style: solid; border-color: red; font-family:'BitstreamVeraSansMono',Consolas,monospace; text-transform: uppercase; } QPushButton#arrow { border-width: 16px; border-right-color:white; padding: -10px; color:red; } QPushButton#url { background-color: red; min-width: 460px; color: white; text-align: left; } QPushButton#url:hover { background-color: white; color: red; } QPushButton#share { background-color: red; color: white; margin-right: 10px; } QPushButton#share:hover { background-color: white; color: red; } QPushButton#url2 { color: #222; text-align: left; } QPushButton#url2:hover { color: red; } """) self.ll = QVBoxLayout() #self.ll.setSpacing(1) self.l = QHBoxLayout() self.l.setSpacing(0) self.l.setMargin(0) #self.l.setContentsMargins(0,0,0,0) self.w = QWidget() self.w.setLayout(self.l) self.setLayout(self.ll) self.setWindowIcon(icon) self.lets_share_button = QPushButton() self.lets_share_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.lets_share_button.setObjectName("share") self.lets_share_button.clicked.connect(self.lets_share) self.stop_share_button = QPushButton() self.stop_share_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.stop_share_button.setObjectName("share") self.stop_share_button.clicked.connect(self.stop_share) self.l.addWidget(self.lets_share_button) self.l.addWidget(self.stop_share_button) if self.us.button_state == "start": self.lets_share_button.show() self.stop_share_button.hide() self.lets_share_button.setText(self.us.share_button_text) else: self.lets_share_button.hide() self.stop_share_button.show() self.stop_share_button.setText(self.us.share_button_text) self.url_label = QPushButton() self.url_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.url_label.setObjectName("url") self.url_label.clicked.connect(self.open_url) self.l.addWidget(self.url_label) self.arrow_button = QPushButton("_____") self.arrow_button.setObjectName("arrow") self.l.addWidget(self.arrow_button) self.ll.addWidget(self.w) self.ll.addSpacing(10) self.chat_button = QPushButton("Chat room: https://chat.memoryoftheworld.org") #self.chat_button.hovered.connect(self.setCursorToHand) self.chat_button.setObjectName("url2") self.chat_button.setToolTip('Meetings every thursday at 23:59 (central eruopean time)') self.chat_button.clicked.connect(functools.partial(self.open_url2, "https://chat.memoryoftheworld.org")) self.ll.addWidget(self.chat_button) self.about_project_button = QPushButton('Public Library: http://www.memoryoftheworld.org') self.about_project_button.setObjectName("url2") self.about_project_button.setToolTip('When everyone is librarian, library is everywhere.') self.about_project_button.clicked.connect(functools.partial(self.open_url2, "http://www.memoryoftheworld.org")) self.ll.addWidget(self.about_project_button) #self.debug_log = QListWidget() #self.ll.addWidget(self.debug_log) #self.debug_log.addItem("Initiatied!") self.upgrade_button = QPushButton('Please download and upgrade from {0} to {1} version of plugin.'.format(self.us.running_version, self.us.latest_version)) self.upgrade_button.setObjectName("url2") self.upgrade_button.setToolTip('Running latest version you make developers happy') self.upgrade_button.clicked.connect(functools.partial(self.open_url2, self.us.plugin_url)) version_list = [self.us.running_version, self.us.latest_version] version_list.sort(key=lambda s: map(int, s.split('.'))) if self.us.running_version != self.us.latest_version: if self.us.running_version == version_list[0]: self.ll.addSpacing(20) self.ll.addWidget(self.upgrade_button) self.resize(self.sizeHint()) self.se = open("lsb.log", "w+b") self.so = self.se sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) os.dup2(self.so.fileno(), sys.stdout.fileno()) os.dup2(self.se.fileno(), sys.stderr.fileno()) self.timer = QTimer() self.timer.timeout.connect(self.check_and_render) self.timer_period = 300 self.timer.start(self.timer_period) self.error_log = "" def lets_share(self): self.lets_share_button.setEnabled(False) self.timer.stop() self.us.share_button_text = "Connecting..." #self.debug_log.addItem("Let's share!") self.us.counter = 0 self.us.lost_connection = False if not self.us.ssh_proc: self.main_gui.start_content_server() opts, args = server_config().option_parser().parse_args(['calibre-server']) self.calibre_server_port = opts.port if sys.platform == "win32": self.win_reg = subprocess.Popen("regedit /s .hosts.reg") self.us.win_port = int(random.random()*40000+10000) self.us.ssh_proc = subprocess.Popen("lsbtunnel.exe -N -T tunnel@{2} -R {0}:localhost:{1} -P 722".format(self.us.win_port, self.calibre_server_port, prefs['lsb_server']), shell=True) self.us.lsb_url = "https://www{0}.{1}".format(self.us.win_port, prefs['lsb_server']) #_dev_self.us.lsb_url = "http://www{0}.{1}".format(self.us.win_port, prefs['lsb_server']) self.us.lsb_url_text = "Go to: {0}".format(self.us.lsb_url) self.us.found_url = True else: self.us.ssh_proc = subprocess.Popen(['ssh', '-T', '-N', '-g', '-o', 'UserKnownHostsFile=.userknownhostsfile', '-o', 'TCPKeepAlive=yes', '-o', 'ServerAliveINterval=60', prefs['lsb_server'], '-l', 'tunnel', '-R', '0:localhost:{0}'.format(self.calibre_server_port), '-p', '722']) self.us.found_url = None self.qaction.setIcon(get_icon('images/icon_connected.png')) self.us.connecting = True self.us.connecting_now = datetime.datetime.now() self.timer.start(self.timer_period) def stop_share(self): self.stop_share_button.setEnabled(False) #self.debug_log.addItem("Stop Share!") self.timer.stop() self.us.lsb_url = 'nourl' self.us.urllib_result = '' self.us.disconnecting = True self.qaction.setIcon(get_icon('images/icon.png')) self.kill_servers_thread.start() self.timer.start(self.timer_period) def check_and_render(self): #self.show_debug() if self.us.button_state == "start": self.stop_share_button.hide() self.lets_share_button.show() self.lets_share_button.setText(self.us.share_button_text) else: self.lets_share_button.hide() self.stop_share_button.show() self.stop_share_button.setText(self.us.share_button_text) if self.us.disconnecting: self.us.share_button_text = "Disconnecting..." if self.us.lost_connection: self.us.lsb_url_text = 'Lost connection. Please start sharing again.' self.us.url_label_tooltip = '<<<< Click on Start sharing button again.' else: self.us.lsb_url_text = 'Be a librarian. Share your library.' self.us.url_label_tooltip = '<<<< Be a librarian. Click on Start sharing button.<<<<' if self.us.kill_finished: #self.debug_log.addItem("Let's share connect!") self.us.button_state = "start" self.us.share_button_text = "Start sharing" self.us.disconnecting = False self.us.kill_finished = False self.lets_share_button.setEnabled(True) elif self.us.connecting: if self.us.connecting_now: if (datetime.datetime.now() - self.us.connecting_now) > datetime.timedelta(seconds=10): #self.debug_log.addItem("Timeout!") self.us.http_error = None self.us.lost_connection = True self.us.connecting = False self.us.connecting_now = None self.stop_share() elif self.us.found_url: self.us.check_finished = False self.urllib_thread.start() if self.us.lsb_url == "nourl" and self.us.ssh_proc and sys.platform != "win32": #self.debug_log.addItem("Wait for Allocated port!") self.se.seek(0) result = self.se.readlines() for line in result: m = re.match("^Allocated port (.*) for .*", line) try: #self.debug_log.addItem(self.us.lsb_url) self.us.lsb_url = 'https://www{0}.{1}'.format(m.groups()[0], prefs['lsb_server']) #_dev_self.us.lsb_url = 'http://www{0}.{1}'.format(m.groups()[0], prefs['lsb_server']) self.us.lsb_url_text = "Go to: {0}".format(self.us.lsb_url) self.us.url_label_tooltip = 'Copy URL to clipboard and check it out in a browser!' self.us.http_error = None self.us.found_url = True except: pass elif self.us.urllib_result == 200: #self.debug_log.addItem("Finish Connecting State!") self.se.seek(0) self.se.truncate() self.us.share_button_text = "Stop sharing" self.us.button_state = "stop" self.stop_share_button.setEnabled(True) self.us.connecting = False self.us.connecting_now = None self.us.found_url = None elif self.us.http_error and self.us.button_state == "stop": #self.debug_log.addItem("Error!") self.us.http_error = None self.us.lost_connection = True self.stop_share() elif self.us.check_finished: #if self.debug_log.item(self.debug_log.count()-1).text()[:10] == "Finally Ca": # self.us.debug_counter = self.us.debug_counter + 1 #else: # self.debug_log.addItem("Finally Called Thread!({0})".format(self.us.debug_counter)) # self.us.debug_counter = 1 self.us.check_finished = False self.urllib_thread.start() if self.us.urllib_result == 200 and self.us.button_state == "stop": self.stop_share_button.setEnabled(True) if self.us.lsb_url == 'nourl' and self.us.button_state == "start": self.lets_share_button.setEnabled(True) self.setWindowTitle("{0} - {1}".format(self.us.window_title, self.us.lsb_url)) self.url_label.setToolTip(self.us.url_label_tooltip) self.url_label.setText(self.us.lsb_url_text) def open_url(self): if self.us.lsb_url == "nourl" and not self.us.http_error: self.us.url_label_tooltip = '<<<< Be a librarian. Click on Start sharing button.' self.us.lsb_url_text = '<<<< Be a librarian. Click on Start sharing button.' else: self.clip.setText(self.us.lsb_url) webbrowser.open(str(self.us.lsb_url)) if self.us.lsb_url != "nourl": self.us.lsb_url_text = "Library at: {0}".format(self.us.lsb_url) def open_url2(self, url): self.clip.setText(url) webbrowser.open(url) def show_debug(self): if self.us.debug_item: self.debug_log.addItem(str(self.us.debug_item)) self.us.debug_item = None self.debug_log.scrollToBottom() self.debug_log.repaint() def closeEvent(self, e): self.hide() #self.urllib_thread.stop() #self.kill_servers_thread.stop() def config(self): self.do_user_config(parent=self) self.label.setText(prefs['lsb_server'])
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Convert sources to FITS brick") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # file selector self.wfile = FileSelector(self, label="FITS filename:", dialog_label="Output FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile) lo.addWidget(self.wfile) # reference frequency lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) label = QLabel("Frequency, MHz:", self) lo1.addWidget(label) tip = """<P>If your sky model contains spectral information (such as spectral indices), then a brick may be generated for a specific frequency. If a frequency is not specified here, the reference frequency of the model sources will be assumed.</P>""" self.wfreq = QLineEdit(self) self.wfreq.setValidator(QDoubleValidator(self)) label.setToolTip(tip) self.wfreq.setToolTip(tip) lo1.addWidget(self.wfreq) # beam gain lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.wpb_apply = QCheckBox("Apply primary beam expression:", self) self.wpb_apply.setChecked(True) lo1.addWidget(self.wpb_apply) tip = """<P>If this option is specified, a primary power beam gain will be applied to the sources before inserting them into the brick. This can be any valid Python expression making use of the variables 'r' (corresponding to distance from field centre, in radians) and 'fq' (corresponding to frequency.)</P>""" self.wpb_exp = QLineEdit(self) self.wpb_apply.setToolTip(tip) self.wpb_exp.setToolTip(tip) lo1.addWidget(self.wpb_exp) # overwrite or add mode lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.woverwrite = QRadioButton("overwrite image", self) self.woverwrite.setChecked(True) lo1.addWidget(self.woverwrite) self.waddinto = QRadioButton("add into image", self) lo1.addWidget(self.waddinto) # add to model self.wadd = QCheckBox( "Add resulting brick to sky model as a FITS image component", self) lo.addWidget(self.wadd) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.wpad = QLineEdit(self) self.wpad.setValidator(QDoubleValidator(self)) self.wpad.setText("1.1") lab = QLabel("...with padding factor:", self) lab.setToolTip( """<P>The padding factor determines the amount of null padding inserted around the image during the prediction stage. Padding alleviates the effects of tapering and detapering in the uv-brick, which can show up towards the edges of the image. For a factor of N, the image will be padded out to N times its original size. This increases memory use, so if you have no flux at the edges of the image anyway, then a pad factor of 1 is perfectly fine.</P>""") self.wpad.setToolTip(lab.toolTip()) QObject.connect(self.wadd, SIGNAL("toggled(bool)"), self.wpad.setEnabled) QObject.connect(self.wadd, SIGNAL("toggled(bool)"), lab.setEnabled) self.wpad.setEnabled(False) lab.setEnabled(False) lo1.addStretch(1) lo1.addWidget(lab, 0) lo1.addWidget(self.wpad, 1) self.wdel = QCheckBox( "Remove from the sky model sources that go into the brick", self) lo.addWidget(self.wdel) # OK/cancel buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) # signals QObject.connect(self.wfile, SIGNAL("filenameSelected"), self._fileSelected) # internal state self.qerrmsg = QErrorMessage(self)
def setupUi(self): """ Setup the UI for the command toolbar. """ #ninad 070123 : It's important to set the Vertical size policy of the # cmd toolbar widget. otherwise the flyout QToolbar messes up the #layout (makes the command toolbar twice as big) #I have set the vertical policy as fixed. Works fine. There are some # MainWindow resizing problems for but those are not due to this #size policy AFAIK self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) layout_cmdtoolbar = QHBoxLayout(self) layout_cmdtoolbar.setMargin(2) layout_cmdtoolbar.setSpacing(2) #See comment at the top for details about this flag if DEFINE_CONTROL_AREA_AS_A_QWIDGET: self.cmdToolbarControlArea = QWidget(self) else: self.cmdToolbarControlArea = QToolBar_WikiHelp(self) self.cmdToolbarControlArea.setAutoFillBackground(True) self.ctrlAreaPalette = self.getCmdMgrCtrlAreaPalette() self.cmdToolbarControlArea.setPalette(self.ctrlAreaPalette) self.cmdToolbarControlArea.setMinimumHeight(62) self.cmdToolbarControlArea.setMinimumWidth(380) self.cmdToolbarControlArea.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #See comment at the top for details about this flag if DEFINE_CONTROL_AREA_AS_A_QWIDGET: layout_controlArea = QHBoxLayout(self.cmdToolbarControlArea) layout_controlArea.setMargin(0) layout_controlArea.setSpacing(0) self.cmdButtonGroup = QButtonGroup() btn_index = 0 for name in ('Build', 'Insert', 'Tools', 'Move', 'Simulation'): btn = QToolButton(self.cmdToolbarControlArea) btn.setObjectName(name) btn.setMinimumWidth(75) btn.setMaximumWidth(75) btn.setMinimumHeight(62) btn.setAutoRaise(True) btn.setCheckable(True) btn.setAutoExclusive(True) iconpath = "ui/actions/Command Toolbar/ControlArea/" + name + ".png" btn.setIcon(geticon(iconpath)) btn.setIconSize(QSize(22, 22)) btn.setText(name) btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btn.setPalette(self.ctrlAreaPalette) self.cmdButtonGroup.addButton(btn, btn_index) btn_index += 1 #See comment at the top for details about this flag if DEFINE_CONTROL_AREA_AS_A_QWIDGET: layout_controlArea.addWidget(btn) else: self.cmdToolbarControlArea.layout().addWidget(btn) #following has issues. so not adding widget directly to the #toolbar. (instead adding it in its layout)-- ninad 070124 ##self.cmdToolbarControlArea.addWidget(btn) layout_cmdtoolbar.addWidget(self.cmdToolbarControlArea) #Flyout Toolbar in the command toolbar self.flyoutToolBar = FlyoutToolBar(self) layout_cmdtoolbar.addWidget(self.flyoutToolBar) #ninad 070116: Define a spacer item. It will have the exact geometry # as that of the flyout toolbar. it is added to the command toolbar # layout only when the Flyout Toolbar is hidden. It is required # to keep the 'Control Area' widget fixed in its place (otherwise, #after hiding the flyout toolbar, the layout adjusts the position of #remaining widget items) self.spacerItem = QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.spacerItem.setGeometry = self.flyoutToolBar.geometry() for btn in self.cmdButtonGroup.buttons(): if str(btn.objectName()) == 'Build': btn.setMenu(self.win.buildStructuresMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Build Commands") whatsThisTextForCommandToolbarBuildButton(btn) if str(btn.objectName()) == 'Insert': btn.setMenu(self.win.insertMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Insert Commands") whatsThisTextForCommandToolbarInsertButton(btn) if str(btn.objectName()) == 'Tools': #fyi: cmd stands for 'command toolbar' - ninad070406 self.win.cmdToolsMenu = QtGui.QMenu(self.win) self.win.cmdToolsMenu.addAction(self.win.toolsExtrudeAction) self.win.cmdToolsMenu.addAction(self.win.toolsFuseChunksAction) self.win.cmdToolsMenu.addSeparator() self.win.cmdToolsMenu.addAction(self.win.modifyMergeAction) self.win.cmdToolsMenu.addAction(self.win.modifyMirrorAction) self.win.cmdToolsMenu.addAction(self.win.modifyInvertAction) self.win.cmdToolsMenu.addAction(self.win.modifyStretchAction) btn.setMenu(self.win.cmdToolsMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Tools") whatsThisTextForCommandToolbarToolsButton(btn) if str(btn.objectName()) == 'Move': self.win.moveMenu = QtGui.QMenu(self.win) self.win.moveMenu.addAction(self.win.toolsMoveMoleculeAction) self.win.moveMenu.addAction(self.win.rotateComponentsAction) self.win.moveMenu.addSeparator() self.win.moveMenu.addAction( self.win.modifyAlignCommonAxisAction) ##self.win.moveMenu.addAction(\ ## self.win.modifyCenterCommonAxisAction) btn.setMenu(self.win.moveMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Move Commands") whatsThisTextForCommandToolbarMoveButton(btn) if str(btn.objectName()) == 'Dimension': btn.setMenu(self.win.dimensionsMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Dimensioning Commands") if str(btn.objectName()) == 'Simulation': btn.setMenu(self.win.simulationMenu) btn.setPopupMode(QToolButton.MenuButtonPopup) btn.setToolTip("Simulation Commands") whatsThisTextForCommandToolbarSimulationButton(btn) # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 # [bruce 081209 revised this -- removed mac = False] fix_QAction_whatsthis(btn) return
def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("My Main Window") self.setMinimumWidth(MAIN_WINDOW_SIZE[0]) self.setMinimumHeight(MAIN_WINDOW_SIZE[1]) self.statusbar = QtGui.QStatusBar(self) self.statusbar.showMessage("Status message") self.setStatusBar(self.statusbar) ################################################ self.menubar = self.menuBar() # Any menu action makes the status bar message disappear fileMenu = QtGui.QMenu(self.menubar) fileMenu.setTitle("File") self.menubar.addAction(fileMenu.menuAction()) newAction = QtGui.QAction("New", self) newAction.setIcon(QtGui.QtIcon(icons + '/GroupPropDialog_image0.png')) fileMenu.addAction(newAction) openAction = QtGui.QAction("Open", self) openAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image1")) fileMenu.addAction(openAction) saveAction = QtGui.QAction("Save", self) saveAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image2")) fileMenu.addAction(saveAction) self.connect(newAction, SIGNAL("activated()"), self.fileNew) self.connect(openAction, SIGNAL("activated()"), self.fileOpen) self.connect(saveAction, SIGNAL("activated()"), self.fileSave) for otherMenuName in ('Edit', 'View', 'Display', 'Select', 'Modify', 'NanoHive-1'): otherMenu = QtGui.QMenu(self.menubar) otherMenu.setTitle(otherMenuName) self.menubar.addAction(otherMenu.menuAction()) helpMenu = QtGui.QMenu(self.menubar) helpMenu.setTitle("Help") self.menubar.addAction(helpMenu.menuAction()) aboutAction = QtGui.QAction("About", self) aboutAction.setIcon(QtGui.QtIcon(icons + '/MainWindowUI_image0.png')) helpMenu.addAction(aboutAction) self.connect(aboutAction, SIGNAL("activated()"), self.helpAbout) ############################################## self.setMenuBar(self.menubar) centralwidget = QWidget() self.setCentralWidget(centralwidget) layout = QVBoxLayout(centralwidget) layout.setMargin(0) layout.setSpacing(0) middlewidget = QWidget() self.bigButtons = QWidget() bblo = QHBoxLayout(self.bigButtons) bblo.setMargin(0) bblo.setSpacing(0) self.bigButtons.setMinimumHeight(50) self.bigButtons.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) for name in ('Features', 'Sketch', 'Build', 'Dimension', 'Simulator'): btn = QPushButton(self.bigButtons) btn.setMaximumWidth(80) btn.setMinimumHeight(50) btn.setText(name) self.bigButtons.layout().addWidget(btn) self.bigButtons.hide() layout.addWidget(self.bigButtons) self.littleIcons = QWidget() self.littleIcons.setMinimumHeight(30) self.littleIcons.setMaximumHeight(30) lilo = QHBoxLayout(self.littleIcons) lilo.setMargin(0) lilo.setSpacing(0) pb = QPushButton(self.littleIcons) pb.setIcon(QIcon(icons + '/GroupPropDialog_image0.png')) self.connect(pb, SIGNAL("clicked()"), self.fileNew) lilo.addWidget(pb) for x in "1 2 4 5 6 7 8 18 42 10 43 150 93 94 97 137".split(): pb = QPushButton(self.littleIcons) pb.setIcon(QIcon(icons + '/MainWindowUI_image' + x + '.png')) lilo.addWidget(pb) layout.addWidget(self.littleIcons) layout.addWidget(middlewidget) self.layout = QGridLayout(middlewidget) self.layout.setMargin(0) self.layout.setSpacing(2) self.gridPosition = GridPosition() self.numParts = 0 self.show() explainWindow = AboutWindow( "Select <b>Help->About</b>" " for instructions...", 200, 3)
def pmAddTopRowButtons(propMgr, showFlags=pmAllButtons): """Creates the OK, Cancel, Preview, and What's This buttons row at the top of the Property Manager <propMgr>. <showFlags> is an enum that can be used to show only certain Property Manager buttons, where: pmDoneButton = 1 pmCancelButton = 2 pmRestoreDefaultsButton = 4 pmPreviewButton = 8 pmWhatsThisButton = 16 pmAllButtons = 31 These flags are defined in PropMgr_Constants.py. This subroutine is used by the following Property Managers (which are still not using the PropMgrBaseClass): - Build Atoms - Build Crystal - Extrude - Move - Movie Player - Fuse Chunks Note: This subrouting is temporary. It will be removed after the PropMgrs in this list are converted to the PropMgrBaseClass. Mark 2007-06-24 """ # The Top Buttons Row includes the following widgets: # # - propMgr.pmTopRowBtns (Hbox Layout containing everything:) # # - frame # - hbox layout "frameHboxLO" (margin=2, spacing=2) # - Done (OK) button # - Abort (Cancel) button # - Restore Defaults button # - Preview button # - What's This button # - right spacer (10x10) # Main "button group" widget (but it is not a QButtonGroup). propMgr.pmTopRowBtns = QHBoxLayout() # Horizontal spacer HSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) # Frame containing all the buttons. propMgr.TopRowBtnsFrame = QFrame() propMgr.TopRowBtnsFrame.setFrameShape(QFrame.NoFrame) propMgr.TopRowBtnsFrame.setFrameShadow(QFrame.Plain) # Create Hbox layout for main frame. TopRowBtnsHLayout = QHBoxLayout(propMgr.TopRowBtnsFrame) TopRowBtnsHLayout.setMargin(pmTopRowBtnsMargin) TopRowBtnsHLayout.setSpacing(pmTopRowBtnsSpacing) TopRowBtnsHLayout.addItem(HSpacer) # Set button type. buttonType = QToolButton # May want to use QToolButton.setAutoRaise(1) below. Mark 2007-05-29 # OK (Done) button. propMgr.done_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.done_btn.setIcon(geticon("ui/actions/Properties Manager/Done.png")) propMgr.done_btn.setIconSize(QSize(22, 22)) propMgr.connect(propMgr.done_btn, SIGNAL("clicked()"), propMgr.ok_btn_clicked) propMgr.done_btn.setToolTip("Done") TopRowBtnsHLayout.addWidget(propMgr.done_btn) # Cancel (Abort) button. propMgr.abort_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.abort_btn.setIcon( geticon("ui/actions/Properties Manager/Abort.png")) propMgr.abort_btn.setIconSize(QSize(22, 22)) propMgr.connect(propMgr.abort_btn, SIGNAL("clicked()"), propMgr.abort_btn_clicked) propMgr.abort_btn.setToolTip("Cancel") TopRowBtnsHLayout.addWidget(propMgr.abort_btn) # Restore Defaults button. propMgr.restore_defaults_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.restore_defaults_btn.setIcon( geticon("ui/actions/Properties Manager/Restore.png")) propMgr.restore_defaults_btn.setIconSize(QSize(22, 22)) propMgr.connect(propMgr.restore_defaults_btn, SIGNAL("clicked()"), propMgr.restore_defaults_btn_clicked) propMgr.restore_defaults_btn.setToolTip("Restore Defaults") TopRowBtnsHLayout.addWidget(propMgr.restore_defaults_btn) # Preview (glasses) button. propMgr.preview_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview.png")) propMgr.preview_btn.setIconSize(QSize(22, 22)) propMgr.connect(propMgr.preview_btn, SIGNAL("clicked()"), propMgr.preview_btn_clicked) propMgr.preview_btn.setToolTip("Preview") TopRowBtnsHLayout.addWidget(propMgr.preview_btn) # What's This (?) button. propMgr.whatsthis_btn = buttonType(propMgr.TopRowBtnsFrame) propMgr.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis.png")) propMgr.whatsthis_btn.setIconSize(QSize(22, 22)) propMgr.connect(propMgr.whatsthis_btn, SIGNAL("clicked()"), QWhatsThis.enterWhatsThisMode) propMgr.whatsthis_btn.setToolTip("What\'s This Help") TopRowBtnsHLayout.addWidget(propMgr.whatsthis_btn) TopRowBtnsHLayout.addItem(HSpacer) # Create Button Row propMgr.pmTopRowBtns.addWidget(propMgr.TopRowBtnsFrame) propMgr.pmVBoxLayout.addLayout(propMgr.pmTopRowBtns) # Add What's This for buttons. propMgr.done_btn.setWhatsThis("""<b>Done</b> <p><img source=\"ui/actions/Properties Manager/Done.png\"><br> Completes and/or exits the current command.</p>""") propMgr.abort_btn.setWhatsThis("""<b>Cancel</b> <p><img source=\"ui/actions/Properties Manager/Abort.png\"><br> Cancels the current command.</p>""") propMgr.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b> <p><img source=\"ui/actions/Properties Manager/Restore.png\"><br> Restores the defaut values of the Property Manager.</p>""") propMgr.preview_btn.setWhatsThis("""<b>Preview</b> <p><img source=\"ui/actions/Properties Manager/Preview.png\"><br> Preview the structure based on current Property Manager settings.</p>""" ) propMgr.whatsthis_btn.setWhatsThis("""<b>What's This</b> <p><img source=\"ui/actions/Properties Manager/WhatsThis.png\"><br> Click this option to invoke a small question mark that is attached to the mouse pointer, then click on an object which you would like more information about. A pop-up box appears with information about the object you selected.</p>""" ) # Hide the buttons that shouldn't be displayed base on <showFlags>. if not showFlags & pmDoneButton: propMgr.done_btn.hide() if not showFlags & pmCancelButton: propMgr.abort_btn.hide() if not showFlags & pmRestoreDefaultsButton: propMgr.restore_defaults_btn.hide() if not showFlags & pmPreviewButton: propMgr.preview_btn.hide() if not showFlags & pmWhatsThisButton: propMgr.whatsthis_btn.hide() return
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Restore model into image") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # file selector self.wfile_in = FileSelector(self, label="Input FITS file:", dialog_label="Input FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile) lo.addWidget(self.wfile_in) self.wfile_out = FileSelector(self, label="Output FITS file:", dialog_label="Output FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.AnyFile) lo.addWidget(self.wfile_out) # beam size lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) lo1.addWidget(QLabel("Restoring beam FWHM, major axis:", self)) self.wbmaj = QLineEdit(self) lo1.addWidget(self.wbmaj) lo1.addWidget(QLabel("\" minor axis:", self)) self.wbmin = QLineEdit(self) lo1.addWidget(self.wbmin) lo1.addWidget(QLabel("\" P.A.:", self)) self.wbpa = QLineEdit(self) lo1.addWidget(self.wbpa) lo1.addWidget(QLabel("\u00B0", self)) for w in self.wbmaj, self.wbmin, self.wbpa: w.setValidator(QDoubleValidator(self)) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) self.wfile_psf = FileSelector(self, label="Set restoring beam by fitting PSF image:", dialog_label="PSF FITS file", default_suffix="fits", file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile) lo1.addSpacing(32) lo1.addWidget(self.wfile_psf) # selection only self.wselonly = QCheckBox("restore selected model sources only", self) lo.addWidget(self.wselonly) # OK/cancel buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) # signals QObject.connect(self.wfile_in, SIGNAL("filenameSelected"), self._fileSelected) QObject.connect(self.wfile_in, SIGNAL("filenameSelected"), self._inputFileSelected) QObject.connect(self.wfile_out, SIGNAL("filenameSelected"), self._fileSelected) QObject.connect(self.wfile_psf, SIGNAL("filenameSelected"), self._psfFileSelected) # internal state self.qerrmsg = QErrorMessage(self)
class LetsShareBooksDialog(QDialog): started_calibre_web_server = QtCore.pyqtSignal() calibre_didnt_start = QtCore.pyqtSignal() established_ssh_tunnel = QtCore.pyqtSignal() def __init__(self, gui, icon, do_user_config, qaction, us): QDialog.__init__(self, gui) self.main_gui = gui self.do_user_config = do_user_config self.qaction = qaction self.us = us self.initial = True self.lsb_url_text = 'Be a librarian. Share your library.' self.url_label_tooltip = '<<<< Be a librarian. Click on Start sharing button.<<<<' self.lsb_url = 'nourl' if prefs['librarian'] == 'l' or prefs['librarian'] == '': self.librarian = get_libranon() else: self.librarian = prefs['librarian'] self.metadata_thread = MetadataLibThread(self.librarian) self.check_connection = ConnectionCheck() self.clip = QApplication.clipboard() self.pxmp = QPixmap() self.pxmp.load('images/icon_connected.png') self.icon_connected = QIcon(self.pxmp) self.setStyleSheet(""" QDialog { background-color: white; } QPushButton { font-size: 16px; border-style: solid; border-color: red; font-family:'BitstreamVeraSansMono',Consolas,monospace; text-transform: uppercase; } QPushButton#arrow { border-width: 16px; border-right-color:white; padding: -10px; color:red; } QPushButton#url { background-color: red; min-width: 460px; color: white; text-align: left; } QPushButton#url:hover { background-color: white; color: red; } QPushButton#share { background-color: red; color: white; margin-right: 10px; } QPushButton#share:hover { background-color: white; color: red; } QPushButton#url2 { color: #222; text-align: left; } QPushButton#url2:hover { color: red; } QLineEdit#edit { background-color: white; color: black; font-size: 16px; border-style: solid; border-color: red; font-family:'BitstreamVeraSansMono',Consolas,monospace; text-transform: uppercase; } """) self.ll = QVBoxLayout() #self.ll.setSpacing(1) self.l = QHBoxLayout() self.l.setSpacing(0) self.l.setMargin(0) #self.l.setContentsMargins(0,0,0,0) self.w = QWidget() self.w.setLayout(self.l) self.setLayout(self.ll) self.setWindowIcon(icon) self.debug_label = QLabel() self.ll.addWidget(self.debug_label) self.debug_label.show() self.lets_share_button = QPushButton() self.lets_share_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.lets_share_button.setObjectName("share") #self.lets_share_button.clicked.connect(self.lets_share) self.l.addWidget(self.lets_share_button) self.url_label = QPushButton() self.url_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.url_label.setObjectName("url") #self.url_label.clicked.connect(self.open_url) self.l.addWidget(self.url_label) self.arrow_button = QPushButton("_____") self.arrow_button.setObjectName("arrow") self.l.addWidget(self.arrow_button) self.ll.addWidget(self.w) self.ll.addSpacing(5) self.libranon_layout = QHBoxLayout() self.libranon_layout.setSpacing(0) self.libranon_layout.setMargin(0) #self.l.setContentsMargins(0,0,0,0) self.libranon_container = QWidget() self.libranon_container.setLayout(self.libranon_layout) self.edit = QLineEdit() self.edit.setObjectName("edit") self.edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.edit.setToolTip("Change your librarian name") self.edit.setText(self.librarian) #self.edit.textChanged.connect(self.handle_text_changed) self.save_libranon = QPushButton("librarian:") self.save_libranon.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.save_libranon.setObjectName("share") self.save_libranon.setToolTip("Save your librarian name") self.libranon_layout.addWidget(self.save_libranon) self.libranon_layout.addWidget(self.edit) self.save_libranon.clicked.connect(self.save_librarian) self.ll.addWidget(self.libranon_container) self.ll.addSpacing(10) self.chat_button = QPushButton("Chat room: https://chat.memoryoftheworld.org") #self.chat_button.hovered.connect(self.setCursorToHand) self.chat_button.setObjectName("url2") self.chat_button.setToolTip('Meetings every thursday at 23:59 (central eruopean time)') self.chat_button.clicked.connect(functools.partial(self.open_url, "https://chat.memoryoftheworld.org/?nick={}".format(self.librarian.lower().replace(" ", "_")))) self.ll.addWidget(self.chat_button) self.about_project_button = QPushButton('Public Library: http://www.memoryoftheworld.org') self.about_project_button.setObjectName("url2") self.about_project_button.setToolTip('When everyone is librarian, library is everywhere.') self.metadata_thread.uploaded.connect(lambda: self.render_library_button("{}://library.{}".format(prefs['server_prefix'], prefs['lsb_server']), "Building together real-time p2p library infrastructure.")) self.ll.addWidget(self.about_project_button) self.debug_log = QListWidget() self.ll.addWidget(self.debug_log) self.debug_log.addItem("Initiatied!") self.debug_log.hide() from PyQt4 import QtWebKit self.webview = QtWebKit.QWebView() self.webview.setMaximumWidth(680) self.webview.setMaximumHeight(400) self.webview.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.webview.setUrl(QtCore.QUrl( "https://chat.memoryoftheworld.org/?nick={}".format(self.librarian.lower().replace(" ", "_")))) self.ll.addWidget(self.webview) #self.webview.hide() #- check if there is a new version of plugin ---------------------------------------------- self.plugin_url = "https://github.com/marcellmars/letssharebooks/raw/master/calibreletssharebooks/letssharebooks_calibre.zip" self.running_version = ".".join(map(str, lsb.version)) try: r = requests.get('https://raw.github.com/marcellmars/letssharebooks/master/calibreletssharebooks/_version', timeout=3) self.latest_version = r.text[-1] except: self.latest_version = "0.0.0" self.upgrade_button = QPushButton('Please download and upgrade from {0} to {1} version of plugin.'.format(self.us.running_version, self.latest_version)) self.upgrade_button.setObjectName("url2") self.upgrade_button.setToolTip('Running latest version you make developers happy') self.upgrade_button.clicked.connect(functools.partial(self.open_url, self.plugin_url)) version_list = [self.us.running_version, self.us.latest_version] version_list.sort(key=lambda s: map(int, s.split('.'))) if self.us.running_version != self.us.latest_version: if self.us.running_version == version_list[0]: self.ll.addSpacing(20) self.ll.addWidget(self.upgrade_button) #------------------------------------------------------------------------------------------ self.resize(self.sizeHint()) #- parsing/tee log file ------------------------------------------------------------------- self.se = open("/tmp/lsb.log", "w+b") #self.se = tempfile.NamedTemporaryFile() self.so = self.se sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) os.dup2(self.so.fileno(), sys.stdout.fileno()) os.dup2(self.se.fileno(), sys.stderr.fileno()) #- state machine -------------------------------------------------------------------------- self.machine = QtCore.QStateMachine() self.on = QtCore.QState() self.on.setObjectName("on") self.on.entered.connect(lambda: self.render_lsb_button("Start sharing", self.lsb_url_text)) self.calibre_web_server = QtCore.QState() self.calibre_web_server.setObjectName("calibre_web_server") self.calibre_web_server.entered.connect(self.start_calibre_server) self.calibre_web_server.entered.connect(lambda: self.render_lsb_button("Stop sharing", self.lsb_url_text)) self.calibre_web_server.assignProperty(self.debug_label, 'text', 'Starting Calibre web server...') self.ssh_server = QtCore.QState() self.ssh_server.setObjectName("ssh_server") self.ssh_server.entered.connect(lambda: self.render_lsb_button("Stop sharing", "Connecting...")) self.ssh_server.entered.connect(self.establish_ssh_server) self.ssh_server.assignProperty(self.debug_label, 'text', 'Establishing SSH tunnel...') self.ssh_server_established = QtCore.QState() self.ssh_server_established.setObjectName("ssh_server_established") self.ssh_server_established.entered.connect(lambda: self.render_lsb_button("Stop sharing", self.lsb_url_text)) self.ssh_server_established.entered.connect(self.check_connections) self.ssh_server_established.assignProperty(self.debug_label, 'text', 'Established SSH tunnel...') self.url_label_clicked = QtCore.QState() self.url_label_clicked.setObjectName("url_label_clicked") self.url_label_clicked.entered.connect(lambda: self.open_url(self.lsb_url)) self.url_label_clicked.assignProperty(self.debug_label, 'text', 'URL label clicked!') self.about_project_clicked = QtCore.QState() self.about_project_clicked.setObjectName("about_project_clicked") self.about_project_clicked.entered.connect(lambda: self.open_url("{}://library.{}".format(prefs['server_prefix'], prefs['lsb_server']))) self.about_project_clicked.assignProperty(self.debug_label, 'text', 'about_project_button clicked!') self.library_state_changed = QtCore.QState() self.library_state_changed.entered.connect(lambda: self.render_library_button("Uploading library metadata...", "Sharing with the others who share their libraries now...")) self.library_state_changed.setObjectName("library_state_changed") self.library_state_changed.entered.connect(self.sync_metadata) self.off = QtCore.QState() self.off.setObjectName("off") self.off.entered.connect(lambda: self.disconnect_all()) self.off.assignProperty(self.debug_label, 'text', 'Start again...') self.on.addTransition(self.lets_share_button.clicked, self.calibre_web_server) self.calibre_web_server.addTransition(self.lets_share_button.clicked, self.off) self.calibre_web_server.addTransition(self.calibre_didnt_start, self.off) self.calibre_web_server.addTransition(self.started_calibre_web_server, self.ssh_server) self.ssh_server.addTransition(self.lets_share_button.clicked, self.off) self.ssh_server.addTransition(self.check_connection.lost_connection, self.off) self.ssh_server.addTransition(self.established_ssh_tunnel, self.ssh_server_established) self.ssh_server_established.addTransition(self.lets_share_button.clicked, self.off) self.ssh_server_established.addTransition(self.url_label.clicked, self.url_label_clicked) self.ssh_server_established.addTransition(self.about_project_button.clicked, self.about_project_clicked) self.ssh_server_established.addTransition(self.check_connection.lost_connection, self.off) self.ssh_server_established.addTransition(self.us.library_changed, self.library_state_changed) self.url_label_clicked.addTransition(self.ssh_server_established) self.about_project_clicked.addTransition(self.ssh_server_established) self.library_state_changed.addTransition(self.metadata_thread.uploaded, self.ssh_server_established) self.library_state_changed.addTransition(self.metadata_thread.upload_error, self.off) self.library_state_changed.addTransition(self.lets_share_button.clicked, self.off) self.library_state_changed.addTransition(self.url_label.clicked, self.url_label_clicked) self.off.addTransition(self.on) self.machine.addState(self.on) self.machine.addState(self.calibre_web_server) self.machine.addState(self.ssh_server) self.machine.addState(self.ssh_server_established) self.machine.addState(self.url_label_clicked) self.machine.addState(self.about_project_clicked) self.machine.addState(self.library_state_changed) self.machine.addState(self.off) self.machine.setInitialState(self.on) self.machine.start() #------------------------------------------------------------------------------------------ def sql_db_changed(self, event, ids): # this could be used for better update on added/removed books if not self.metadata_thread.isRunning(): self.sync_metadata() else: print("metadata_thread is running! no sync!") def sync_metadata(self): from calibre.gui2.ui import get_gui try: del self.sql_db except: pass self.sql_db = get_gui().current_db self.sql_db.add_listener(self.sql_db_changed) self.metadata_thread.sql_db = self.sql_db self.metadata_thread.port = self.port self.metadata_thread.uploaded.connect(lambda: self.debug_log.addItem("uploaded!")) self.metadata_thread.upload_error.connect(lambda: self.debug_log.addItem("upload_ERROR!")) self.metadata_thread.start() def check_connections(self): #self.webview.show() if self.initial: print("initial!") self.us.library_changed_emit() self.initial = False self.qaction.setIcon(get_icon('images/icon_connected.png')) self.check_connection.add_urls(["http://*****:*****@{2} -R {0}:localhost:{1} -P 722".format(self.port, self.calibre_server_port, prefs['lsb_server']), shell=True) self.lsb_url = "{}://www{}.{}".format(prefs['server_prefix'], self.port, prefs['lsb_server']) self.lsb_url_text = "Go to: {}".format(self.lsb_url) QTimer.singleShot(3000, self.established_ssh_tunnel.emit) else: self.ssh_proc = subprocess.Popen(['ssh', '-T', '-N', '-g', '-o', 'TCPKeepAlive=yes', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no','-o', 'ServerAliveINterval=60', prefs['lsb_server'], '-l', 'tunnel', '-R', '0:localhost:{0}'.format(self.calibre_server_port), '-p', '722']) if self.ssh_proc: def parse_log(): gotcha = False try: self.se.seek(0) result = self.se.readlines() self.se.seek(0) self.se.truncate() for line in result: m = re.match("^Allocated port (.*) for .*", line) try: self.port = m.groups()[0] self.lsb_url = '{}://www{}.{}'.format(prefs['server_prefix'], self.port, prefs['lsb_server']) self.lsb_url_text = "Go to: {0}".format(self.lsb_url) self.url_label_tooltip = 'Copy URL to clipboard and check it out in a browser!' self.established_ssh_tunnel.emit() gotcha = True except: pass finally: if not gotcha: QTimer.singleShot(500, parse_log) parse_log() def start_calibre_server(self): if self.main_gui.content_server is None: self.main_gui.start_content_server() opts, args = server_config().option_parser().parse_args(['calibre-server']) self.calibre_server_port = opts.port self.started_calibre_web_server.emit() else: self.calibre_didnt_start.emit() def config(self): self.do_user_config(parent=self) self.label.setText(prefs['lsb_server']) def save_librarian(self): print('librarian {} saved!'.format(str(self.edit.text()))) if self.edit.text() != "" and self.edit.text() != "l": prefs['librarian'] = str(self.edit.text()) else: prefs['librarian'] = get_libranon() self.edit.setText(prefs['librarian']) def open_url(self, url): self.clip.setText(url) webbrowser.open(url) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: pass def closeEvent(self, e): print("close popup!") self.hide()