コード例 #1
0
 def run(self, address):
     "run(address) -> (filename,address), all as strings"
     if address:
         self.address.set_text("%06X" % address)
     self.dialog.show_all()
     filename = None
     while 1:
         response = self.dialog.run()
         if response == gtk.RESPONSE_APPLY:
             filename = self.file.get_filename()
             address_txt = self.address.get_text()
             if filename and address_txt:
                 try:
                     address = int(address_txt, 16)
                 except ValueError:
                     ErrorDialog(
                         self.dialog).run("address needs to be in hex")
                     continue
                 break
             else:
                 ErrorDialog(self.dialog).run("please fill the field(s)")
         else:
             break
     self.dialog.hide()
     return (filename, address)
コード例 #2
0
 def run(self, address):
     "run(address) -> (filename,address,length), all as strings"
     if address:
         self.address.set_text("%06X" % address)
     self.dialog.show_all()
     filename = length = None
     while 1:
         response = self.dialog.run()
         if response == gtk.RESPONSE_APPLY:
             filename = self.file.get_filename()
             address_txt = self.address.get_text()
             length_txt = self.length.get_text()
             if filename and address_txt and length_txt:
                 try:
                     address = int(address_txt, 16)
                 except ValueError:
                     ErrorDialog(self.dialog).run("address needs to be in hex")
                     continue
                 try:
                     length = int(length_txt)
                 except ValueError:
                     ErrorDialog(self.dialog).run("length needs to be a number")
                     continue
                 if os.path.exists(filename):
                     question = "File:\n%s\nexists, replace?" % filename
                     if not AskDialog(self.dialog).run(question):
                         continue
                 break
             else:
                 ErrorDialog(self.dialog).run("please fill the field(s)")
         else:
             break
     self.dialog.hide()
     return (filename, address, length)
コード例 #3
0
    def __init__(self):
        # Hatari and configuration
        self.hatari = Hatari()
        error = self.hatari.is_compatible()
        if error:
            ErrorDialog(None).run(error)
            sys.exit(1)

        self.config = HatariConfigMapping(self.hatari)
        try:
            self.config.validate()
        except (KeyError, AttributeError):
            NoteDialog(None).run(
                "Hatari configuration validation failed!\nRetrying after saving Hatari configuration."
            )
            error = self.hatari.save_config()
            if error:
                ErrorDialog(None).run(
                    "Hatari configuration saving failed (code: %d), quitting!"
                    % error)
                sys.exit(error)
            self.config = HatariConfigMapping(self.hatari)
            try:
                self.config.validate()
            except (KeyError, AttributeError):
                ErrorDialog(None).run(
                    "Invalid Hatari configuration, quitting!")
                sys.exit(1)
        self.config.init_compat()

        # windows are created when needed
        self.mainwin = None
        self.hatariwin = None
        self.debugui = None
        self.panels = {}

        # dialogs are created when needed
        self.aboutdialog = None
        self.inputdialog = None
        self.tracedialog = None
        self.resetdialog = None
        self.quitdialog = None
        self.killdialog = None

        self.floppydialog = None
        self.harddiskdialog = None
        self.displaydialog = None
        self.joystickdialog = None
        self.machinedialog = None
        self.peripheraldialog = None
        self.sounddialog = None
        self.pathdialog = None

        # used by run()
        self.memstate = None
        self.floppy = None
        self.io_id = None

        # TODO: Hatari UI own configuration settings save/load
        self.tracepoints = None
コード例 #4
0
 def write(self, message, loggerName='log', logLevel='debug', showErrorDialog=True):
     message = str(message).strip()
     if message != '':
         logLevel = logLevel.lower()
         myLogger = logging.getLogger(loggerName)
         if logLevel == 'debug':
             myLogger.debug(message)
         elif logLevel == 'info':
             myLogger.info(message)
             self.rtobjectWrite(message)
         elif logLevel == 'warning':
             myLogger.warning(message)
             self.rtobjectWrite(message)
         elif logLevel == 'error':
             myLogger.error(message)
             self.rtobjectWrite(message)
             if showErrorDialog:
                 ErrorDialog('Error', message)
         elif logLevel == 'critical':
             myLogger.critical(message)
             self.rtobjectWrite(message)
             if showErrorDialog:
                 ErrorDialog('Critical', message)
         elif logLevel == 'exception':
             myLogger.exception(message)
             self.rtobjectWrite(message)
             if showErrorDialog:
                 ErrorDialog('Exception', message)
         # Flush now
         try:
             sys.stdout.flush()
         except:
             pass
コード例 #5
0
        def on_ok(widget, path_to_file):
            filesize = os.path.getsize(path_to_file)  # in bytes
            invalid_file = False
            msg = ''
            if os.path.isfile(path_to_file):
                stat = os.stat(path_to_file)
                if stat[6] == 0:
                    invalid_file = True
                    msg = _('File is empty')
            else:
                invalid_file = True
                msg = _('File does not exist')
            if filesize < 60000:
                img = urllib2.quote(
                    base64.standard_b64encode(open(path_to_file, "rb").read()),
                    '')
                if len(img) > 60000:
                    invalid_file = True
                    msg = _('File too big')
            else:
                invalid_file = True
                msg = _('File too big')
            if invalid_file:
                ErrorDialog(_('Could not load image'), msg)
                return

            dlg.destroy()
            msg = 'HTML image'
            extension = os.path.splitext(os.path.split(path_to_file)[1])[1] \
                .lower()[1:]
            xhtml = '<body><br/> <img alt="img" src="data:image/%s;base64,%s"/> \
                    </body>' % (extension, img)
            self.chat_control.send_message(message=msg, xhtml=xhtml)
            self.chat_control.msg_textview.grab_focus()
コード例 #6
0
def uncaught_excepthook(*args):
    sys.__excepthook__(*args)
    if __debug__:
        from pprint import pprint
        from types import BuiltinFunctionType, ClassType, ModuleType, TypeType
        tb = sys.last_traceback
        while tb.tb_next: tb = tb.tb_next
        print('\nDumping locals() ...')
        pprint({k:v for k,v in tb.tb_frame.f_locals.items()
                    if not k.startswith('_') and
                       not isinstance(v, (BuiltinFunctionType,
                                          ClassType, ModuleType, TypeType))})
        if sys.stdin.isatty() and (sys.stdout.isatty() or sys.stderr.isatty()):
            try:
                import ipdb as pdb  # try to import the IPython debugger
            except ImportError:
                import pdb as pdb
            print '\nStarting interactive debug prompt ...'
            pdb.pm()
    else:
        import traceback
        from dialogs import ErrorDialog
        ErrorDialog(_('Unexpected error'),
                    '<b>%s</b>' % _("The installer failed with the following error."),
                    '<tt>' + '\n'.join(traceback.format_exception(*args)) + '</tt>')
    sys.exit(1)
コード例 #7
0
 def _entry_cb(self, widget):
     try:
         address = int(widget.get_text(), 16)
     except ValueError:
         ErrorDialog(widget.get_toplevel()).run("invalid address")
         return
     self.dump(address)
コード例 #8
0
ファイル: main.py プロジェクト: wroldwiedbwe/solydxk-system
def uncaught_excepthook(*args):
    sys.__excepthook__(*args)
    if __debug__:
        from pprint import pprint
        from types import BuiltinFunctionType, ClassType, ModuleType, TypeType
        tb = sys.last_traceback
        while tb.tb_next:
            tb = tb.tb_next
        print(('\nDumping locals() ...'))
        pprint({
            k: v
            for k, v in tb.tb_frame.f_locals.items()
            if not k.startswith('_') and not isinstance(
                v, (BuiltinFunctionType, ClassType, ModuleType, TypeType))
        })
        if sys.stdin.isatty() and (sys.stdout.isatty() or sys.stderr.isatty()):
            try:
                import ipdb as pdb  # try to import the IPython debugger
            except ImportError:
                import pdb as pdb
            print(('\nStarting interactive debug prompt ...'))
            pdb.pm()
    else:
        import traceback
        details = '\n'.join(traceback.format_exception(*args)).replace(
            '<', '').replace('>', '')
        title = _('Unexpected error')
        msg = _(
            'SolydXK System Settings has failed with the following unexpected error. Please submit a bug report!'
        )
        ErrorDialog(title, "<b>%s</b>" % msg, "<tt>%s</tt>" % details, None,
                    True, 'solydxk')

    sys.exit(1)
コード例 #9
0
 def uploader():
     progress_messages.put(_('Uploading file via HTTP...'))
     try:
         headers = {
             'User-Agent': 'Gajim %s' % gajim.version,
             'Content-Type': mime_type
         }
         request = urllib2.Request(put.getData().encode("utf-8"),
                                   data=data,
                                   headers=headers)
         request.get_method = lambda: 'PUT'
         log.debug("opening urllib2 upload request...")
         transfer = urllib2.urlopen(request, timeout=30)
         log.debug("urllib2 upload request done, response code: " +
                   str(transfer.getcode()))
         return transfer.getcode()
     except UploadAbortedException:
         log.info("Upload aborted")
     except:
         progress_window.close_dialog()
         ErrorDialog(
             _('Could not upload file'),
             _('Got unexpected exception while uploading file (see error log for more information)'
               ),
             transient_for=self.chat_control.parent_win.window)
         raise  # fill error log with useful information
     return 0
コード例 #10
0
 def view_url(self, url, name):
     """view given URL or file path, or error use 'name' as its name"""
     if self._view and "://" in url or os.path.exists(url):
         print("RUN: '%s' '%s'" % (self._view, url))
         os.spawnlp(os.P_NOWAIT, self._view, self._view, url)
         return
     if not self._view:
         msg = "Cannot view %s, HTML viewer missing" % name
     else:
         msg = "Cannot view %s,\n'%s' file is missing" % (name, url)
     from dialogs import ErrorDialog
     ErrorDialog(self.mainwin).run(msg)
コード例 #11
0
    def on_rename_item(self, widget):
        model, iter = self.get_selection().get_selected()
        filepath = model.get_value(iter, DIR_PATH)

        if filepath != self.dir:
            model.set_value(iter, DIR_EDITABLE, True)

            column = self.get_column(0)
            path = self.model.get_path(iter)
            self.set_cursor(path, focus_column=column, start_editing=True)
        else:
            ErrorDialog(_("Can't rename the root folder")).launch()
コード例 #12
0
    def on_cellrenderer_edited(self, cellrenderertext, path, new_text):
        iter = self.model.get_iter_from_string(path)
        filepath = self.model.get_value(iter, DIR_PATH)
        old_text = self.model.get_value(iter, DIR_TITLE)

        if old_text == new_text or new_text not in os.listdir(
                os.path.dirname(filepath)):
            newpath = os.path.join(os.path.dirname(filepath), new_text)
            os.rename(filepath, newpath)
            self.model.set(iter, DIR_TITLE, new_text, DIR_PATH, newpath,
                           DIR_EDITABLE, False)
        else:
            ErrorDialog(_("Can't rename!\n\nThere are files in it!")).launch()
コード例 #13
0
    def _on_plugin_toggled(self, cell, path, model):
        new_state = not model[path][0]
        path = int(path)
        plugin_name = self._plugins[path]['NAME']

        plugin_mgr = mesk.plugin.get_manager()
        state_str = ''
        try:
            if new_state:
                state_str = _('Plugin activation error')
                plugin_mgr.activate_plugin(plugin_name)
            else:
                state_str = _('Plugin deactivation error')
                plugin_mgr.deactivate_plugin(plugin_name)
            # Update model
            model[path][0] = new_state
        except Exception, ex:
            d = ErrorDialog(self.window)
            d.set_markup('<b>%s</b>' % state_str)
            d.format_secondary_text(str(ex))
            d.run()
            d.destroy()
コード例 #14
0
    def exec_command(self, command):
        try:
            # Run the command in a separate thread
            self.set_buttons_state(False)
            name = 'cmd'
            t = ExecuteThreadedCommands([command], self.queue)
            self.threads[name] = t
            t.daemon = True
            t.start()
            self.queue.join()
            GObject.timeout_add(1000, self.check_thread, name)

        except Exception as detail:
            ErrorDialog(self.btnExecute.get_label(), detail)
コード例 #15
0
            def show_error():
                import traceback
                msg = _('Playlist export failed: %s') % str(ex)
                mesk.log.error("%s\n%s" % (msg, traceback.format_exc()))

                from dialogs import ErrorDialog
                d = ErrorDialog(self.dialog, markup='<b>%s</b>' % msg)
                d.run()
                d.destroy()
コード例 #16
0
 def show_message(self, cmdOutput):
     try:
         self.log.write("Command output: {}".format(cmdOutput),
                        'show_message')
         ret = int(cmdOutput)
         if ret > 1 and ret != 255:
             if ret == 1:
                 ErrorDialog(self.btnSave.get_label(), _("Run as root."))
             elif ret == 2:
                 ErrorDialog(self.btnSave.get_label(),
                             _("Wrong arguments passed to ddm."))
             elif ret == 3:
                 ErrorDialog(self.btnSave.get_label(),
                             _("There are no driver available."))
             elif ret == 4:
                 ErrorDialog(self.btnSave.get_label(),
                             _("The driver cannot be found in repository."))
             elif ret == 5:
                 ErrorDialog(
                     self.btnSave.get_label(),
                     _("Download error.\nCheck your internet connection."))
             elif ret == 6:
                 ErrorDialog(self.btnSave.get_label(),
                             _("DDM cannot purge the driver."))
             elif ret == 7:
                 ErrorDialog(self.btnSave.get_label(),
                             _("This card is not supported."))
             else:
                 msg = _(
                     "There was an error during the installation.\n"
                     "Please, run 'sudo apt-get -f install' in a terminal.\n"
                     "Visit our forum for support: http://forums.solydxk.com"
                 )
                 ErrorDialog(self.btnSave.get_label(), msg)
         else:
             msg = _("The software has been successfully installed.")
             msg_restart = _("You will need to restart your system.")
             MessageDialog(self.btnSave.get_label(),
                           "{}\n\n{}".format(msg, msg_restart))
     except:
         ErrorDialog(self.btnSave.get_label(), cmdOutput)
コード例 #17
0
    def on_delete_item(self, widget):
        model, iter = self.get_selection().get_selected()
        if not iter:
            return
        filepath = model.get_value(iter, DIR_PATH)

        if filepath != self.dir:
            if os.path.isdir(filepath):
                shutil.rmtree(filepath)
            else:
                os.remove(filepath)

            self.emit('deleted')
            self.update_model()
        else:
            ErrorDialog(_("Can't delete the root folder")).launch()
コード例 #18
0
 def load_options(self):
     # TODO: move config to MemoryAddress class?
     # (depends on how monitoring of addresses should work)
     lines = self.address.get_lines()
     follow_pc = self.address.get_follow_pc()
     miss_is_error = False  # needed for adding windows
     defaults = {"[General]": {"nLines": lines, "bFollowPC": follow_pc}}
     userconfdir = ".hatari"
     config = ConfigStore(userconfdir, defaults, miss_is_error)
     configpath = config.get_filepath("debugui.cfg")
     config.load(configpath)  # set defaults
     try:
         self.address.set_lines(config.get("[General]", "nLines"))
         self.address.set_follow_pc(config.get("[General]", "bFollowPC"))
     except (KeyError, AttributeError):
         ErrorDialog(None).run(
             "Debug UI configuration mismatch!\nTry again after removing: '%s'."
             % configpath)
     self.config = config
コード例 #19
0
    def on_button_ok_clicked(self, widget):
        # Collect data
        format_as = self.cmb_use_as_handler.getValue()
        mount_as = self.cmb_mount_point_handler.getValue()
        encrypt = self.go("chk_encryption").get_active()
        enc_passphrase1 = self.go("entry_encpass1").get_text().strip()
        enc_passphrase2 = self.go("entry_encpass2").get_text().strip()
        label = self.txt_label.get_text().strip()

        # Check user input
        if encrypt:
            errorFound = False
            if enc_passphrase1 == "":
                errorFound = True
                errorMessage = _("Please provide an encryption password.")
            elif enc_passphrase1 != enc_passphrase2:
                errorFound = True
                errorMessage = _("Your encryption passwords do not match.")
            elif not format_as:
                errorFound = True
                errorMessage = "{} {}".format(
                    _("You need to choose a format type\n"
                      "for your encrypted partition (default: ext4):"),
                    self.partition.path)
                self.cmb_use_as_handler.selectValue('ext4')
            if not mount_as:
                errorFound = True
                errorMessage = "{} {}".format(
                    _("You need to choose a mount point for partition:"),
                    self.partition.path)

            if errorFound:
                ErrorDialog(_("Encryption"), errorMessage)
                return True
        else:
            # For good measure
            enc_passphrase1 = ''

        # Save the settings and close the window
        assign_mount_point(self.partition, mount_as, format_as, encrypt,
                           enc_passphrase1, label)
        self.window.hide()
コード例 #20
0
    def add_bookmark_button_clicked(self, widget):
        """
        Bookmark the room, without autojoin and not minimized
        """
        from dialogs import ErrorDialog, InformationDialog
        password = gajim.gc_passwords.get(self.gc_control.room_jid, '')
        account = self.gc_control.account

        bm = {'name': self.gc_control.name,
              'jid': self.gc_control.room_jid,
              'autojoin': 0,
              'minimize': 0,
              'password': password,
              'nick': self.gc_control.nick}

        place_found = False
        index = 0
        # check for duplicate entry and respect alpha order
        for bookmark in gajim.connections[account].bookmarks:
            if bookmark['jid'] == bm['jid']:
                ErrorDialog(
                    _('Bookmark already set'),
                    _('Group Chat "%s" is already in your bookmarks.') % \
                    bm['jid'])
                return
            if bookmark['name'] > bm['name']:
                place_found = True
                break
            index += 1
        if place_found:
            gajim.connections[account].bookmarks.insert(index, bm)
        else:
            gajim.connections[account].bookmarks.append(bm)
        self.plugin.save_bookmarks(account, gajim.connections[account].bookmarks)
        gajim.interface.roster.set_actions_menu_needs_rebuild()
        InformationDialog(
            _('Bookmark has been added successfully'),
            _('You can manage your bookmarks via Actions menu in your roster.'))
コード例 #21
0
ファイル: debugui.py プロジェクト: hatari/hatari
 def load_options(self):
     # TODO: move config to MemoryAddress class?
     # (depends on how monitoring of addresses should work)
     lines = self.address.get_lines()
     # ConfigStore does checks and type conversions based on names
     # of Hatari config sections and keys, so this needs to use
     # same names to avoid asserts, and it can't e.g. save
     # follow_pc option value, which will keep as run-time one
     defaults = {
         "[Debugger]": {
             "nDisasmLines": lines,
         }
     }
     userconfdir = ".hatari"
     config = ConfigStore(userconfdir, defaults)
     configpath = config.get_filepath(".debugui.cfg")
     config.load(configpath)  # set defaults
     try:
         self.address.set_lines(config.get("[Debugger]", "nDisasmLines"))
     except (KeyError, AttributeError):
         ErrorDialog(None).run(
             "Debug UI configuration mismatch!\nTry again after removing: '%s'."
             % configpath)
     self.config = config
コード例 #22
0
    def on_unhandled_exception(self, type, value, tb):
        """Called if an unhandled exception occurres. Shows the exception in
        an error dialog and prints the stack trace to stderr."""
        try:
            list = traceback.format_tb(tb, None) + \
                    traceback.format_exception_only(type, value)
            tracelog = '\nTraceback (most recent call last):\n' + "%-20s%s" % \
                    ("".join(list[:-1]), list[-1])

            message = "An internal program error has occurred."
            message += "\n" + tracelog

            gtk.gdk.threads_enter()
            ed = ErrorDialog(_("Unhandled exception"), message)
            ed.run()
            ed.destroy()
            gtk.gdk.threads_leave()

            sys.stderr.write(message)
        except:
            traceback.print_exc()
コード例 #23
0
ファイル: file_decryption.py プロジェクト: sepsemi/dotfiles
 def error(self, error):
     ErrorDialog(_('Error'),
                 error,
                 transient_for=self.chat_control.parent_win.window)
     return False
コード例 #24
0
            def upload_complete(response_code):
                if response_code == 0:
                    return      # Upload was aborted
                if response_code >= 200 and response_code < 300:
                    log.info("Upload completed successfully")
                    xhtml = None
                    is_image = mime_type.split('/', 1)[0] == 'image'
                    if (not isinstance(self.chat_control, chat_control.ChatControl) or not self.chat_control.gpg_is_active) and \
                        self.dialog_type == 'image' and is_image and not self.encrypted_upload:

                        progress_messages.put(_('Calculating (possible) image thumbnail...'))
                        thumb = None
                        quality_steps = (100, 80, 60, 50, 40, 35, 30, 25, 23, 20, 18, 15, 13, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
                        with open(path_to_file, 'rb') as content_file:
                            thumb = urllib2.quote(base64.standard_b64encode(content_file.read()), '')
                        if thumb and len(thumb) < max_thumbnail_size:
                            quality = 100
                            log.info("Image small enough (%d bytes), not resampling" % len(thumb))
                        elif pil_available:
                            log.info("PIL available, using it for image downsampling")
                            try:
                                for quality in quality_steps:
                                    thumb = Image.open(path_to_file)
                                    thumb.thumbnail((max_thumbnail_dimension, max_thumbnail_dimension), Image.ANTIALIAS)
                                    output = BytesIO()
                                    thumb.save(output, format='JPEG', quality=quality, optimize=True)
                                    thumb = output.getvalue()
                                    output.close()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("pil thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                        else:
                            thumb = None
                        if not thumb:
                            log.info("PIL not available, using GTK for image downsampling")
                            temp_file = None
                            try:
                                with open(path_to_file, 'rb') as content_file:
                                    thumb = content_file.read()
                                loader = gtk.gdk.PixbufLoader()
                                loader.write(thumb)
                                loader.close()
                                pixbuf = loader.get_pixbuf()
                                scaled_pb = self.get_pixbuf_of_size(pixbuf, max_thumbnail_dimension)
                                handle, temp_file = tempfile.mkstemp(suffix='.jpeg', prefix='gajim_httpupload_scaled_tmp', dir=gajim.TMP)
                                log.debug("Saving temporary jpeg image to '%s'..." % temp_file)
                                os.close(handle)
                                for quality in quality_steps:
                                    scaled_pb.save(temp_file, "jpeg", {"quality": str(quality)})
                                    with open(temp_file, 'rb') as content_file:
                                        thumb = content_file.read()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("gtk thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                            finally:
                                if temp_file:
                                    os.unlink(temp_file)
                        if thumb:
                            if len(thumb) > max_thumbnail_size:
                                log.info("Couldn't compress image enough, not sending any thumbnail")
                            else:
                                log.info("Using thumbnail jpeg quality %d (image size: %d bytes)" % (quality, len(thumb)))
                                xhtml = '<body><br/><a href="%s"> <img alt="%s" src="data:image/png;base64,%s"/> </a></body>' % \
                                    (get.getData(), get.getData(), thumb)
                    progress_window.close_dialog()
                    id_ = gajim.get_an_id()
                    def add_oob_tag():
                        pass
                    if self.encrypted_upload:
                        keyAndIv = '#' + binascii.hexlify(iv) + binascii.hexlify(key)
                        self.chat_control.send_message(message=get.getData() + keyAndIv, xhtml=None)
                    else:
                        self.chat_control.send_message(message=get.getData(), xhtml=xhtml)
                    self.chat_control.msg_textview.grab_focus()
                else:
                    progress_window.close_dialog()
                    log.error("got unexpected http upload response code: " + str(response_code))
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected http response code from server: ') + str(response_code),
                                transient_for=self.chat_control.parent_win.window)
コード例 #25
0
        def upload_file(stanza):
            slot = stanza.getTag("slot")
            if not slot:
                progress_window.close_dialog()
                log.error("got unexpected stanza: "+str(stanza))
                error = stanza.getTag("error")
                if error and error.getTag("text"):
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server: %s') % str(error.getTagData("text")),
                                transient_for=self.chat_control.parent_win.window)
                else:
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server (protocol mismatch??)'),
                                transient_for=self.chat_control.parent_win.window)
                return

            try:
                if self.encrypted_upload:
                    key = os.urandom(32)
                    iv = os.urandom(16)
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress,
                                                  self.encrypted_upload, key, iv)
                else:
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress)
            except:
                progress_window.close_dialog()
                ErrorDialog(_('Could not open file'), 
                            _('Exception raised while opening file (see error log for more information)'),
                            transient_for=self.chat_control.parent_win.window)
                raise       # fill error log with useful information

            put = slot.getTag("put")
            get = slot.getTag("get")
            if not put or not get:
                progress_window.close_dialog()
                log.error("got unexpected stanza: " + str(stanza))
                ErrorDialog(_('Could not request upload slot'), 
                            _('Got unexpected response from server (protocol mismatch??)'),
                            transient_for=self.chat_control.parent_win.window)
                return

            def upload_complete(response_code):
                if response_code == 0:
                    return      # Upload was aborted
                if response_code >= 200 and response_code < 300:
                    log.info("Upload completed successfully")
                    xhtml = None
                    is_image = mime_type.split('/', 1)[0] == 'image'
                    if (not isinstance(self.chat_control, chat_control.ChatControl) or not self.chat_control.gpg_is_active) and \
                        self.dialog_type == 'image' and is_image and not self.encrypted_upload:

                        progress_messages.put(_('Calculating (possible) image thumbnail...'))
                        thumb = None
                        quality_steps = (100, 80, 60, 50, 40, 35, 30, 25, 23, 20, 18, 15, 13, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
                        with open(path_to_file, 'rb') as content_file:
                            thumb = urllib2.quote(base64.standard_b64encode(content_file.read()), '')
                        if thumb and len(thumb) < max_thumbnail_size:
                            quality = 100
                            log.info("Image small enough (%d bytes), not resampling" % len(thumb))
                        elif pil_available:
                            log.info("PIL available, using it for image downsampling")
                            try:
                                for quality in quality_steps:
                                    thumb = Image.open(path_to_file)
                                    thumb.thumbnail((max_thumbnail_dimension, max_thumbnail_dimension), Image.ANTIALIAS)
                                    output = BytesIO()
                                    thumb.save(output, format='JPEG', quality=quality, optimize=True)
                                    thumb = output.getvalue()
                                    output.close()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("pil thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                        else:
                            thumb = None
                        if not thumb:
                            log.info("PIL not available, using GTK for image downsampling")
                            temp_file = None
                            try:
                                with open(path_to_file, 'rb') as content_file:
                                    thumb = content_file.read()
                                loader = gtk.gdk.PixbufLoader()
                                loader.write(thumb)
                                loader.close()
                                pixbuf = loader.get_pixbuf()
                                scaled_pb = self.get_pixbuf_of_size(pixbuf, max_thumbnail_dimension)
                                handle, temp_file = tempfile.mkstemp(suffix='.jpeg', prefix='gajim_httpupload_scaled_tmp', dir=gajim.TMP)
                                log.debug("Saving temporary jpeg image to '%s'..." % temp_file)
                                os.close(handle)
                                for quality in quality_steps:
                                    scaled_pb.save(temp_file, "jpeg", {"quality": str(quality)})
                                    with open(temp_file, 'rb') as content_file:
                                        thumb = content_file.read()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("gtk thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                            finally:
                                if temp_file:
                                    os.unlink(temp_file)
                        if thumb:
                            if len(thumb) > max_thumbnail_size:
                                log.info("Couldn't compress image enough, not sending any thumbnail")
                            else:
                                log.info("Using thumbnail jpeg quality %d (image size: %d bytes)" % (quality, len(thumb)))
                                xhtml = '<body><br/><a href="%s"> <img alt="%s" src="data:image/png;base64,%s"/> </a></body>' % \
                                    (get.getData(), get.getData(), thumb)
                    progress_window.close_dialog()
                    id_ = gajim.get_an_id()
                    def add_oob_tag():
                        pass
                    if self.encrypted_upload:
                        keyAndIv = '#' + binascii.hexlify(iv) + binascii.hexlify(key)
                        self.chat_control.send_message(message=get.getData() + keyAndIv, xhtml=None)
                    else:
                        self.chat_control.send_message(message=get.getData(), xhtml=xhtml)
                    self.chat_control.msg_textview.grab_focus()
                else:
                    progress_window.close_dialog()
                    log.error("got unexpected http upload response code: " + str(response_code))
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected http response code from server: ') + str(response_code),
                                transient_for=self.chat_control.parent_win.window)
            
            def uploader():
                progress_messages.put(_('Uploading file via HTTP...'))
                try:
                    headers = {'User-Agent': 'Gajim %s' % gajim.version,
                               'Content-Type': mime_type}
                    request = urllib2.Request(put.getData().encode("utf-8"), data=data, headers=headers)
                    request.get_method = lambda: 'PUT'
                    log.debug("opening urllib2 upload request...")
                    transfer = urllib2.urlopen(request, timeout=30)
                    log.debug("urllib2 upload request done, response code: " + str(transfer.getcode()))
                    return transfer.getcode()
                except UploadAbortedException:
                    log.info("Upload aborted")
                except:
                    progress_window.close_dialog()
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected exception while uploading file (see error log for more information)'),
                                transient_for=self.chat_control.parent_win.window)
                    raise       # fill error log with useful information
                return 0

            log.info("Uploading file to '%s'..." % str(put.getData()))
            log.info("Please download from '%s' later..." % str(get.getData()))

            gajim.thread_interface(uploader, [], upload_complete)
コード例 #26
0
    def on_file_dialog_ok(self, widget, path_to_file=None):
        global jid_to_servers

        try:
            self.encrypted_upload = self.encryption_activated()
        except Exception as e:
            log.debug(e)
            self.encrypted_upload = False

        if not path_to_file:
            path_to_file = self.dlg.get_filename()
            if not path_to_file:
                self.dlg.destroy()
                return
            path_to_file = gtkgui_helpers.decode_filechooser_file_paths(
                    (path_to_file,))[0]
        self.dlg.destroy()
        if not os.path.exists(path_to_file):
            return
        if self.encrypted_upload:
            filesize = os.path.getsize(path_to_file) + TAGSIZE  # in bytes
        else:
            filesize = os.path.getsize(path_to_file)
        invalid_file = False
        msg = ''
        if os.path.isfile(path_to_file):
            stat = os.stat(path_to_file)
            if stat[6] == 0:
                invalid_file = True
                msg = _('File is empty')
        else:
            invalid_file = True
            msg = _('File does not exist')
        if invalid_file:
            ErrorDialog(_('Could not open file'), msg, transient_for=self.chat_control.parent_win.window)
            return

        mime_type = mimetypes.MimeTypes().guess_type(path_to_file)[0]
        if not mime_type:
            mime_type = 'application/octet-stream'  # fallback mime type
        log.info("Detected MIME Type of file: " + str(mime_type))
        progress_messages = Queue(8)
        progress_window = ProgressWindow(_('HTTP Upload'), _('Requesting HTTP Upload Slot...'), progress_messages, self.plugin)
        def upload_file(stanza):
            slot = stanza.getTag("slot")
            if not slot:
                progress_window.close_dialog()
                log.error("got unexpected stanza: "+str(stanza))
                error = stanza.getTag("error")
                if error and error.getTag("text"):
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server: %s') % str(error.getTagData("text")),
                                transient_for=self.chat_control.parent_win.window)
                else:
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server (protocol mismatch??)'),
                                transient_for=self.chat_control.parent_win.window)
                return

            try:
                if self.encrypted_upload:
                    key = os.urandom(32)
                    iv = os.urandom(16)
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress,
                                                  self.encrypted_upload, key, iv)
                else:
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress)
            except:
                progress_window.close_dialog()
                ErrorDialog(_('Could not open file'), 
                            _('Exception raised while opening file (see error log for more information)'),
                            transient_for=self.chat_control.parent_win.window)
                raise       # fill error log with useful information

            put = slot.getTag("put")
            get = slot.getTag("get")
            if not put or not get:
                progress_window.close_dialog()
                log.error("got unexpected stanza: " + str(stanza))
                ErrorDialog(_('Could not request upload slot'), 
                            _('Got unexpected response from server (protocol mismatch??)'),
                            transient_for=self.chat_control.parent_win.window)
                return

            def upload_complete(response_code):
                if response_code == 0:
                    return      # Upload was aborted
                if response_code >= 200 and response_code < 300:
                    log.info("Upload completed successfully")
                    xhtml = None
                    is_image = mime_type.split('/', 1)[0] == 'image'
                    if (not isinstance(self.chat_control, chat_control.ChatControl) or not self.chat_control.gpg_is_active) and \
                        self.dialog_type == 'image' and is_image and not self.encrypted_upload:

                        progress_messages.put(_('Calculating (possible) image thumbnail...'))
                        thumb = None
                        quality_steps = (100, 80, 60, 50, 40, 35, 30, 25, 23, 20, 18, 15, 13, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
                        with open(path_to_file, 'rb') as content_file:
                            thumb = urllib2.quote(base64.standard_b64encode(content_file.read()), '')
                        if thumb and len(thumb) < max_thumbnail_size:
                            quality = 100
                            log.info("Image small enough (%d bytes), not resampling" % len(thumb))
                        elif pil_available:
                            log.info("PIL available, using it for image downsampling")
                            try:
                                for quality in quality_steps:
                                    thumb = Image.open(path_to_file)
                                    thumb.thumbnail((max_thumbnail_dimension, max_thumbnail_dimension), Image.ANTIALIAS)
                                    output = BytesIO()
                                    thumb.save(output, format='JPEG', quality=quality, optimize=True)
                                    thumb = output.getvalue()
                                    output.close()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("pil thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                        else:
                            thumb = None
                        if not thumb:
                            log.info("PIL not available, using GTK for image downsampling")
                            temp_file = None
                            try:
                                with open(path_to_file, 'rb') as content_file:
                                    thumb = content_file.read()
                                loader = gtk.gdk.PixbufLoader()
                                loader.write(thumb)
                                loader.close()
                                pixbuf = loader.get_pixbuf()
                                scaled_pb = self.get_pixbuf_of_size(pixbuf, max_thumbnail_dimension)
                                handle, temp_file = tempfile.mkstemp(suffix='.jpeg', prefix='gajim_httpupload_scaled_tmp', dir=gajim.TMP)
                                log.debug("Saving temporary jpeg image to '%s'..." % temp_file)
                                os.close(handle)
                                for quality in quality_steps:
                                    scaled_pb.save(temp_file, "jpeg", {"quality": str(quality)})
                                    with open(temp_file, 'rb') as content_file:
                                        thumb = content_file.read()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("gtk thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                            finally:
                                if temp_file:
                                    os.unlink(temp_file)
                        if thumb:
                            if len(thumb) > max_thumbnail_size:
                                log.info("Couldn't compress image enough, not sending any thumbnail")
                            else:
                                log.info("Using thumbnail jpeg quality %d (image size: %d bytes)" % (quality, len(thumb)))
                                xhtml = '<body><br/><a href="%s"> <img alt="%s" src="data:image/png;base64,%s"/> </a></body>' % \
                                    (get.getData(), get.getData(), thumb)
                    progress_window.close_dialog()
                    id_ = gajim.get_an_id()
                    def add_oob_tag():
                        pass
                    if self.encrypted_upload:
                        keyAndIv = '#' + binascii.hexlify(iv) + binascii.hexlify(key)
                        self.chat_control.send_message(message=get.getData() + keyAndIv, xhtml=None)
                    else:
                        self.chat_control.send_message(message=get.getData(), xhtml=xhtml)
                    self.chat_control.msg_textview.grab_focus()
                else:
                    progress_window.close_dialog()
                    log.error("got unexpected http upload response code: " + str(response_code))
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected http response code from server: ') + str(response_code),
                                transient_for=self.chat_control.parent_win.window)
            
            def uploader():
                progress_messages.put(_('Uploading file via HTTP...'))
                try:
                    headers = {'User-Agent': 'Gajim %s' % gajim.version,
                               'Content-Type': mime_type}
                    request = urllib2.Request(put.getData().encode("utf-8"), data=data, headers=headers)
                    request.get_method = lambda: 'PUT'
                    log.debug("opening urllib2 upload request...")
                    transfer = urllib2.urlopen(request, timeout=30)
                    log.debug("urllib2 upload request done, response code: " + str(transfer.getcode()))
                    return transfer.getcode()
                except UploadAbortedException:
                    log.info("Upload aborted")
                except:
                    progress_window.close_dialog()
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected exception while uploading file (see error log for more information)'),
                                transient_for=self.chat_control.parent_win.window)
                    raise       # fill error log with useful information
                return 0

            log.info("Uploading file to '%s'..." % str(put.getData()))
            log.info("Please download from '%s' later..." % str(get.getData()))

            gajim.thread_interface(uploader, [], upload_complete)

        is_supported = gajim.get_jid_from_account(self.chat_control.account) in jid_to_servers and \
                    gajim.connections[self.chat_control.account].connection != None
        log.info("jid_to_servers of %s: %s ; connection: %s" % (gajim.get_jid_from_account(self.chat_control.account), str(jid_to_servers[gajim.get_jid_from_account(self.chat_control.account)]), str(gajim.connections[self.chat_control.account].connection)))
        if not is_supported:
            progress_window.close_dialog()
            log.error("upload component vanished, account got disconnected??")
            ErrorDialog(_('Your server does not support http uploads or you just got disconnected.\nPlease try to reconnect or reopen the chat window to fix this.'),
                transient_for=self.chat_control.parent_win.window)
            return

        # create iq for slot request
        id_ = gajim.get_an_id()
        iq = nbxmpp.Iq(
            typ='get',
            to=jid_to_servers[gajim.get_jid_from_account(self.chat_control.account)],
            queryNS=None
        )
        iq.setID(id_)
        request = iq.addChild(
            name="request",
            namespace=NS_HTTPUPLOAD
        )
        filename = request.addChild(
            name="filename",
        )
        filename.addData(os.path.basename(path_to_file))
        size = request.addChild(
            name="size",
        )
        size.addData(filesize)
        content_type = request.addChild(
            name="content-type",
        )
        content_type.addData(mime_type)

        # send slot request and register callback
        log.debug("sending httpupload slot request iq...")
        iq_ids_to_callbacks[str(id_)] = upload_file
        gajim.connections[self.chat_control.account].connection.send(iq)

        self.chat_control.msg_textview.grab_focus()
コード例 #27
0
def show_message(*args):
    from dialogs import ErrorDialog
    title = 'Daemon start failed'
    message = ('Youker Assisant systemdaemon didn\'t start correctly.\n'
                'If you want to help developers debugging, try to run "<b>sudo /usr/lib/python2.7/dist-packages/youker-assistant-daemon/src/start_systemdbus.py</b>" in a terminal.')
    ErrorDialog(title=title, message=message).launch()
コード例 #28
0
 def show_message(self, cmdOutput):
     try:
         self.log.write("Command output: {}".format(cmdOutput),
                        'show_message')
         ret = int(cmdOutput)
         if ret > 1 and ret != 255:
             if ret == 1:
                 ErrorDialog(
                     self.btnExecute.get_label(),
                     _("Run this application with root permission."))
             elif ret == 2:
                 ErrorDialog(
                     self.btnExecute.get_label(),
                     _("Wrong arguments were passed to usb-creator."))
             elif ret == 3:
                 ErrorDialog(
                     self.btnExecute.get_label(),
                     _("The device was not found or no device was given."))
             elif ret == 4:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("Given ISO path was not found."))
             elif ret == 5:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("Device is in use by another application."))
             elif ret == 6:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("Unable to mount the device."))
             elif ret == 7:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("Hash mismatch."))
             elif ret == 8:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("The device has no fat32 partition."))
             elif ret == 9:
                 ErrorDialog(self.btnExecute.get_label(),
                             _("The device has no bootloader installed."))
             elif ret == 10:
                 ErrorDialog(
                     self.btnExecute.get_label(),
                     _("There is not enough space available on the device.")
                 )
             elif ret == 11:
                 ErrorDialog(
                     self.btnExecute.get_label(),
                     _("Unable to guess distribution from ISO name.\n"
                       "Make sure you have the distribution name in the ISO name."
                       ))
             else:
                 msg = _(
                     "An unknown error accured.\n"
                     "Please, visit our forum for support: http://forums.solydxk.com"
                 )
                 ErrorDialog(self.window.get_title(), msg)
         else:
             msg = _("The USB was successfully written.")
             MessageDialog(self.window.get_title(), msg)
     except:
         ErrorDialog(self.btnExecute.get_label(), cmdOutput)