Example #1
0
def set_default_printer():
    from pytis.presentation import Field
    from pytis.form import Error, Text, InputForm, run_dialog, run_form
    try:
        import cups
        import cupshelpers
    except ImportError:
        run_dialog(
            Error,
            _("Default printer setup failed.\n"
              "CUPS Python interface not present.\n"
              "Please, contact the system administrator."))
        return None
    connection = cups.Connection()
    user_default = UserDefaultPrinter()
    default_printer = user_default.get()
    if not default_printer:
        default_printer = connection.getDefault()
    printers = cupshelpers.getPrinters(connection)
    result = run_form(
        InputForm,
        title=_("Printer Selection"),
        fields=(Field('printer',
                      "",
                      width=40,
                      not_null=True,
                      type=pytis.data.String,
                      enumerator=pytis.data.FixedEnumerator(
                          list(printers.keys())),
                      default=default_printer), ),
        layout=(Text(_("Choose the default printer:")), 'printer'),
    )
    if result:
        user_default.set(result['printer'].value())
    return None
Example #2
0
 def _run_formatter_process(self, stream, on_background=False, hook=None, file_=None):
     result = None
     try:
         if on_background:
             result = thread.start_new_thread(self._run_formatter, (stream,))
         else:
             result = self._run_formatter(stream, hook=hook, file_=file_)
     except lcg.SubstitutionIterator.NotStartedError:
         tbstring = pytis.util.format_traceback()
         pytis.util.log(pytis.util.OPERATIONAL, 'Print exception caught', tbstring)
         from pytis.form import run_dialog
         run_dialog(Error, _("Invalid use of identifier `data' in print specification.\n"
                             "Maybe use `current_row' instead?"))
     except UserBreakException:
         pass
     return result
Example #3
0
def run_viewer(file_):
    """Run PDF viewer on given file.

    Run it on a remote station if requested in configuration and the remote
    station is available.

    Arguments:

      file_ -- tempfile.NamedTemporaryFile instance

    """
    import subprocess
    file_name = file_.name
    viewer = config.postscript_viewer
    remote = (config.rpc_remote_view and pytis.remote.client_available())
    if remote:
        suffix = (os.path.splitext(file_name)[1] or '.pdf')
        try:
            remote_file = pytis.remote.make_temporary_file(suffix=suffix)
            if remote_file is None:
                remote = False
        except:
            remote = False
    if remote:
        try:
            f = open(file_name)
            while True:
                data = f.read(10000000)
                if not data:
                    break
                remote_file.write(data)
            f.close()
        finally:
            remote_file.close()
        pytis.remote.launch_file(remote_file.name())
    elif viewer:
        call_args = viewer.split()
        subprocess.call(call_args + [file_name])
    else:
        import mailcap
        match = mailcap.findmatch(mailcap.getcaps(), 'application/pdf')[1]
        if match:
            command = match['view'] % (file_name,)
            os.system(command)
        else:
            from pytis.form import run_dialog
            run_dialog(Error, _("No PDF viewer found."))
Example #4
0
def run_viewer(file_):
    """Run PDF viewer on given file.

    Run it on a remote station if requested in configuration and the remote
    station is available.

    Arguments:

      file_ -- tempfile.NamedTemporaryFile instance

    """
    import subprocess
    file_name = file_.name
    viewer = config.postscript_viewer
    remote = (config.rpc_remote_view and pytis.remote.client_available())
    if remote:
        suffix = (os.path.splitext(file_name)[1] or '.pdf')
        try:
            remote_file = pytis.remote.make_temporary_file(suffix=suffix)
            if remote_file is None:
                remote = False
        except:
            remote = False
    if remote:
        try:
            f = open(file_name)
            while True:
                data = f.read(10000000)
                if not data:
                    break
                remote_file.write(data)
            f.close()
        finally:
            remote_file.close()
        pytis.remote.launch_file(remote_file.name())
    elif viewer:
        call_args = viewer.split()
        subprocess.call(call_args + [file_name])
    else:
        import mailcap
        match = mailcap.findmatch(mailcap.getcaps(), 'application/pdf')[1]
        if match:
            command = match['view'] % (file_name, )
            os.system(command)
        else:
            from pytis.form import run_dialog
            run_dialog(Error, _("No PDF viewer found."))
Example #5
0
 def _reload_actions(self, record):
     import wiking
     def action_descr(module, action):
         if issubclass(module, wiking.PytisModule):
             for a in module.Spec.actions:
                 if a.name() == action:
                     return a.descr() or a.title()
         try:
             return dict(self._DEFAULT_ACTIONS)[action]
         except KeyError:
             method = getattr(module, 'action_' + action)
             docstring = method.__doc__
             return docstring and docstring.splitlines()[0] or _("Neuvedeno")
     module = self._module(record['modname'].value())
     if module:
         from pytis.form import run_dialog, CheckListDialog, create_data_object
         data = create_data_object(self._spec_name('Actions'))
         data.select(condition=pd.EQ('mod_id', record['mod_id']))
         existing_actions = {}
         while True:
             row = data.fetchone()
             if row is None:
                 break
             else:
                 existing_actions[row['name'].value()] = row['action_id']
         data.close()
         actions = [attr[7:] for attr in dir(module)
                    if attr.startswith('action_') and
                    isinstance(getattr(module, attr), collections.Callable)]
         default_actions = [a[0] for a in self._DEFAULT_ACTIONS]
         # Order default actions first and in the order of self._DEFAULT_ACTIONS.
         order = lambda a: a in default_actions and (default_actions.index(a) + 1) or a
         actions.sort(lambda a, b: cmp(order(a), order(b)))
         descriptions = [action_descr(module, action) for action in actions]
         result = run_dialog(CheckListDialog, title=_("Nalezené akce"),
                             message=_("Zaškrtněte akce, které chcete zpřístupnit webovým "
                                       "uživatelům:"),
                             items=zip([a in existing_actions for a in actions],
                                       actions, descriptions),
                             columns=(_("Action"), _("Description")))
         if result is not None:
             # TODO: Use a transaction.  Respect existing actions.
             for i, action in enumerate(actions):
                 if result[i]:
                     description_value = pd.Value(pd.String(), descriptions[i] or None)
                     try:
                         key = existing_actions[action]
                     except KeyError:
                         rowdata = [('mod_id', record['mod_id']),
                                    ('name', pd.Value(pd.String(), action)),
                                    ('description', description_value)]
                         data.insert(pd.Row(rowdata))
                     else:
                         data.update((key,), pd.Row((('description', description_value),)))
Example #6
0
 def _run_formatter_process(self,
                            stream,
                            on_background=False,
                            hook=None,
                            file_=None):
     result = None
     try:
         if on_background:
             result = thread.start_new_thread(self._run_formatter,
                                              (stream, ))
         else:
             result = self._run_formatter(stream, hook=hook, file_=file_)
     except lcg.SubstitutionIterator.NotStartedError:
         tbstring = pytis.util.format_traceback()
         pytis.util.log(pytis.util.OPERATIONAL, 'Print exception caught',
                        tbstring)
         from pytis.form import run_dialog
         run_dialog(
             Error,
             _("Invalid use of identifier `data' in print specification.\n"
               "Maybe use `current_row' instead?"))
     except UserBreakException:
         pass
     return result
Example #7
0
    def _reload_actions(self, record):
        import wiking

        def action_descr(module, action):
            if issubclass(module, wiking.PytisModule):
                for a in module.Spec.actions:
                    if a.name() == action:
                        return a.descr() or a.title()
            try:
                return dict(self._DEFAULT_ACTIONS)[action]
            except KeyError:
                method = getattr(module, 'action_' + action)
                docstring = method.__doc__
                return docstring and docstring.splitlines()[0] or _(
                    "Neuvedeno")

        module = self._module(record['modname'].value())
        if module:
            from pytis.form import run_dialog, CheckListDialog, create_data_object
            data = create_data_object(self._spec_name('Actions'))
            data.select(condition=pd.EQ('mod_id', record['mod_id']))
            existing_actions = {}
            while True:
                row = data.fetchone()
                if row is None:
                    break
                else:
                    existing_actions[row['name'].value()] = row['action_id']
            data.close()
            actions = [
                attr[7:] for attr in dir(module) if attr.startswith('action_')
                and isinstance(getattr(module, attr), collections.Callable)
            ]
            default_actions = [a[0] for a in self._DEFAULT_ACTIONS]
            # Order default actions first and in the order of self._DEFAULT_ACTIONS.
            order = lambda a: a in default_actions and (default_actions.index(
                a) + 1) or a
            actions.sort(lambda a, b: cmp(order(a), order(b)))
            descriptions = [action_descr(module, action) for action in actions]
            result = run_dialog(
                CheckListDialog,
                title=_("Nalezené akce"),
                message=_("Zaškrtněte akce, které chcete zpřístupnit webovým "
                          "uživatelům:"),
                items=zip([a in existing_actions for a in actions], actions,
                          descriptions),
                columns=(_("Action"), _("Description")))
            if result is not None:
                # TODO: Use a transaction.  Respect existing actions.
                for i, action in enumerate(actions):
                    if result[i]:
                        description_value = pd.Value(pd.String(),
                                                     descriptions[i] or None)
                        try:
                            key = existing_actions[action]
                        except KeyError:
                            rowdata = [('mod_id', record['mod_id']),
                                       ('name', pd.Value(pd.String(), action)),
                                       ('description', description_value)]
                            data.insert(pd.Row(rowdata))
                        else:
                            data.update(
                                (key, ),
                                pd.Row((('description', description_value), )))