Пример #1
0
 def _set_preferences(prefs):
     try:
         prefs = prefs()
     except RPCException:
         prefs = {}
     threads = []
     for target in (
             common.ICONFACTORY.load_icons,
             common.MODELACCESS.load_models,
             common.MODELHISTORY.load_history,
             common.VIEW_SEARCH.load_searches,
     ):
         t = threading.Thread(target=target)
         threads.append(t)
         t.start()
     for t in threads:
         t.join()
     if prefs and 'language_direction' in prefs:
         translate.set_language_direction(prefs['language_direction'])
         CONFIG['client.language_direction'] = \
             prefs['language_direction']
     self.sig_win_menu(prefs=prefs)
     for action_id in prefs.get('actions', []):
         Action.execute(action_id, {})
     self.set_title(prefs.get('status_bar', ''))
     if prefs and 'language' in prefs:
         translate.setlang(prefs['language'], prefs.get('locale'))
         if CONFIG['client.lang'] != prefs['language']:
             self.favorite_unset()
         CONFIG['client.lang'] = prefs['language']
     # Set placeholder after language is set to get correct translation
     self.global_search_entry.set_placeholder_text(_("Action"))
     CONFIG.save()
Пример #2
0
 def run(self):
     'Run the window'
     res = self.win.run()
     if res == gtk.RESPONSE_OK:
         CONFIG['client.limit'] = self.spin_limit.get_value_as_int()
         CONFIG.save()
     self.parent.present()
     self.win.destroy()
     return res
Пример #3
0
 def run(self):
     "Run the window"
     res = self.win.run()
     if res == Gtk.ResponseType.OK:
         CONFIG['client.email'] = self.entry.get_text()
         CONFIG.save()
     self.parent.present()
     self.win.destroy()
     return res
Пример #4
0
 def run(self):
     'Run the window'
     res = self.win.run()
     if res == gtk.RESPONSE_OK:
         CONFIG['client.limit'] = self.spin_limit.get_value_as_int()
         CONFIG.save()
     self.parent.present()
     self.win.destroy()
     return res
Пример #5
0
def main():
    CSS = b"""
    .readonly entry {
        background-color: @insensitive_bg_color;
    }
    .required entry {
        border-color: darker(@unfocused_borders);
    }
    .invalid entry, entry.invalid {
        border-color: @error_color;
    }
    """

    screen = Gdk.Screen.get_default()
    style_context = Gtk.StyleContext()
    provider = Gtk.CssProvider()
    provider.load_from_data(CSS)
    style_context.add_provider_for_screen(
        screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
    theme_path = os.path.join(get_config_dir(), 'theme.css')
    if os.path.exists(theme_path):
        provider = Gtk.CssProvider()
        provider.load_from_path(theme_path)
        style_context.add_provider_for_screen(screen, provider,
                                              Gtk.STYLE_PROVIDER_PRIORITY_USER)

    def excepthook(type_, value, traceback_):
        common.error(str(value), ''.join(traceback.format_tb(traceback_)))

    sys.excepthook = excepthook

    CONFIG.parse()
    if CONFIG.arguments:
        url = CONFIG.arguments[0]
        urlp = urlparse(url)
        if urlp.scheme == 'tryton':
            urlp = urlparse('http' + url[6:])
            database, _ = (urlp.path[1:].split('/', 1) + [None])[:2]
            CONFIG['login.host'] = urlp.netloc
            CONFIG['login.db'] = database
            CONFIG['login.expanded'] = True
        else:
            CONFIG.arguments = []
    translate.set_language_direction(CONFIG['client.language_direction'])
    translate.setlang(CONFIG['client.lang'])
    common.ICONFACTORY.load_client_icons()
    if CONFIG.arguments or DBLogin().run():
        server = '%(hostname)s:%(port)s/%(database)s' % {
            'hostname': common.get_hostname(CONFIG['login.host']),
            'port': common.get_port(CONFIG['login.host']),
            'database': CONFIG['login.db'],
        }
        server = hashlib.md5(server.encode('utf-8')).hexdigest()
        application_id = 'org.tryton._' + server
        app = gui.Main(application_id=application_id,
                       flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        app.run([sys.argv[0]] + CONFIG.arguments)
Пример #6
0
 def run(self):
     "Run the window"
     res = self.win.run()
     if res == gtk.RESPONSE_OK:
         CONFIG['client.email'] = self.entry.get_text()
         CONFIG.save()
     self.parent.present()
     self.win.destroy()
     return res
Пример #7
0
    def run(self):
        main = gui.Main(self)

        signal.signal(signal.SIGINT, lambda signum, frame: main.sig_quit())
        signal.signal(signal.SIGTERM, lambda signum, frame: main.sig_quit())
        if hasattr(signal, 'SIGQUIT'):
            signal.signal(signal.SIGQUIT,
                          lambda signum, frame: main.sig_quit())

        def excepthook(exctyp, exception, tb):
            import common
            import traceback
            from tryton.exceptions import TrytonServerError
            if (CONFIG['sentry.dsn']
                    and not isinstance(exception, TrytonServerError)):
                log = logging.getLogger(__name__)
                log.error(''.join(
                    traceback.format_exception(exctyp, exception, tb)) + '\n' +
                          str(exception))
                sentry = Client(CONFIG['sentry.dsn'])
                sentry_id = sentry.captureException((exctyp, exception, tb))
            else:
                sentry_id = None
            tb = ''.join(traceback.format_exception(exctyp, exception, tb))
            common.process_exception(exception, tb=tb, sentry_id=sentry_id)

        sys.excepthook = excepthook

        if CONFIG['tip.autostart']:
            main.sig_tips()
        main.sig_login()

        if sys.platform == 'win32':
            # http://faq.pygtk.org/index.py?req=show&file=faq21.003.htp
            def sleeper():
                time.sleep(.001)
                return 1

            gobject.timeout_add(400, sleeper)

        try:
            if sys.platform == 'win32':
                while not self.quit_client.isSet():
                    with gtk.gdk.lock:
                        gtk.main_iteration(True)
            else:
                gtk.main()
        except KeyboardInterrupt:
            CONFIG.save()
            gtk.accel_map_save(os.path.join(get_config_dir(), 'accel.map'))
Пример #8
0
    def run(self):
        main = gui.Main(self)

        signal.signal(signal.SIGINT, lambda signum, frame: main.sig_quit())
        signal.signal(signal.SIGTERM, lambda signum, frame: main.sig_quit())
        if hasattr(signal, "SIGQUIT"):
            signal.signal(signal.SIGQUIT, lambda signum, frame: main.sig_quit())

        def excepthook(exctyp, exception, tb):
            import common
            import traceback
            from tryton.exceptions import TrytonServerError

            if CONFIG["sentry.dsn"] and not isinstance(exception, TrytonServerError):
                log = logging.getLogger(__name__)
                log.error("".join(traceback.format_exception(exctyp, exception, tb)) + "\n" + str(exception))
                sentry = Client(CONFIG["sentry.dsn"])
                sentry_id = sentry.captureException((exctyp, exception, tb))
            else:
                sentry_id = None
            tb = "".join(traceback.format_exception(exctyp, exception, tb))
            common.process_exception(exception, tb=tb, sentry_id=sentry_id)

        sys.excepthook = excepthook

        if CONFIG["tip.autostart"]:
            main.sig_tips()
        main.sig_login()

        if sys.platform == "win32":
            # http://faq.pygtk.org/index.py?req=show&file=faq21.003.htp
            def sleeper():
                time.sleep(0.001)
                return 1

            gobject.timeout_add(400, sleeper)

        try:
            if sys.platform == "win32":
                while not self.quit_client.isSet():
                    with gtk.gdk.lock:
                        gtk.main_iteration(True)
            else:
                gtk.main()
        except KeyboardInterrupt:
            CONFIG.save()
            gtk.accel_map_save(os.path.join(get_config_dir(), "accel.map"))
Пример #9
0
    def run(self):
        main = gui.Main(self)

        signal.signal(signal.SIGINT, lambda signum, frame: main.sig_quit())
        signal.signal(signal.SIGTERM, lambda signum, frame: main.sig_quit())
        if hasattr(signal, 'SIGQUIT'):
            signal.signal(signal.SIGQUIT,
                lambda signum, frame: main.sig_quit())

        def excepthook(exctyp, exception, tb):
            import common
            import traceback
            tb = '\n'.join(traceback.format_tb(tb))
            common.process_exception(exception, tb=tb)

        sys.excepthook = excepthook

        if CONFIG['tip.autostart']:
            main.sig_tips()
        main.sig_login()

        #XXX psyco breaks report printing
        #try:
        #    import psyco
        #    psyco.full()
        #except ImportError:
        #    pass

        if sys.platform == 'win32':
            # http://faq.pygtk.org/index.py?req=show&file=faq21.003.htp
            def sleeper():
                time.sleep(.001)
                return 1
            gobject.timeout_add(400, sleeper)

        try:
            if sys.platform == 'win32':
                while not self.quit_client.isSet():
                    with gtk.gdk.lock:
                            gtk.main_iteration(True)
            else:
                gtk.main()
        except KeyboardInterrupt:
            CONFIG.save()
            if hasattr(gtk, 'accel_map_save'):
                gtk.accel_map_save(os.path.join(get_config_dir(), 'accel.map'))
Пример #10
0
    def get_preferences(self, date=''):
        RPCContextReload()
        try:
            prefs = RPCExecute('model', 'res.user', 'get_preferences', False)
        except RPCException:
            prefs = {}

        threads = []
        for target in (
                common.IconFactory.load_icons,
                common.MODELACCESS.load_models,
                common.MODELHISTORY.load_history,
                common.VIEW_SEARCH.load_searches,
                ):
            t = threading.Thread(target=target)
            threads.append(t)
            t.start()
        for t in threads:
            t.join()
        if prefs and 'language_direction' in prefs:
            translate.set_language_direction(prefs['language_direction'])
            CONFIG['client.language_direction'] = \
                prefs['language_direction']
        self.sig_win_menu(prefs=prefs)
        for action_id in prefs.get('actions', []):
            Action.execute(action_id, {})
        # XXX: add connection date
        connection_date = date.strftime('%d/%m/%Y') if date else ''
        self.set_title(prefs.get('status_bar', ''), connection_date)
        # AKE: change bg color based on preferences
        color_bg = prefs.get('color_bg', None
            ) or os.environ.get('TRYTON_CLIENT_BG_COLOR', None)
        if color_bg:
            self.window.modify_bg(Gtk.StateType.NORMAL,
                Gdk.color_parse(color_bg))
        if prefs and 'language' in prefs:
            translate.setlang(prefs['language'], prefs.get('locale'))
            if CONFIG['client.lang'] != prefs['language']:
                self.favorite_unset()
            CONFIG['client.lang'] = prefs['language']
        # Set placeholder after language is set to get correct translation
        self.global_search_entry.set_placeholder_text(_("Action"))
        CONFIG.save()
Пример #11
0
 def __init__(self):
     CONFIG.parse()
     if CONFIG.arguments:
         url, = CONFIG.arguments
         urlp = urlparse(url)
         if urlp.scheme == "tryton":
             urlp = urlparse("http" + url[6:])
             hostname, port = (urlp.netloc.split(":", 1) + [CONFIG.defaults["login.port"]])[:2]
             database, _ = (urlp.path[1:].split("/", 1) + [None])[:2]
             if IPCClient(hostname, port, database).write(url):
                 sys.exit(0)
             CONFIG["login.server"] = hostname
             CONFIG["login.port"] = port
             CONFIG["login.db"] = database
             CONFIG["login.expanded"] = True
             CONFIG["proxy.active"] = False
     translate.set_language_direction(CONFIG["client.language_direction"])
     translate.setlang(CONFIG["client.lang"])
     self.quit_client = threading.Event() if sys.platform == "win32" else None
     common.ICONFACTORY.load_client_icons()
Пример #12
0
 def __init__(self):
     CONFIG.parse()
     if CONFIG.arguments:
         url, = CONFIG.arguments
         urlp = urlparse(url)
         if urlp.scheme == 'tryton':
             urlp = urlparse('http' + url[6:])
             hostname = common.get_hostname(urlp.netloc)
             port = common.get_port(urlp.netloc)
             database, _ = (urlp.path[1:].split('/', 1) + [None])[:2]
             if IPCClient(hostname, port, database).write(url):
                 sys.exit(0)
             CONFIG['login.host'] = urlp.netloc
             CONFIG['login.db'] = database
             CONFIG['login.expanded'] = True
     translate.set_language_direction(CONFIG['client.language_direction'])
     translate.setlang(CONFIG['client.lang'])
     self.quit_client = (threading.Event()
                         if sys.platform == 'win32' else None)
     common.ICONFACTORY.load_client_icons()
Пример #13
0
    def run(self):
        main = gui.Main(self)

        signal.signal(signal.SIGINT, lambda signum, frame: main.sig_quit())
        signal.signal(signal.SIGTERM, lambda signum, frame: main.sig_quit())
        if hasattr(signal, 'SIGQUIT'):
            signal.signal(signal.SIGQUIT,
                          lambda signum, frame: main.sig_quit())

        def excepthook(*args):
            import common
            import traceback
            detail = ''.join(traceback.format_exception(*args))
            common.error(str(args[1]), detail)

        sys.excepthook = excepthook

        #       Remove Tips
        #        if CONFIG['tip.autostart']:
        #            main.sig_tips()

        main.sig_login()

        if sys.platform == 'win32':
            # http://faq.pygtk.org/index.py?req=show&file=faq21.003.htp
            def sleeper():
                time.sleep(.001)
                return 1

            gobject.timeout_add(400, sleeper)

        try:
            if sys.platform == 'win32':
                while not self.quit_client.isSet():
                    with gtk.gdk.lock:
                        gtk.main_iteration()
            else:
                gtk.main()
        except KeyboardInterrupt:
            CONFIG.save()
            gtk.accel_map_save(os.path.join(get_config_dir(), 'accel.map'))
Пример #14
0
 def __init__(self):
     CONFIG.parse()
     if CONFIG.arguments:
         url, = CONFIG.arguments
         urlp = urlparse(url)
         if urlp.scheme == 'tryton':
             urlp = urlparse('http' + url[6:])
             hostname, port = (urlp.netloc.split(':', 1)
                     + [CONFIG.defaults['login.port']])[:2]
             database, _ = (urlp.path[1:].split('/', 1) + [None])[:2]
             if IPCClient(hostname, port, database).write(url):
                 sys.exit(0)
             CONFIG['login.server'] = hostname
             CONFIG['login.port'] = port
             CONFIG['login.db'] = database
             CONFIG['login.expanded'] = True
     translate.set_language_direction(CONFIG['client.language_direction'])
     translate.setlang(CONFIG['client.lang'])
     self.quit_client = (threading.Event()
         if sys.platform == 'win32' else None)
     common.ICONFACTORY.load_client_icons()
Пример #15
0
    def __init__(self):
        CONFIG.parse()
        if CONFIG.arguments:
            url, = CONFIG.arguments
            urlp = urlparse(url)
            if urlp.scheme == 'tryton':
                urlp = urlparse('http' + url[6:])
                hostname, port = (urlp.netloc.split(':', 1)
                        + [CONFIG.defaults['login.port']])[:2]
                database, _ = (urlp.path[1:].split('/', 1) + [None])[:2]
                if IPCClient(hostname, port, database).write(url):
                    sys.exit(0)
                CONFIG['login.server'] = hostname
                CONFIG['login.port'] = port
                CONFIG['login.db'] = database
                CONFIG['login.expanded'] = True
        logging.basicConfig()
        translate.set_language_direction(CONFIG['client.language_direction'])
        translate.setlang(CONFIG['client.lang'])
        loglevel = {
                'DEBUG': logging.DEBUG,
                'INFO': logging.INFO,
                'WARNING': logging.WARNING,
                'ERROR': logging.ERROR,
                'CRITICAL': logging.CRITICAL,
                }
        for logger in CONFIG['logging.logger'].split(','):
            if logger:
                log = logging.getLogger(logger)
                log.setLevel(loglevel[CONFIG['logging.level'].upper()])
        if CONFIG['logging.default']:
            logging.getLogger().setLevel(
                    loglevel[CONFIG['logging.default'].upper()])

        self.quit_client = (threading.Event()
            if sys.platform == 'win32' else None)
        common.ICONFACTORY.load_client_icons()
Пример #16
0
    def __init__(self):
        self.tips = [
            _('''<b>Welcome to Tryton</b>


'''),
            _(u'''<b>Do you know Triton, one of the namesakes for our project?</b>

Triton (pronounced /ˈtraɪtən/ TRYE-tən, or as in Greek Τρίτων) is the
largest moon of the planet Neptune, discovered on October 10, 1846
by William Lassell. It is the only large moon in the Solar System
with a retrograde orbit, which is an orbit in the opposite direction
to its planet's rotation. At 2,700 km in diameter, it is the seventh-largest
moon in the Solar System. Triton comprises more than 99.5 percent of all
the mass known to orbit Neptune, including the planet's rings and twelve
other known moons. It is also more massive than all the Solar System's
159 known smaller moons combined.
'''),
            _('''<b>Export list records</b>

You can copy records from any list with Ctrl + C
and paste in any application with Ctrl + V
'''),
            _('''<b>Export graphs</b>

You can save any graphs in PNG file with right-click on it.
'''),
        ]

        parent = get_toplevel_window()
        self.win = gtk.Dialog(
            _('Tips'), parent,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.win.set_icon(TRYTON_ICON)
        self.win.set_has_separator(True)
        self.win.set_default_size(500, 400)

        self.win.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.win.set_default_response(gtk.RESPONSE_CLOSE)
        vbox = gtk.VBox()
        img = gtk.Image()
        img.set_from_file(os.path.join(PIXMAPS_DIR, 'tryton.png'))
        vbox.pack_start(img, False, False)
        self.label = gtk.Label()
        self.label.set_alignment(0, 0)
        vbox.pack_start(self.label, True, True)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, False)

        hbox = gtk.HBox()
        self.check = gtk.CheckButton(_('_Display a new tip next time'), True)
        self.check.set_active(True)
        hbox.pack_start(self.check)
        but_previous = gtk.Button()
        hbox_previous = gtk.HBox()
        img_previous = gtk.Image()
        img_previous.set_from_stock('tryton-go-previous', gtk.ICON_SIZE_BUTTON)
        hbox_previous.pack_start(img_previous)
        label_previous = gtk.Label(_('Previous'))
        hbox_previous.pack_start(label_previous)
        but_previous.add(hbox_previous)
        but_previous.set_relief(gtk.RELIEF_NONE)
        but_previous.connect('clicked', self.tip_previous)
        hbox.pack_start(but_previous)
        hbox_next = gtk.HBox()
        label_next = gtk.Label(_('Next'))
        hbox_next.pack_start(label_next)
        but_next = gtk.Button()
        img_next = gtk.Image()
        img_next.set_from_stock('tryton-go-next', gtk.ICON_SIZE_BUTTON)
        hbox_next.pack_start(img_next)
        but_next.add(hbox_next)
        but_next.set_relief(gtk.RELIEF_NONE)
        but_next.connect('clicked', self.tip_next)
        hbox.pack_start(but_next)
        vbox.pack_start(hbox, False, False)
        self.win.vbox.pack_start(vbox)
        self.win.show_all()

        try:
            self.number = int(CONFIG['tip.position'])
        except ValueError:
            self.number = 0

        self.tip_set()

        self.win.run()
        CONFIG['tip.autostart'] = self.check.get_active()
        CONFIG['tip.position'] = self.number + 1
        CONFIG.save()
        parent.present()
        self.win.destroy()
Пример #17
0
def save(widget, graph):
    parent = common.get_toplevel_window()
    dia = gtk.Dialog(
        _('Save As'), parent,
        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
    dia.set_icon(TRYTON_ICON)
    dia.set_has_separator(True)
    dia.set_default_response(gtk.RESPONSE_OK)

    dia.vbox.set_spacing(5)
    dia.vbox.set_homogeneous(False)

    title = gtk.Label('<b>' + _('Image Size') + '</b>')
    title.set_alignment(0.0, 0.5)
    title.set_use_markup(True)
    dia.vbox.pack_start(title)

    table = gtk.Table(2, 2)
    table.set_col_spacings(3)
    table.set_row_spacings(3)
    table.set_border_width(1)
    table.attach(gtk.Label(_('Width:')),
                 0,
                 1,
                 0,
                 1,
                 yoptions=False,
                 xoptions=gtk.FILL)
    spinwidth = gtk.SpinButton(
        gtk.Adjustment(400.0, 0.0, sys.maxint, 1.0, 10.0))
    spinwidth.set_numeric(True)
    spinwidth.set_activates_default(True)
    table.attach(spinwidth, 1, 2, 0, 1, yoptions=False, xoptions=gtk.FILL)
    table.attach(gtk.Label(_('Height:')),
                 0,
                 1,
                 1,
                 2,
                 yoptions=False,
                 xoptions=gtk.FILL)
    spinheight = gtk.SpinButton(
        gtk.Adjustment(200.0, 0.0, sys.maxint, 1.0, 10.0))
    spinheight.set_numeric(True)
    spinheight.set_activates_default(True)
    table.attach(spinheight, 1, 2, 1, 2, yoptions=False, xoptions=gtk.FILL)
    dia.vbox.pack_start(table)

    filechooser = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SAVE, None)
    filechooser.set_current_folder(CONFIG['client.default_path'])
    filter = gtk.FileFilter()
    filter.set_name(_('PNG image (*.png)'))
    filter.add_mime_type('image/png')
    filter.add_pattern('*.png')
    filechooser.add_filter(filter)
    dia.vbox.pack_start(filechooser)

    dia.show_all()

    while True:
        response = dia.run()
        width = spinwidth.get_value_as_int()
        height = spinheight.get_value_as_int()
        filename = filechooser.get_filename()
        if filename:
            filename = filename.decode('utf-8')
            try:
                CONFIG['client.default_path'] = \
                    os.path.dirname(filename)
                CONFIG.save()
            except IOError:
                pass
        if response == gtk.RESPONSE_OK:
            if width and height and filename:
                if not filename.endswith('.png'):
                    filename = filename + '.png'
                try:
                    graph.export_png(filename, width, height)
                    break
                except MemoryError:
                    common.message(_('Image size too large!'), dia,
                                   gtk.MESSAGE_ERROR)
        else:
            break
    parent.present()
    dia.destroy()
    return
Пример #18
0
def file_selection(title, filename='',
        action=gtk.FILE_CHOOSER_ACTION_OPEN, preview=True, multi=False,
        filters=None):
    parent = get_toplevel_window()
    if action == gtk.FILE_CHOOSER_ACTION_OPEN:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_OPEN, gtk.RESPONSE_OK)
    else:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_SAVE, gtk.RESPONSE_OK)
    win = gtk.FileChooserDialog(title, None, action, buttons)
    win.set_transient_for(parent)
    win.set_icon(TRYTON_ICON)
    win.set_current_folder(CONFIG['client.default_path'])
    if filename:
        win.set_current_name(filename)
    win.set_select_multiple(multi)
    win.set_default_response(gtk.RESPONSE_OK)
    if filters is not None:
        for filt in filters:
            win.add_filter(filt)

    def update_preview_cb(win, img):
        have_preview = False
        filename = win.get_preview_filename()
        if filename:
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    filename, 128, 128)
                img.set_from_pixbuf(pixbuf)
                have_preview = True
            except (IOError, glib.GError):
                pass
        win.set_preview_widget_active(have_preview)
        return

    if preview:
        img_preview = gtk.Image()
        win.set_preview_widget(img_preview)
        win.connect('update-preview', update_preview_cb, img_preview)

    button = win.run()
    if button != gtk.RESPONSE_OK:
        parent.present()
        win.destroy()
        return False
    if not multi:
        filepath = win.get_filename()
        if filepath:
            filepath = filepath.decode('utf-8')
            try:
                CONFIG['client.default_path'] = \
                    os.path.dirname(filepath)
                CONFIG.save()
            except IOError:
                pass
        parent.present()
        win.destroy()
        return filepath
    else:
        filenames = win.get_filenames()
        if filenames:
            filenames = [x.decode('utf-8') for x in filenames]
            try:
                CONFIG['client.default_path'] = \
                    os.path.dirname(filenames[0])
            except IOError:
                pass
        parent.present()
        win.destroy()
        return filenames
Пример #19
0
def save(widget, graph):
    parent = common.get_toplevel_window()
    dia = gtk.Dialog(_('Save As'), parent,
        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
    dia.set_icon(TRYTON_ICON)
    dia.set_has_separator(True)
    dia.set_default_response(gtk.RESPONSE_OK)

    dia.vbox.set_spacing(5)
    dia.vbox.set_homogeneous(False)

    title = gtk.Label('<b>' + _('Image Size') + '</b>')
    title.set_alignment(0.0, 0.5)
    title.set_use_markup(True)
    dia.vbox.pack_start(title)

    table = gtk.Table(2, 2)
    table.set_col_spacings(3)
    table.set_row_spacings(3)
    table.set_border_width(1)
    table.attach(gtk.Label(_('Width:')), 0, 1, 0, 1, yoptions=False,
            xoptions=gtk.FILL)
    spinwidth = gtk.SpinButton(gtk.Adjustment(400.0,
            0.0, sys.maxint, 1.0, 10.0))
    spinwidth.set_numeric(True)
    spinwidth.set_activates_default(True)
    table.attach(spinwidth, 1, 2, 0, 1, yoptions=False, xoptions=gtk.FILL)
    table.attach(gtk.Label(_('Height:')), 0, 1, 1, 2, yoptions=False,
            xoptions=gtk.FILL)
    spinheight = gtk.SpinButton(gtk.Adjustment(200.0,
            0.0, sys.maxint, 1.0, 10.0))
    spinheight.set_numeric(True)
    spinheight.set_activates_default(True)
    table.attach(spinheight, 1, 2, 1, 2, yoptions=False, xoptions=gtk.FILL)
    dia.vbox.pack_start(table)

    filechooser = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SAVE, None)
    filechooser.set_current_folder(CONFIG['client.default_path'])
    filter = gtk.FileFilter()
    filter.set_name(_('PNG image (*.png)'))
    filter.add_mime_type('image/png')
    filter.add_pattern('*.png')
    filechooser.add_filter(filter)
    dia.vbox.pack_start(filechooser)

    dia.show_all()

    while True:
        response = dia.run()
        width = spinwidth.get_value_as_int()
        height = spinheight.get_value_as_int()
        filename = filechooser.get_filename()
        if filename:
            filename = filename.decode('utf-8')
            try:
                CONFIG['client.default_path'] = \
                       os.path.dirname(filename)
                CONFIG.save()
            except IOError:
                pass
        if response == gtk.RESPONSE_OK:
            if width and height and filename:
                if not filename.endswith('.png'):
                    filename = filename + '.png'
                try:
                    graph.export_png(filename, width, height)
                    break
                except MemoryError:
                    common.message(_('Image size too large!'), dia,
                            gtk.MESSAGE_ERROR)
        else:
            break
    parent.present()
    dia.destroy()
    return
Пример #20
0
def file_selection(title, filename='',
        action=gtk.FILE_CHOOSER_ACTION_OPEN, preview=True, multi=False,
        filters=None):
    parent = get_toplevel_window()
    if action == gtk.FILE_CHOOSER_ACTION_OPEN:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_OPEN, gtk.RESPONSE_OK)
    else:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_SAVE, gtk.RESPONSE_OK)
    win = gtk.FileChooserDialog(title, None, action, buttons)
    win.set_transient_for(parent)
    win.set_icon(TRYTON_ICON)
    win.set_current_folder(CONFIG['client.default_path'])
    if filename:
        win.set_current_name(filename)
    win.set_select_multiple(multi)
    win.set_default_response(gtk.RESPONSE_OK)
    if filters is not None:
        for filt in filters:
            win.add_filter(filt)

    def update_preview_cb(win, img):
        have_preview = False
        filename = win.get_preview_filename()
        if filename:
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename.decode(
                        sys.getfilesystemencoding().encode('utf-8')), 128, 128)
                img.set_from_pixbuf(pixbuf)
                have_preview = True
            except (IOError, glib.GError):
                pass
        win.set_preview_widget_active(have_preview)
        return

    if preview:
        img_preview = gtk.Image()
        win.set_preview_widget(img_preview)
        win.connect('update-preview', update_preview_cb, img_preview)

    button = win.run()
    if button != gtk.RESPONSE_OK:
        parent.present()
        win.destroy()
        return False
    if not multi:
        filepath = win.get_filename()
        if filepath:
            filepath = filepath.decode('utf-8')
            try:
                CONFIG['client.default_path'] = \
                    os.path.dirname(filepath)
                CONFIG.save()
            except IOError:
                pass
        parent.present()
        win.destroy()
        return filepath
    else:
        filenames = win.get_filenames()
        if filenames:
            filenames = [x.decode('utf-8') for x in filenames]
            try:
                CONFIG['client.default_path'] = \
                    os.path.dirname(filenames[0])
            except IOError:
                pass
        parent.present()
        win.destroy()
        return filenames
Пример #21
0
def main():
    CSS = b"""
    .readonly entry, .readonly text {
        background-color: @insensitive_bg_color;
    }
    .required entry, .required text {
        border-color: darker(@unfocused_borders);
    }
    .invalid entry, entry.invalid, .invalid text, text.invalid {
        border-color: @error_color;
    }
    label.required {
        font-weight: bold;
    }
    label.editable {
        font-style: italic;
    }
    .window-title, .wizard-title {
        background-color: white;
        font-size: large;
        font-weight: bold;
    }
    .window-title .status {
        font-size: medium;
        font-weight: normal;
    }
    """

    screen = Gdk.Screen.get_default()
    style_context = Gtk.StyleContext()
    provider = Gtk.CssProvider()
    # the line below injects CSS with higher priority than the custom theme
    # -> it overrides Coog theme behavior
    # provider.load_from_data(CSS)
    style_context.add_provider_for_screen(screen, provider,
                                          Gtk.STYLE_PROVIDER_PRIORITY_USER)
    theme_path = os.path.join(get_config_dir(), 'theme.css')
    if os.path.exists(theme_path):
        provider = Gtk.CssProvider()
        provider.load_from_path(theme_path)
        style_context.add_provider_for_screen(screen, provider,
                                              Gtk.STYLE_PROVIDER_PRIORITY_USER)

    def excepthook(type_, value, traceback_):
        common.error(value, ''.join(traceback.format_tb(traceback_)))

    sys.excepthook = excepthook

    CONFIG.parse()
    if CONFIG.arguments:
        url = CONFIG.arguments[0]
        urlp = urlparse(url)
        if urlp.scheme == 'tryton':
            urlp = urlparse('http' + url[6:])
            database, _ = (urlp.path[1:].split('/', 1) + [None])[:2]
            CONFIG['login.host'] = urlp.netloc
            CONFIG['login.db'] = database
            CONFIG['login.expanded'] = True
        else:
            CONFIG.arguments = []
    translate.set_language_direction(CONFIG['client.language_direction'])
    translate.setlang(CONFIG['client.lang'])
    if CONFIG.arguments or DBLogin().run():
        server = '%(hostname)s:%(port)s/%(database)s' % {
            'hostname': common.get_hostname(CONFIG['login.host']),
            'port': common.get_port(CONFIG['login.host']),
            'database': CONFIG['login.db'],
        }
        server = hashlib.md5(server.encode('utf-8')).hexdigest()
        application_id = 'org.tryton._' + server
        app = gui.Main(application_id=application_id,
                       flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        app.run([sys.argv[0]] + CONFIG.arguments)
Пример #22
0
 def do_shutdown(self):
     Gtk.Application.do_shutdown(self)
     common.Logout()
     CONFIG.save()
     Gtk.AccelMap.save(os.path.join(get_config_dir(), 'accel.map'))
Пример #23
0
    def __init__(self):
        self.tips = [
            _('''<b>Welcome to Tryton</b>


'''),
            _(u'''<b>Do you know Triton, one of the namesakes for our project?</b>

Triton (pronounced /ˈtraɪtən/ TRYE-tən, or as in Greek Τρίτων) is the
largest moon of the planet Neptune, discovered on October 10, 1846
by William Lassell. It is the only large moon in the Solar System
with a retrograde orbit, which is an orbit in the opposite direction
to its planet's rotation. At 2,700 km in diameter, it is the seventh-largest
moon in the Solar System. Triton comprises more than 99.5 percent of all
the mass known to orbit Neptune, including the planet's rings and twelve
other known moons. It is also more massive than all the Solar System's
159 known smaller moons combined.
'''),
            _('''<b>Export list records</b>

You can copy records from any list with Ctrl + C
and paste in any application with Ctrl + V
'''),
            _('''<b>Export graphs</b>

You can save any graphs in PNG file with right-click on it.
'''),
        ]

        parent = get_toplevel_window()
        self.win = gtk.Dialog(_('Tips'), parent,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.win.set_icon(TRYTON_ICON)
        self.win.set_has_separator(True)
        self.win.set_default_size(500, 400)

        self.win.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.win.set_default_response(gtk.RESPONSE_CLOSE)
        vbox = gtk.VBox()
        img = gtk.Image()
        img.set_from_file(os.path.join(PIXMAPS_DIR, 'tryton.png'))
        vbox.pack_start(img, False, False)
        self.label = gtk.Label()
        self.label.set_alignment(0, 0)
        vbox.pack_start(self.label, True, True)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, False)

        hbox = gtk.HBox()
        self.check = gtk.CheckButton(_('_Display a new tip next time'), True)
        self.check.set_active(True)
        hbox.pack_start(self.check)
        but_previous = gtk.Button()
        hbox_previous = gtk.HBox()
        img_previous = gtk.Image()
        img_previous.set_from_stock('tryton-go-previous', gtk.ICON_SIZE_BUTTON)
        hbox_previous.pack_start(img_previous)
        label_previous = gtk.Label(_('Previous'))
        hbox_previous.pack_start(label_previous)
        but_previous.add(hbox_previous)
        but_previous.set_relief(gtk.RELIEF_NONE)
        but_previous.connect('clicked', self.tip_previous)
        hbox.pack_start(but_previous)
        hbox_next = gtk.HBox()
        label_next = gtk.Label(_('Next'))
        hbox_next.pack_start(label_next)
        but_next = gtk.Button()
        img_next = gtk.Image()
        img_next.set_from_stock('tryton-go-next', gtk.ICON_SIZE_BUTTON)
        hbox_next.pack_start(img_next)
        but_next.add(hbox_next)
        but_next.set_relief(gtk.RELIEF_NONE)
        but_next.connect('clicked', self.tip_next)
        hbox.pack_start(but_next)
        vbox.pack_start(hbox, False, False)
        self.win.vbox.pack_start(vbox)
        self.win.show_all()

        try:
            self.number = int(CONFIG['tip.position'])
        except ValueError:
            self.number = 0

        self.tip_set()

        self.win.run()
        CONFIG['tip.autostart'] = self.check.get_active()
        CONFIG['tip.position'] = self.number + 1
        CONFIG.save()
        parent.present()
        self.win.destroy()
Пример #24
0
    def __init__(self):

        self.tips = [
            _('''<b>Welcome to Akara Services</b>


'''),
            
            _('''<b>Export list records</b>

You can copy records from any list with Ctrl + C
and paste in any application with Ctrl + V
'''),
            _('''<b>Export graphs</b>

You can save any graphs in PNG file with right-click on it.
'''),
        ]

        parent = get_toplevel_window()
        
        self.win = gtk.Dialog(_('Tips'), parent,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.win.set_icon(TRYTON_ICON)
        self.win.set_has_separator(True)
        self.win.set_size_request(500, 400)

        self.win.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.win.set_default_response(gtk.RESPONSE_CLOSE)
        vbox = gtk.VBox()
        #img = gtk.Image()
        #img.set_from_file(os.path.join(PIXMAPS_DIR, 'tryton.png'))
        #vbox.pack_start(img, False, False)
        self.label = gtk.Label()
        self.label.set_alignment(0, 0)
        vbox.pack_start(self.label, True, True)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, False)

        hbox = gtk.HBox()
        self.check = gtk.CheckButton(_('_Display a new tip next time'), True)
        self.check.set_active(True)
        hbox.pack_start(self.check)
        but_previous = gtk.Button()
        hbox_previous = gtk.HBox()
        img_previous = gtk.Image()
        img_previous.set_from_stock('tryton-go-previous', gtk.ICON_SIZE_BUTTON)
        hbox_previous.pack_start(img_previous)
        label_previous = gtk.Label(_('Previous'))
        hbox_previous.pack_start(label_previous)
        but_previous.add(hbox_previous)
        but_previous.set_relief(gtk.RELIEF_NONE)
        but_previous.connect('clicked', self.tip_previous)
        hbox.pack_start(but_previous)
        hbox_next = gtk.HBox()
        label_next = gtk.Label(_('Next'))
        hbox_next.pack_start(label_next)
        but_next = gtk.Button()
        img_next = gtk.Image()
        img_next.set_from_stock('tryton-go-next', gtk.ICON_SIZE_BUTTON)
        hbox_next.pack_start(img_next)
        but_next.add(hbox_next)
        but_next.set_relief(gtk.RELIEF_NONE)
        but_next.connect('clicked', self.tip_next)
        hbox.pack_start(but_next)
        vbox.pack_start(hbox, False, False)
        self.win.vbox.pack_start(vbox)
        self.win.show_all()

        try:
            self.number = int(CONFIG['tip.position'])
        except ValueError:
            self.number = 0

        self.tip_set()

        self.win.run()
        CONFIG['tip.autostart'] = self.check.get_active()
        CONFIG['tip.position'] = self.number + 1
        CONFIG.save()
        parent.present()
        self.win.destroy()