Ejemplo n.º 1
0
 def copy_cover(self):
     idx = self.currentIndex()
     pmap = self.model().cover_pixmap(idx)
     if pmap is None and idx.row() == 0:
         pmap = self.model().cc
     if pmap is not None:
         QApplication.clipboard().setPixmap(pmap)
Ejemplo n.º 2
0
    def show_data(self, html):
        def color_to_string(col):
            ans = '#000000'
            if col.isValid():
                col = col.toRgb()
                if col.isValid():
                    ans = unicode(col.name())
            return ans

        fi = QFontInfo(QApplication.font(self.parent()))
        f = fi.pixelSize()+1+int(tweaks['change_book_details_font_size_by'])
        fam = unicode(fi.family()).strip().replace('"', '')
        if not fam:
            fam = 'sans-serif'

        c = color_to_string(QApplication.palette().color(QPalette.Normal,
                        QPalette.WindowText))
        templ = '''\
        <html>
            <head>
            <style type="text/css">
                body, td {background-color: transparent; font-family: "%s"; font-size: %dpx; color: %s }
                a { text-decoration: none; color: blue }
                div.description { margin-top: 0; padding-top: 0; text-indent: 0 }
                table { margin-bottom: 0; padding-bottom: 0; }
            </style>
            </head>
            <body>
            <div class="description">
            %%s
            </div>
            </body>
        <html>
        '''%(fam, f, c)
        self.setHtml(templ%html)
Ejemplo n.º 3
0
def main():
    app = QApplication(sys.argv)
    rddtDataExtractor = loadState()
    if rddtDataExtractor is None:
        rddtDataExtractor = RedditDataExtractor()
    rddtDataExtractor.currentlyDownloading = False # If something weird happened to cause currentlyDownloading to be saved as True, set it back to False

    queue = Queue()
    thread = QThread()
    recv = QueueMessageReceiver(queue)
    mainGUIWindow = RddtDataExtractorGUI(rddtDataExtractor, queue, recv)

    recv.queuePutSignal.connect(mainGUIWindow.append_text)
    recv.moveToThread(thread)
    thread.started.connect(recv.run)
    # Add clean up finished signals so the threads end appropriately when the program ends
    recv.finished.connect(thread.quit)
    recv.finished.connect(recv.deleteLater)
    thread.finished.connect(thread.deleteLater)

    # start the receiver
    thread.start()
    # show the GUI
    mainGUIWindow.show()
    # display Imgur API pop up if not hidden by user and client-id isn't set
    if rddtDataExtractor.showImgurAPINotification and rddtDataExtractor.imgurAPIClientID is None:
        mainGUIWindow.notifyImgurAPI()
    # and wait for the user to exit
    sys.exit(app.exec_())
Ejemplo n.º 4
0
def main(args=sys.argv):
    # Ensure viewer can continue to function if GUI is closed
    os.environ.pop('CALIBRE_WORKER_TEMP_DIR', None)
    reset_base_dir()

    parser = option_parser()
    opts, args = parser.parse_args(args)
    if getattr(opts, 'detach', False):
        detach_gui()
    try:
        open_at = float(opts.open_at)
    except:
        open_at = None
    override = 'calibre-ebook-viewer' if islinux else None
    app = Application(args, override_program_name=override)
    app.load_builtin_fonts()
    app.setWindowIcon(QIcon(I('viewer.png')))
    QApplication.setOrganizationName(ORG_NAME)
    QApplication.setApplicationName(APP_UID)
    main = EbookViewer(args[1] if len(args) > 1 else None,
            debug_javascript=opts.debug_javascript, open_at=open_at,
                       start_in_fullscreen=opts.full_screen)
    # This is needed for paged mode. Without it, the first document that is
    # loaded will have extra blank space at the bottom, as
    # turn_off_internal_scrollbars does not take effect for the first
    # rendered document
    main.view.load_path(P('viewer/blank.html', allow_user_override=False))

    sys.excepthook = main.unhandled_exception
    main.show()
    if opts.raise_window:
        main.raise_()
    with main:
        return app.exec_()
    return 0
Ejemplo n.º 5
0
 def copy_to_clipboard(self):
     rows = {i.row() for i in self.selectedIndexes()}
     words = {self.model().word_for_row(r) for r in rows}
     words.discard(None)
     words = sorted({w[0] for w in words}, key=sort_key)
     if words:
         QApplication.clipboard().setText('\n'.join(words))
Ejemplo n.º 6
0
 def copy_to_clipboard(self, *args):
     QApplication.clipboard().setText(
             'calibre, version %s\n%s: %s\n\n%s' %
             (__version__, unicode(self.windowTitle()),
                 unicode(self.msg_label.text()),
                 unicode(self.det_msg.toPlainText())))
     self.copy_button.setText(_('Copied'))
Ejemplo n.º 7
0
 def decodeAndCopy(self, url):
     if url.startswith("https://slack-redir.net/link?url="):
         url_param = parse_qs(urlsplit(url).query).get('url')
         decodedURL = url_param[0] if url_param else url
     else:
         decodedURL = url
     QApplication.clipboard().setText(decodedURL)
Ejemplo n.º 8
0
 def fix_errors(self, container, errors):
     with BusyCursor():
         self.show_busy(_('Running fixers, please wait...'))
         QApplication.processEvents()
         changed = fix_errors(container, errors)
     self.run_checks(container)
     return changed
Ejemplo n.º 9
0
 def show_splash_screen(self):
     self.splash_pixmap = QPixmap()
     self.splash_pixmap.load(I("library.png"))
     self.splash_screen = QSplashScreen(self.splash_pixmap)
     self.splash_screen.showMessage(_("Starting %s: Loading books...") % __appname__)
     self.splash_screen.show()
     QApplication.instance().processEvents()
Ejemplo n.º 10
0
 def render_html(self, ok):
     try:
         if not ok:
             return
         cwidth, cheight = self.page.mainFrame().contentsSize().width(), self.page.mainFrame().contentsSize().height()
         self.page.setViewportSize(QSize(cwidth, cheight))
         factor = float(self.width)/cwidth if cwidth > self.width else 1
         cutoff_height = int(self.height/factor)-3
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(self.dpi*(100/2.54))
         image.setDotsPerMeterY(self.dpi*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         cheight = image.height()
         cwidth = image.width()
         pos = 0
         while pos < cheight:
             img = image.copy(0, pos, cwidth, min(cheight-pos, cutoff_height))
             pos += cutoff_height-20
             if cwidth > self.width:
                 img = img.scaledToWidth(self.width, Qt.SmoothTransform)
             f = os.path.join(self.tdir, '%d.png'%pos)
             img.save(f)
             self.images.append((f, img.width(), img.height()))
     finally:
         QApplication.quit()
Ejemplo n.º 11
0
Archivo: blain.py Proyecto: dodo/blain
    def __init__(self):
        print "loading ..."
        QApplication.__init__(self, sys.argv)

        self.cwd = dirname(realpath(__file__))
        self.window       =       Window(self)
        self.db           =    Databaser(self)
        self.preferences  =  Preferencer(self)
        self.filters      =     Filterer(self)
        self.icons        =       Iconer(self)
        self.accounts     =    Accounter(self)
        self.updates      =      Updater(self)
        self.threads      =     Threader(self)
        self.reader       =       Reader(self)
        self.notifier     =     Notifier(self)

        controllers = [self.window, self.db, self.preferences,
                       self.filters, self.accounts, self.updates,
                       self.icons, self.threads, self.reader,
                       self.notifier]

        for controller in controllers:
            controller.setup()
        # need to be seperated
        for controller in controllers:
            controller.connect()
Ejemplo n.º 12
0
def main(args=sys.argv):
    app = QApplication(args)
 
    spellEdit = SpellTextEdit()
    spellEdit.show()
 
    return app.exec_()
Ejemplo n.º 13
0
    def run(self):
        from trezorlib.pinmatrix import PinMatrixWidget

        import sys
        from PyQt4.Qt import QApplication, QWidget, QVBoxLayout
        from PyQt4.QtGui import QPushButton, QLabel
        from PyQt4.QtCore import QObject, SIGNAL

        a = QApplication(sys.argv)

        matrix = PinMatrixWidget()

        def clicked():
            self.pin_value = str(matrix.get_value())
            a.closeAllWindows()

        ok = QPushButton('OK')
        QObject.connect(ok, SIGNAL('clicked()'), clicked)

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(self.input_text + self.message))
        vbox.addWidget(matrix)
        vbox.addWidget(ok)

        w = QWidget()
        w.setLayout(vbox)
        w.move(100, 100)
        w.show()

        a.exec_()
Ejemplo n.º 14
0
def launch_editor(path_to_edit, path_is_raw=False, syntax='html'):
    from calibre.gui2.tweak_book import dictionaries
    from calibre.gui2.tweak_book.main import option_parser
    from calibre.gui2.tweak_book.ui import Main
    from calibre.gui2.tweak_book.editor.syntax.html import refresh_spell_check_status
    dictionaries.initialize()
    refresh_spell_check_status()
    opts = option_parser().parse_args([])
    app = QApplication([])
    # Create the actions that are placed into the editors toolbars
    main = Main(opts)  # noqa
    if path_is_raw:
        raw = path_to_edit
    else:
        with open(path_to_edit, 'rb') as f:
            raw = f.read().decode('utf-8')
        ext = path_to_edit.rpartition('.')[-1].lower()
        if ext in ('html', 'htm', 'xhtml', 'xhtm'):
            syntax = 'html'
        elif ext in ('css',):
            syntax = 'css'
    t = Editor(syntax)
    t.data = raw
    t.show()
    app.exec_()
Ejemplo n.º 15
0
def main():
    app = QApplication(sys.argv)
    rddtDataExtractor = loadState()
    if rddtDataExtractor is None:
        rddtDataExtractor = RedditDataExtractor()
    else:
        # If something weird happened to cause currentlyDownloading to be saved as True, set it back to False
        rddtDataExtractor.currentlyDownloading = False
        # reinstantiate the praw instance because it doesn't shelve properly
        # praw shelve issue causes http.validate_certs to be uninstantiated
        rddtDataExtractor._r = praw.Reddit(user_agent='Data Extractor for reddit v1.1 by /u/VoidXC')
        rddtDataExtractor._r.http.validate_certs = 'RedditDataExtractor/cacert.pem'

    queue = Queue()
    thread = QThread()
    recv = QueueMessageReceiver(queue)
    mainGUIWindow = RddtDataExtractorGUI(rddtDataExtractor, queue, recv)

    recv.queuePutSignal.connect(mainGUIWindow.append_text)
    recv.moveToThread(thread)
    thread.started.connect(recv.run)
    # Add clean up finished signals so the threads end appropriately when the program ends
    recv.finished.connect(thread.quit)
    recv.finished.connect(recv.deleteLater)
    thread.finished.connect(thread.deleteLater)

    # start the receiver
    thread.start()
    # show the GUI
    mainGUIWindow.show()
    # display Imgur API pop up if not hidden by user and client-id isn't set
    if rddtDataExtractor.showImgurAPINotification and rddtDataExtractor.imgurAPIClientID is None:
        mainGUIWindow.notifyImgurAPI()
    # and wait for the user to exit
    sys.exit(app.exec_())
Ejemplo n.º 16
0
def main():
    """ Main loop to run text widget as applation
    """
    app = QApplication(sys.argv)

    mwTextEditor = QMainWindow()
    textEditorBar = EditorBar(mwTextEditor)
    textEditor = TextWidget(textEditorBar)

    textEditorBar.saveDocAsSignal.connect(textEditor.saveAs)
    textEditorBar.spellSignal.connect(textEditor.toggleSpell)
    textEditorBar.whiteSpaceSignal.connect(textEditor.togglewhiteSpace)
    textEditorBar.boldSignal.connect(textEditor.toggleBold)
    textEditorBar.italicSignal.connect(textEditor.toggleItalic)
    textEditorBar.underlineSignal.connect(textEditor.toggleUnderline)
    textEditorBar.strikethroughSignal.connect(textEditor.toggleStrikethrough)
    textEditorBar.subscriptSignal.connect(textEditor.toggleSubscript)
    textEditorBar.superscriptSignal.connect(textEditor.toggleSuperscript)

    textEditor.fontFormatSignal.connect(textEditorBar.toggleFormat)

    mwTextEditor.addToolBar(textEditorBar)
    mwTextEditor.setCentralWidget(textEditor)

    mwTextEditor.show()

    return app.exec_()
Ejemplo n.º 17
0
 def clock(self):
     runner.clock(self)
     if len(self.unfinished_procs) == 0:
         print "Finished in %d cycles." % simulator.cycle
         QApplication.quit()
     for c in self.components:
         c.update_color()
Ejemplo n.º 18
0
    def __init__(self, view):
        QObject.__init__(self, view)
        self.state = State()
        self.state.swiped.connect(self.handle_swipe)
        self.evmap = {QEvent.TouchBegin: 'start', QEvent.TouchUpdate: 'update', QEvent.TouchEnd: 'end'}

        # Ignore fake mouse events generated by the window system from touch
        # events. At least on windows, we know how to identify these fake
        # events. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
        self.is_fake_mouse_event = lambda : False
        if touch_supported and iswindows:
            MI_WP_SIGNATURE = 0xFF515700
            SIGNATURE_MASK = 0xFFFFFF00
            try:
                f = ctypes.windll.user32.GetMessageExtraInfo
                f.restype = wintypes.LPARAM
                def is_fake_mouse_event():
                    val = f()
                    ans = (val & SIGNATURE_MASK) == MI_WP_SIGNATURE
                    return ans
                self.is_fake_mouse_event = is_fake_mouse_event
                QApplication.instance().focusChanged.connect(self.register_for_wm_touch)
            except Exception:
                import traceback
                traceback.print_exc()
Ejemplo n.º 19
0
 def add_image_diff(self, left_data, right_data):
     def load(data):
         p = QPixmap()
         p.loadFromData(bytes(data))
         if data and p.isNull():
             p = self.failed_img
         return p
     left_img, right_img = load(left_data), load(right_data)
     change = []
     # Let any initial resizing of the window finish in case this is the
     # first diff, to avoid the expensive resize calculation later
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
     for v, img, size in ((self.left, left_img, len(left_data)), (self.right, right_img, len(right_data))):
         c = v.textCursor()
         c.movePosition(c.End)
         start = c.block().blockNumber()
         lines, w = self.get_lines_for_image(img, v)
         c.movePosition(c.StartOfBlock)
         if size > 0:
             c.beginEditBlock()
             c.insertText(_('Size: {0} Resolution: {1}x{2}').format(human_readable(size), img.width(), img.height()))
             for i in xrange(lines + 1):
                 c.insertBlock()
         change.extend((start, c.block().blockNumber()))
         c.insertBlock()
         c.endEditBlock()
         v.images[start] = (img, w, lines)
     change.append('replace' if left_data and right_data else 'delete' if left_data else 'insert')
     self.left.changes.append((change[0], change[1], change[-1]))
     self.right.changes.append((change[2], change[3], change[-1]))
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
 def _analyseCsv(self):
     self.dataSourceHandler = None
     self.vectorDescriptor = None
     csvFilePath = self.newDialog.filePath.text()
     if csvFilePath:
         try:                    
             self._updateDataSource(csvFilePath) 
             self._hideCharsetWidget()               
         except InvalidDataSourceException as e:
             self.newDialog.statusNotificationLabel.setText(QApplication.translate('GeoCsvNewController', 'invalid file path'))            
             self._hideGeometryTypeWidget()
             self._hideCharsetWidget()
         except InvalidDelimiterException as e:
             #currently not tested
             self.newDialog.statusNotificationLabel.setText(QApplication.translate('GeoCsvNewController', 'invalid delimiter. expected "{}"').format(e.expectedDelimiter))
             self._hideGeometryTypeWidget()
             self._hideCharsetWidget()
         except UnicodeDecodeError:
             self._hideGeometryTypeWidget()                
             self._onCharsetError()                            
         else:
             self._createVectorDescriptorFromCsvt()
             self._hideCharsetWidget()
             self._showGeometryTypeWidget()     
     else:            
         self.newDialog.statusNotificationLabel.setText("")
     self._updateAcceptButton()
Ejemplo n.º 21
0
        def do_all(replace=True):
            count = 0
            if not files and editor is None:
                return 0
            lfiles = files or {name:editor.syntax}

            for n, syntax in lfiles.iteritems():
                if n in editors:
                    raw = editors[n].get_raw_data()
                else:
                    raw = current_container().raw_data(n)
                if replace:
                    raw, num = pat.subn(state['replace'], raw)
                else:
                    num = len(pat.findall(raw))
                count += num
                if replace and num > 0:
                    if n in editors:
                        editors[n].replace_data(raw)
                    else:
                        with current_container().open(n, 'wb') as f:
                            f.write(raw.encode('utf-8'))
            QApplication.restoreOverrideCursor()
            count_message(_('Replaced') if replace else _('Found'), count)
            return count
Ejemplo n.º 22
0
 def handle_tap_hold(self, action, tp):
     etype = {'start':QEvent.MouseButtonPress, 'update':QEvent.MouseMove, 'end':QEvent.MouseButtonRelease}[action]
     ev = QMouseEvent(etype, self.current_position(tp), tp.current_screen_position.toPoint(), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
     QApplication.sendEvent(self.parent(), ev)
     if action == 'end':
         ev = QContextMenuEvent(QContextMenuEvent.Other, self.current_position(tp), tp.current_screen_position.toPoint())
         # We have to use post event otherwise the popup remains an alien widget and does not receive events
         QApplication.postEvent(self.parent(), ev)
Ejemplo n.º 23
0
 def start_qt():
     global app
     app = QApplication(sys.argv)
     app.setQuitOnLastWindowClosed(False)
     from malcolm.gui.guiopener import GuiOpener
     global opener
     opener = GuiOpener()
     app.exec_()
Ejemplo n.º 24
0
 def copy(self):
     # Workaround Qt replacing nbsp with normal spaces on copy
     c = self.textCursor()
     if not c.hasSelection():
         return
     md = QMimeData()
     md.setText(self.selected_text)
     QApplication.clipboard().setMimeData(md)
Ejemplo n.º 25
0
 def __init__(self,name,interval=1000):
     if self not in self.indicators:
         self.indicators += [self]
     self.name = name
     self.interval = interval
     self.initSystray()
     self.splash = None
     QApplication.desktop().resized.connect( self.screenSizeChanged)
Ejemplo n.º 26
0
 def no_replace(prefix=''):
     QApplication.restoreOverrideCursor()
     if prefix:
         prefix += ' '
     error_dialog(
         self.gui, _('Cannot replace'), prefix + _(
         'You must first click Find, before trying to replace'), show=True)
     return False
Ejemplo n.º 27
0
def __testWikiHelpBrowser():
    import sys

    app = QApplication(sys.argv)
    w = WikiHelpBrowser("Here is a wiki page about " + __wikiPageHtmlLink("QWhatsThis and web links") + " to click.")
    w.show()
    app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
    app.exec_()
Ejemplo n.º 28
0
 def fix_errors(self, container, errors):
     from calibre.gui2.tweak_book.boss import BusyCursor
     with BusyCursor():
         self.show_busy(_('Running fixers, please wait...'))
         QApplication.processEvents()
         changed = fix_errors(container, errors)
     self.run_checks(container)
     return changed
Ejemplo n.º 29
0
 def copy_to_clipboard(self):
     items = []
     for item in (self.items.item(i) for i in xrange(self.items.count())):
         msg = unicode(item.text())
         msg = prefix_for_level(item.data(Qt.UserRole).toPyObject().level) + msg
         items.append(msg)
     if items:
         QApplication.clipboard().setText('\n'.join(items))
Ejemplo n.º 30
0
def main(args=sys.argv):
    app = QApplication(args)

    widget = SpellCheckTextEdit('Type here')
    widget.show()
    widget.raise_()

    return app.exec_()
Ejemplo n.º 31
0
    def restore_defaults(self):
        if self.devices.count() > 0:
            self.devices.clear()

    def commit(self):
        devs = {}
        for i in xrange(0, self.devices.count()):
            e = self.devices.item(i)
            dev, uid = e.data(Qt.UserRole).toPyObject()
            if dev not in devs:
                devs[dev] = []
            if e.checkState() == Qt.Checked:
                devs[dev].append(uid)

        for dev, bl in devs.iteritems():
            dev.set_user_blacklisted_devices(bl)

        for i in xrange(self.device_plugins.count()):
            e = self.device_plugins.item(i)
            dev = e.data(Qt.UserRole).toPyObject()
            if e.checkState() == Qt.Unchecked:
                enable_plugin(dev)

        return True  # Restart required


if __name__ == '__main__':
    from PyQt4.Qt import QApplication
    app = QApplication([])
    test_widget('Sharing', 'Ignored Devices')
Ejemplo n.º 32
0
            return
        self._dialog.videoPlayer.stop()

    def _pauseMedia(self):
        """
        Pause the media streaming
        """
        if not self._okToPlayPauseStop():
            return
        self._dialog.videoPlayer.pause()

    def _okToPlayPauseStop(self):
        """
        Determines if the medai source can be played paused or stopped.
        """
        okToProceed = True
        if self.mediaSource is None:
            err = "Specify an audio file using File->Open"
            self._dialog.fileLineEdit.setText(err)
            okToProceed = False

        return okToProceed


#----------------------------------
# Run the Video Player !
#----------------------------------
app = QApplication(sys.argv)
videoPlayer = VideoPlayerDialog()
app.exec_()
Ejemplo n.º 33
0
 def run(self):
     QTimer.singleShot(self.old_time, self.update)
     while self.cycles:
         QApplication.processEvents()
     self.emit(self.signal)
Ejemplo n.º 34
0
    def start_animation(self):
        if config['disable_animations']: return
        if self.animation.state(
        ) != self.animation.Stopped or not self.isVisible():
            return
        size = self.normal_icon_size.width()
        smaller = int(0.7 * size)
        self.animation.setStartValue(QSize(smaller, smaller))
        self.animation.setEndValue(self.normal_icon_size)
        QMetaObject.invokeMethod(self.animation, 'start', Qt.QueuedConnection)

    def stop_animation(self):
        self.animation.stop()
        self.animation_finished()


if __name__ == '__main__':
    from PyQt4.Qt import QApplication, QWidget, QHBoxLayout, QIcon
    app = QApplication([])
    w = QWidget()
    w.setLayout(QHBoxLayout())
    b = ThrobbingButton()
    b.setIcon(QIcon(I('donate.png')))
    w.layout().addWidget(b)
    w.show()
    b.set_normal_icon_size(64, 64)
    b.start_animation()

    app.exec_()
Ejemplo n.º 35
0
 def copyQuoted(self, str):
     mark = '> '
     quote = mark + str.replace('\n', '\n' + mark)
     QApplication.clipboard().setText(quote)
Ejemplo n.º 36
0
 def show_windows(self):
     for window in QApplication.topLevelWidgets():
         if getattr(window, '__systray_minimized', False):
             window.show()
             setattr(window, '__systray_minimized', False)
Ejemplo n.º 37
0
 def event_has_mods(self, event=None):
     mods = event.modifiers() if event is not None else \
             QApplication.keyboardModifiers()
     return mods & Qt.ControlModifier or mods & Qt.ShiftModifier
Ejemplo n.º 38
0
def main():
    QApplication.setApplicationName(__appname__+' console')
    QApplication.setOrganizationName('Kovid Goyal')
    app = QApplication([])
    app
    show()
Ejemplo n.º 39
0
 def __exit__(self, *args):
     QApplication.restoreOverrideCursor()
Ejemplo n.º 40
0
def render_html(current_book,
                css,
                vertical,
                widget,
                all_fields=False,
                render_data_func=None):
    u"""

    :param current_book:
    :param css:
    :param vertical:
    :param widget:
    :param all_fields:
    :param render_data_func:
    :return:
    """
    table, comment_fields = render_data(current_book,
                                        all_fields=all_fields,
                                        use_roman_numbers=True)

    def color_to_string(col):
        ans = '#000000'
        if col.isValid():
            col = col.toRgb()
            if col.isValid():
                ans = unicode(col.name())
        return ans

    font_info = QFontInfo(QApplication.font(widget))
    font_px = font_info.pixelSize() + 1
    font_family = unicode(font_info.family()).strip().replace('"', '')

    if not font_family:
        font_family = 'sans-serif'

    body_td_color = color_to_string(QApplication.palette().color(
        QPalette.Normal, QPalette.WindowText))

    template = u"""
    <html>
        <head>
        <style type="text/css">
            body, td {
                background-color: transparent;
                font-size: %dpx;
                font-family: "%s", sans-serif;
                color: %s
            }
        </style>
        <style type="text/css">
            %s
        </style>
        </head>
        <body>
        %%s
        </body>
    </html>
    """ % (font_px, font_family, body_td_color, css)
    comments = u''
    comment_fields = None
    if comment_fields:
        comments = '\n'.join(u'<div>%s</div>' % x for x in comment_fields)
    right_pane = u'<div id="comments" class="comments">%s</div>' % comments

    if vertical:
        ans = template % (table + right_pane)
    else:
        ans = template % (
            u'<table><tr><td valign="top" '
            'style="padding-right:2em; width:40%%">%s</td><td valign="top">%s</td></tr></table>'
            % (table, right_pane))
    return ans
Ejemplo n.º 41
0
class TestCloudPreferencesPage(TestCase):
    def setUp(self):
        self.app = QApplication(sys.argv)
        self.app.setOrganizationName("GNS3")
        self.app.setOrganizationDomain("gns3.net")
        self.app.setApplicationName("Testsuite")
        self.page = CloudPreferencesPage()
        # mock settings instance inside the page widget
        self.page.settings = mock.MagicMock()
        settings_copy = CLOUD_SETTINGS.copy()
        self.page.settings.__getitem__.side_effect = make_getitem(settings_copy)
        self.page.settings.__setitem__.side_effect = make_setitem(settings_copy)
        self._init_page()

    def tearDown(self):
        # Explicitly deallocate QApplication instance to avoid crashes
        del self.app

    def _init_page(self):
        self.page = CloudPreferencesPage()
        self.page.settings = mock.MagicMock()
        fake_settings = CLOUD_SETTINGS.copy()
        self.page.settings.__getitem__.side_effect = make_getitem(fake_settings)
        self.page.settings.__setitem__.side_effect = make_setitem(fake_settings)

    def test_defaults(self):
        self.page.loadPreferences()
        self.assertFalse(self.page.uiForgetAPIKeyRadioButton.isChecked())
        self.assertFalse(self.page.uiRememberAPIKeyRadioButton.isChecked())
        # saving preferences without setting "store or not" radio button triggers a message box
        def closeMsgBox():
            self.assertIsInstance(self.app.activeModalWidget(), QtGui.QMessageBox)
            self.app.activeModalWidget().close()
        QTimer.singleShot(100, closeMsgBox)
        self.page.uiUserNameLineEdit.setText('foo')
        self.page.uiAPIKeyLineEdit.setText('bar')
        valid = self.page._validate()
        self.assertFalse(valid)
        self.assertEqual(self.page.uiCloudProviderComboBox.currentIndex(), 0)
        self.assertEqual(self.page.uiRegionComboBox.currentIndex(), -1)  # not set
        self.assertEqual(self.page.uiMemPerInstanceSpinBox.value(), 1)
        self.assertEqual(self.page.uiMemPerNewInstanceSpinBox.value(), 1)
        self.assertEqual(self.page.uiNumOfInstancesSpinBox.value(), 0)
        self.assertFalse(self.page.uiTermsCheckBox.isChecked())
        self.assertEqual(self.page.uiTimeoutSpinBox.value(), 30)

    def test_user_interaction(self):
        """
        Simulate user interactions via keyboard or mouse and check dialog status
        """
        # following line is because of https://bugreports.qt-project.org/browse/QTBUG-14483
        self.page.show()

        QTest.keyClicks(self.page.uiUserNameLineEdit, "Bob")
        self.assertEqual(self.page.uiUserNameLineEdit.text(), 'Bob')
        QTest.keyClick(self.page.uiAPIKeyLineEdit, Qt.Key_Eacute)
        self.assertEqual(self.page.uiAPIKeyLineEdit.text(), 'É')
        QTest.mouseClick(self.page.uiRememberAPIKeyRadioButton, Qt.LeftButton)
        self.assertTrue(self.page._store_api_key())
        QTest.mouseClick(self.page.uiTermsCheckBox, Qt.LeftButton)
        self.assertTrue(self.page.uiTermsCheckBox.isChecked())
        QTest.mouseClick(self.page.uiForgetAPIKeyRadioButton, Qt.LeftButton)
        self.assertFalse(self.page._store_api_key())

        self.assertTrue(self.page._validate())

    def test_load_settings(self):
        self.page.settings['cloud_store_api_key_chosen'] = True

        self.page.loadPreferences()

        self.page.settings['cloud_user_name'] = 'Bob'
        self.page.settings['cloud_api_key'] = '1234567890€'
        self.page.settings['cloud_store_api_key'] = True
        self.page.settings['cloud_store_api_key_chosen'] = True
        self.page.settings['cloud_provider'] = 'rackspace'
        self.page.settings['cloud_region'] = 'United States'
        self.page.settings['accepted_terms'] = True
        self.page.settings['instances_per_project'] = 3
        self.page.settings['memory_per_instance'] = 2
        self.page.settings['memory_per_new_instance'] = 6
        self.page.settings['instance_timeout'] = 120

        self.page.loadPreferences()

        self.assertEqual(self.page.uiUserNameLineEdit.text(), 'Bob')
        self.assertEqual(self.page.uiAPIKeyLineEdit.text(), '1234567890€')
        self.assertFalse(self.page.uiForgetAPIKeyRadioButton.isChecked())
        self.assertTrue(self.page.uiRememberAPIKeyRadioButton.isChecked())
        self.assertEqual(self.page.uiCloudProviderComboBox.currentText(), "Rackspace")
        self.assertEqual(self.page.uiRegionComboBox.currentText(), "United States")
        self.assertTrue(self.page.uiTermsCheckBox.isChecked())
        self.assertEqual(self.page.uiNumOfInstancesSpinBox.value(), 3)
        self.assertEqual(self.page.uiMemPerInstanceSpinBox.value(), 2)
        self.assertEqual(self.page.uiMemPerNewInstanceSpinBox.value(), 6)
        self.assertEqual(self.page.uiTimeoutSpinBox.value(), 120)

    def test_save_preferences(self):
        self.page.settings['cloud_store_api_key_chosen'] = True
        self.page.settings['cloud_provider'] = 'rackspace'
        self.page.loadPreferences()

        self.page.uiUserNameLineEdit.setText("foo")
        self.page.uiAPIKeyLineEdit.setText("bar")
        self.page.uiRememberAPIKeyRadioButton.setChecked(True)
        self.page.uiTermsCheckBox.setChecked(True)
        self.page.uiRememberAPIKeyRadioButton.setChecked(True)
        self.page.uiCloudProviderComboBox.setCurrentIndex(1)
        self.page.uiRegionComboBox.setCurrentIndex(1)
        self.page.uiTermsCheckBox.setChecked(True)
        self.page.uiNumOfInstancesSpinBox.setValue(8)
        self.page.uiMemPerInstanceSpinBox.setValue(16)
        self.page.uiMemPerNewInstanceSpinBox.setValue(32)
        self.page.uiTimeoutSpinBox.setValue(5)

        self.page.savePreferences()

        self.assertTrue(self.page.settings['cloud_store_api_key'])
        self.assertEqual(self.page.settings['cloud_provider'], 'rackspace')
        self.assertEqual(self.page.settings['cloud_region'], 'United States')
        self.assertTrue(self.page.settings['accepted_terms'])
        self.assertEqual(self.page.settings['instances_per_project'], 8)
        self.assertEqual(self.page.settings['memory_per_instance'], 16)
        self.assertEqual(self.page.settings['memory_per_new_instance'], 32)
        self.assertEqual(self.page.settings['instance_timeout'], 5)

    def test_clear_settings_on_user_request(self):
        # no mocking for this testcase
        page = CloudPreferencesPage()
        # first run, user stores settings on disk
        page.uiRememberAPIKeyRadioButton.setChecked(True)
        page.uiAPIKeyLineEdit.setText("myapikey")
        page.uiUserNameLineEdit.setText("myusername")
        page.uiTermsCheckBox.setChecked(True)
        page.savePreferences()
        settings = MainWindow.instance().cloud_settings()
        self.assertTrue(settings.get('cloud_store_api_key'))
        self.assertEqual(settings.get('cloud_api_key'), 'myapikey')
        self.assertEqual(settings.get('cloud_user_name'), 'myusername')
        # now users change their mind
        page.uiForgetAPIKeyRadioButton.setChecked(True)
        page.savePreferences()
        # mainwindow settings should be still valid at this point...
        self.assertTrue(settings.get('cloud_store_api_key'))
        self.assertEqual(settings.get('cloud_api_key'), 'myapikey')
        self.assertEqual(settings.get('cloud_user_name'), 'myusername')
        # ...and values on disk should be gone
        stored_settings = QtCore.QSettings()
        stored_settings.beginGroup(CLOUD_SETTINGS_GROUP)
        self.assertFalse(stored_settings.value('cloud_store_api_key', type=bool))
        self.assertEqual(stored_settings.value('cloud_api_key', type=str), '')
        self.assertEqual(stored_settings.value('cloud_user_name', type=str), '')
Ejemplo n.º 42
0
 def hide_windows(self):
     for window in QApplication.topLevelWidgets():
         if isinstance(window, (MainWindow, QDialog)) and \
                 window.isVisible():
             window.hide()
             setattr(window, '__systray_minimized', True)
Ejemplo n.º 43
0
 def copy_to_clipboard(self):
     QApplication.clipboard().setText(''.join(self.log.plain_text))
Ejemplo n.º 44
0
            img2 = self.imv2.getImageItem()
            h, y = img2.getHistogram()
            self.imv2.setLevels(min(h), max(h))
        else:
            img = self.imv.getImageItem()
            h, y = img.getHistogram()
            self.imv.setLevels(min(h), max(h))


if __name__ == "__main__":
    import sys
    from PyQt4.Qt import QApplication
    from lantz import Q_
    import numpy as np

    ap = QApplication(sys.argv)
    m = ScanMonitorWidget()
    axis = {
        'wavelength': {
            'stop': Q_('1500nm'),
            'start': Q_('1200nm'),
            'step': Q_('1nm')
        },
        'y_axis': {
            'name': 'y_axis',
            'start': Q_('1mm'),
            'stop': Q_('10mm'),
            'step': Q_('1mm'),
        }
    }
    m.two_way = True
Ejemplo n.º 45
0
    def mouseMoveEvent(self, event):
        if self.drag is not None:
            QTreeView.mouseMoveEvent(self, event)
            return
        if ((event.globalPos() - self.mouse_press_qpoint).manhattanLength() <
                QApplication.startDragDistance()):
            return
        #
        # starting a drag
        # [logic bug, after bruce change 070507: should not do this
        #  if we already started dragging out a selection. How can we tell?
        #  Only by whether the initial press had eventInRect, I think
        #  (not yet recorded), or at least, the initial move (#e could record here).]
        #
        index = self.indexAt(event.pos())

        sellst = self.selectedList()  # bruce 070507 move earlier

        DEBUG2 = True

        if index.isValid():
            thisnode = index.internalPointer().node

            #bruce 070507 bring in some code from modelTreeGui.py
            alreadySelected = (thisnode in sellst)

            item = index.internalPointer()
            rect = self.visualRect(index)
            if DEBUG2:
                print "visualRect coords", rect.left(), rect.right(), rect.top(
                ), rect.bottom()
            qfm = QFontMetrics(QLineEdit(self).font())
            rect.setWidth(qfm.width(item.node.name) + _ICONSIZE[0] + 4)
            if DEBUG2:
                print "visualRect coords, modified:", rect.left(), rect.right(
                ), rect.top(), rect.bottom()
                # looks like icon and text, a bit taller than text (guesses)
            eventInRect = rect.contains(event.pos())
            if DEBUG2:
                print "valid index: eventInRect = %r, item = %r, index = %r, alreadySelected = %r" % \
                      (eventInRect, item, index, alreadySelected)#######
        else:
            thisnode = item = None
            alreadySelected = eventInRect = False

        if not eventInRect:
            # nothing to drag, but [bruce 070507] let super handle it (for dragging over nodes to select)
            self.drag_is_not_DND = True  ### not yet used
            QTreeView.mouseMoveEvent(self, event)
            return

        if thisnode in sellst:
            # if dragging something selected, drag along all other selected ones
            dragged_nodes = sellst
        else:
            # if dragging something unselected, ignore any selected ones
            dragged_nodes = [thisnode]
        qdrag = QDrag(self)
        drag_type = 'move'  # how do I decide between 'move' and 'copy'?
        self.drag = (dragged_nodes, drag_type, qdrag)
        mimedata = QMimeData()
        mimedata.setText("need a string here for a valid mimetype")
        qdrag.setMimeData(mimedata)
        display_prefs = {}
        pixmap = dragged_nodes[0].node_icon(display_prefs)
        qdrag.setPixmap(pixmap)
        qdrag.setHotSpot(QPoint(-8, 8))
        qdrag.start()
Ejemplo n.º 46
0
 def check_terminal_save(self):
     if self.save_manager.has_tasks:
         return QTimer.singleShot(50, self.check_terminal_save)
     self.shutdown()
     QApplication.instance().quit()
Ejemplo n.º 47
0
    print("Please wait a second while the GUI starts up.")

    import sys
    import signal
    import os
    import os.path

    from PyQt4.Qt import *

    import Purr
    import Purr.MainWindow
    import Purr.Render
    import Purr.Startup

    app = QApplication(sys.argv)
    app.setDesktopSettingsAware(True)

    #  splash = QSplashScreen(Purr.pixmaps.purr_logo.pm())
    #  splash.showMessage("PURR!")
    #  splash.show()

    purrwin = Purr.MainWindow.MainWindow(None)

    try:
        if not Purr.Startup.startWizard(rem_args, purrwin):
            print("Cancelled by user")
            os._exit(1)
    except Purr.Startup.Error as err:
        print(err.error_message)
        os._exit(1)
Ejemplo n.º 48
0
 def copy_to_clipboard(self):
     QApplication.clipboard().setText(self.log.toPlainText())
Ejemplo n.º 49
0
    def load_ebook(self, pathtoebook, open_at=None):
        if self.iterator is not None:
            self.save_current_position()
            self.iterator.__exit__()
        self.iterator = EbookIterator(pathtoebook)
        self.open_progress_indicator(_('Loading ebook...'))
        worker = Worker(target=partial(self.iterator.__enter__,
                                       extract_embedded_fonts_for_qt=True))
        worker.start()
        while worker.isAlive():
            worker.join(0.1)
            QApplication.processEvents()
        if worker.exception is not None:
            if isinstance(worker.exception, DRMError):
                from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                DRMErrorMessage(self).exec_()
            else:
                r = getattr(worker.exception, 'reason', worker.exception)
                error_dialog(self,
                             _('Could not open ebook'),
                             as_unicode(r) or _('Unknown error'),
                             det_msg=worker.traceback,
                             show=True)
            self.close_progress_indicator()
        else:
            self.metadata.show_opf(self.iterator.opf,
                                   self.iterator.book_format)
            self.view.current_language = self.iterator.language
            title = self.iterator.opf.title
            if not title:
                title = os.path.splitext(os.path.basename(pathtoebook))[0]
            if self.iterator.toc:
                self.toc_model = TOC(self.iterator.spine, self.iterator.toc)
                self.toc.setModel(self.toc_model)
                if self.show_toc_on_open:
                    self.action_table_of_contents.setChecked(True)
            else:
                self.toc_model = TOC(self.iterator.spine)
                self.toc.setModel(self.toc_model)
                self.action_table_of_contents.setChecked(False)
            if isbytestring(pathtoebook):
                pathtoebook = force_unicode(pathtoebook, filesystem_encoding)
            vh = vprefs.get('viewer_open_history', [])
            try:
                vh.remove(pathtoebook)
            except:
                pass
            vh.insert(0, pathtoebook)
            vprefs.set('viewer_open_history', vh[:50])
            self.build_recent_menu()

            self.action_table_of_contents.setDisabled(not self.iterator.toc)
            self.current_book_has_toc = bool(self.iterator.toc)
            self.current_title = title
            self.setWindowTitle(self.base_window_title + ' - ' + title +
                                ' [%s]' % self.iterator.book_format)
            self.pos.setMaximum(sum(self.iterator.pages))
            self.pos.setSuffix(' / %d' % sum(self.iterator.pages))
            self.vertical_scrollbar.setMinimum(100)
            self.vertical_scrollbar.setMaximum(100 * sum(self.iterator.pages))
            self.vertical_scrollbar.setSingleStep(10)
            self.vertical_scrollbar.setPageStep(100)
            self.set_vscrollbar_value(1)
            self.current_index = -1
            QApplication.instance().alert(self, 5000)
            previous = self.set_bookmarks(self.iterator.bookmarks)
            if open_at is None and previous is not None:
                self.goto_bookmark(previous)
            else:
                if open_at is None:
                    self.next_document()
                else:
                    if open_at > self.pos.maximum():
                        open_at = self.pos.maximum()
                    if open_at < self.pos.minimum():
                        open_at = self.pos.minimum()
                    self.goto_page(open_at, loaded_check=False)
Ejemplo n.º 50
0
 def quit(self):
     if not self.confirm_quit():
         return
     self.save_state()
     QApplication.instance().quit()
Ejemplo n.º 51
0
 def __enter__(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
Ejemplo n.º 52
0
    def computeImage(self, expression=None):
        """Computes image from expression (if expression is None, pops up dialog)"""
        if expression is None:
            (expression, ok) = QInputDialog.getText(
                self, "Compute image", """Enter an image expression to compute.
                                              Any valid numpy expression is supported, and
                                              all functions from the numpy module are available (including sub-modules such as fft).
                                              Use 'a', 'b', 'c' to refer to images.
                                              Examples:  "(a+b)/2", "cos(a)+sin(b)", "a-a.mean()", "fft.fft2(a)", etc."""
            )
            #      (expression,ok) = QInputDialog.getText(self,"Compute image","""<P>Enter an expression to compute.
            #        Use 'a', 'b', etc. to refer to loaded images. Any valid numpy expression is supported, and all the
            #       functions from the numpy module are available. Examples of valid expressions include "(a+b)/2",
            #       "cos(a)+sin(b)", "a-a.mean()", etc.
            #        </P>
            #      """)
            expression = str(expression)
            if not ok or not expression:
                return
        # try to parse expression
        arglist = [(chr(ord('a') + ic.getNumber()), ic.image)
                   for ic in self._imagecons]
        try:
            exprfunc = eval(
                "lambda " + (",".join([x[0]
                                       for x in arglist])) + ":" + expression,
                numpy.__dict__, {})
        except Exception as exc:
            self.showErrorMessage("""Error parsing expression "%s": %s.""" %
                                  (expression, str(exc)))
            return None
        # try to evaluate expression
        self.showMessage("Computing expression \"%s\"" % expression, 10000)
        busy = BusyIndicator()
        QApplication.flush()

        # trim trivial trailing dimensions. This avoids the problem of when an NxMx1 and an NxMx1x1 arrays are added,
        # the result is promoted to NxMxMx1 following the numpy rules.
        def trimshape(shape):
            out = shape
            while out and out[-1] == 1:
                out = out[:-1]
            return out

        def trimarray(array):
            return array.reshape(trimshape(array.shape))

        try:
            result = exprfunc(*[trimarray(x[1].data()) for x in arglist])
        except Exception as exc:
            busy = None
            traceback.print_exc()
            self.showErrorMessage("""Error evaluating "%s": %s.""" %
                                  (expression, str(exc)))
            return None
        busy = None
        if type(result) != numpy.ma.masked_array and type(
                result) != numpy.ndarray:
            self.showErrorMessage(
                """Result of "%s" is of invalid type "%s" (array expected)."""
                % (expression, type(result).__name__))
            return None
        # convert coomplex results to real
        if numpy.iscomplexobj(result):
            self.showErrorMessage(
                """Result of "%s" is complex. Complex images are currently
      not fully supported, so we'll implicitly use the absolute value instead."""
                % (expression))
            expression = "abs(%s)" % expression
            result = abs(result)
        # determine which image this expression can be associated with
        res_shape = trimshape(result.shape)
        arglist = [
            x for x in arglist if hasattr(x[1], 'fits_header')
            and trimshape(x[1].data().shape) == res_shape
        ]
        if not arglist:
            self.showErrorMessage(
                """Result of "%s" has shape %s, which does not match any loaded FITS image."""
                % (expression, "x".join(map(str, result.shape))))
            return None
        # look for an image in the arglist with the same projection, and with a valid dirname
        # (for the where-to-save hint)
        template = arglist[0][1]
        # if all images in arglist have the same projection, then it doesn't matter what we use
        # else ask
        if len(
            [x for x in arglist[1:] if x[1].projection == template.projection
             ]) != len(arglist) - 1:
            options = [x[0] for x in arglist]
            (which, ok) = QInputDialog.getItem(
                self, "Compute image",
                "Coordinate system to use for the result of \"%s\":" %
                expression, options, 0, False)
            if not ok:
                return None
            try:
                template = arglist[options.index(which)][1]
            except:
                pass
        # create a FITS image
        busy = BusyIndicator()
        dprint(2, "creating FITS image", expression)
        self.showMessage("""Creating image for %s""" % expression, 3000)
        QApplication.flush()
        try:
            hdu = pyfits.PrimaryHDU(result.transpose(), template.fits_header)
            skyimage = SkyImage.FITSImagePlotItem(name=expression,
                                                  filename=None,
                                                  hdu=hdu)
        except:
            busy = None
            traceback.print_exc()
            self.showErrorMessage("""Error creating FITS image %s: %s""" %
                                  (expression, str(sys.exc_info()[1])))
            return None
        # get directory name for save-to hint
        dirname = getattr(template, 'filename', None)
        if not dirname:
            dirnames = [
                getattr(img, 'filename') for x, img in arglist
                if hasattr(img, 'filename')
            ]
            dirname = dirnames[0] if dirnames else None
        # create control bar, add to widget stack
        self._createImageController(
            skyimage,
            expression,
            expression,
            save=((dirname and os.path.dirname(dirname)) or "."))
        self.showMessage("Created new image for %s" % expression, 3000)
        dprint(2, "image created")
Ejemplo n.º 53
0
                import traceback
                # Probably the user deleted the files, in any case, failing
                # to delete the book is not catastrophic
                traceback.print_exc()

    def email_news(self, id_):
        mi = self.library_view.model().db.get_metadata(id_,
                index_is_id=True)
        remove = [id_] if config['delete_news_from_library_on_upload'] \
                else []
        def get_fmts(fmts):
            files, auto = self.library_view.model().\
                    get_preferred_formats_from_ids([id_], fmts,
                            set_metadata=True,
                            use_plugboard=plugboard_email_value,
                            plugboard_formats=plugboard_email_formats)
            return files
        sent_mails = email_news(mi, remove,
                get_fmts, self.email_sent, self.job_manager)
        if sent_mails:
            self.status_bar.show_message(_('Sent news to')+' '+
                    ', '.join(sent_mails),  3000)

# }}}

if __name__ == '__main__':
    from PyQt4.Qt import QApplication
    app = QApplication([])  # noqa
    print (select_recipients())

Ejemplo n.º 54
0
 def loadImage(self,
               filename=None,
               duplicate=True,
               to_top=True,
               model=None):
     """Loads image. Returns ImageControlBar object.
     If image is already loaded: returns old ICB if duplicate=False (raises to top if to_top=True),
     or else makes a new control bar.
     If model is set to a source name, marks the image as associated with a model source. These can be unloaded en masse by calling
     unloadModelImages().
     """
     if filename is None:
         if not self._load_image_dialog:
             dialog = self._load_image_dialog = QFileDialog(
                 self, "Load FITS image", ".",
                 "FITS images (%s);;All files (*)" %
                 (" ".join(["*" + ext for ext in FITS_ExtensionList])))
             dialog.setFileMode(QFileDialog.ExistingFile)
             dialog.setModal(True)
             QObject.connect(dialog,
                             SIGNAL("filesSelected(const QStringList &)"),
                             self.loadImage)
         self._load_image_dialog.exec_()
         return None
     if isinstance(filename, QStringList):
         filename = filename[0]
     filename = str(filename)
     # report error if image does not exist
     if not os.path.exists(filename):
         self.showErrorMessage("""FITS image %s does not exist.""" %
                               filename)
         return None
     # see if image is already loaded
     if not duplicate:
         for ic in self._imagecons:
             if ic.getFilename() and os.path.samefile(
                     filename, ic.getFilename()):
                 if to_top:
                     self.raiseImage(ic)
                 if model:
                     self._model_imagecons.add(id(ic))
                 return ic
     # load the FITS image
     busy = BusyIndicator()
     dprint(2, "reading FITS image", filename)
     self.showMessage("""Reading FITS image %s""" % filename, 3000)
     QApplication.flush()
     try:
         image = SkyImage.FITSImagePlotItem(str(filename))
     except KeyboardInterrupt:
         raise
     except:
         busy = None
         traceback.print_exc()
         self.showErrorMessage(
             """<P>Error loading FITS image %s: %s. This may be due to a bug in Tigger; if the FITS file loads fine in another viewer,
       please send the FITS file, along with a copy of any error messages from the text console, to [email protected].</P>"""
             % (filename, str(sys.exc_info()[1])))
         return None
     # create control bar, add to widget stack
     ic = self._createImageController(image,
                                      "model source '%s'" %
                                      model if model else filename,
                                      model or image.name,
                                      model=model)
     self.showMessage("""Loaded FITS image %s""" % filename, 3000)
     dprint(2, "image loaded")
     return ic
Ejemplo n.º 55
0
 def quit(self):
     if self.shutdown():
         QApplication.instance().quit()
Ejemplo n.º 56
0
 def _loadClipboardPath(self):
     try:
         path = QApplication.clipboard().text(self._clipboard_mode)
     except:
         return
     self.loadImage(path)
Ejemplo n.º 57
0
 def copy(self, x):
     if self.selected_text:
         QApplication.clipboard().setText(self.selected_text)
Ejemplo n.º 58
0
Archivo: iqt.py Proyecto: gyenney/Tools
"""iqt

Provides control over PyQt and PyQwt widgets from the command line interpreter.
"""

# Import GNU readline, so that readline can do its work in Python scripts.
# _iqt falls back on a different method when there is no GNU readline.
try:
    import readline
except ImportError:
    pass

from PyQt4.Qt import QApplication, QCoreApplication, PYQT_VERSION

if QCoreApplication.instance() is None:
    _a = QApplication([])

if PYQT_VERSION < 0x40300:
    import _iqt

# Local Variables: ***
# mode: python ***
# End: ***
Ejemplo n.º 59
0
                        time.sleep(0.5)
            self.p.join()
        except AttributeError:
            pass
        if self.q.qsize() > 0:
            self.messageWidget.appendLog('i', 'The queue was not empty')
            print('Freeing up memory...')
            self.emptyQueue()

        # Save LOG.
        fn = self._session.Saving['filename_log']
        filename = '%s.log' % (fn)
        fileDir = self._session.Saving['directory']
        if not os.path.exists(fileDir):
            os.makedirs(fileDir)

        f = open(os.path.join(fileDir, filename), "a")
        for line in self.messageWidget.logText:
            f.write(line + '\n')
        f.flush()
        f.close()
        print('Saved LOG')
        super(cameraMain, self).closeEvent(evnt)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    cam = cameraMain()
    cam.show()
    sys.exit(app.exec_())
Ejemplo n.º 60
0
 def copy_to_clipboard(self):
     QApplication.clipboard().setText(self.text_results)