예제 #1
0
    def __init__(self, handle):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle)

        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        # Draw the canvas
        self._canvas = MyCanvas()
        self.set_canvas(self._canvas)
        self._canvas.show()

        GObject.timeout_add(100, read_accelerometer, self._canvas)
    def __init__(self, handle):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle)

        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        # Draw the canvas
        self._canvas = MyCanvas()
        self.set_canvas(self._canvas)
        self._canvas.show()

        GObject.timeout_add(100, read_accelerometer, self._canvas)
예제 #3
0
    def build_toolbar(self):

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        return toolbar_box
예제 #4
0
    def __init__(self, handle):
        print "running activity init", handle
        activity.Activity.__init__(self, handle)
        print "activity running"

        self.set_title('Teach Teacher')

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = Gtk.Toolbar()

        button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(button, -1)

        self.goBack = ToolButton('go-left')
        self.goBack.set_tooltip("Go Back")
        self.goBack.connect('clicked', self.back_clicked)
        toolbar.insert(self.goBack, -1)

        self.home = ToolButton('go-home')
        self.home.set_tooltip("Home")
        self.home.connect('clicked', self.home_clicked)
        toolbar.insert(self.home, -1)

        self.xois = ToolButton('computer-xo')
        self.xois.set_tooltip("T's XO")
        self.xois.connect('clicked', self.xois_clicked)
        # toolbar.insert(self.xois, -1)
        # self.xois.show()

        self.guide = ToolButton('go-next')
        self.guide.set_tooltip("T's Guide")
        self.guide.connect('clicked', self.guide_clicked)
        # toolbar.insert(self.guide, -1)
        # self.guide.show()

        toolbarbox.toolbar.insert(ToolbarButton(page=toolbar, icon_name='toolbar-edit'), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbarbox.toolbar.insert(stop_button, -1)

        scroll = Gtk.ScrolledWindow()
        self.set_canvas(scroll)

        self.webview = WebView()
        self.webview.load_uri('http://147.47.120.20/~tsquare/menu.php')
        scroll.add(self.webview)

        toolbar.show_all()
        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
        self.show_all()

        print "AT END OF THE CLASS"
예제 #5
0
    def __init__(self, handle):
        print "running activity init", handle
        activity.Activity.__init__(self, handle)
        print "activity running"

        self.set_title('Teach Teacher')

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = Gtk.Toolbar()

        button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(button, -1)

        self.goBack = ToolButton('go-left')
        self.goBack.set_tooltip("Go Back")
        self.goBack.connect('clicked', self.back_clicked)
        toolbar.insert(self.goBack, -1)

        self.home = ToolButton('go-home')
        self.home.set_tooltip("Home")
        self.home.connect('clicked', self.home_clicked)
        toolbar.insert(self.home, -1)

        self.xois = ToolButton('computer-xo')
        self.xois.set_tooltip("T's XO")
        self.xois.connect('clicked', self.xois_clicked)
        # toolbar.insert(self.xois, -1)
        # self.xois.show()

        self.guide = ToolButton('go-next')
        self.guide.set_tooltip("T's Guide")
        self.guide.connect('clicked', self.guide_clicked)
        # toolbar.insert(self.guide, -1)
        # self.guide.show()

        toolbarbox.toolbar.insert(ToolbarButton(page=toolbar, icon_name='toolbar-edit'), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbarbox.toolbar.insert(stop_button, -1)

        scroll = Gtk.ScrolledWindow()
        self.set_canvas(scroll)

        self.webview = WebView()
        self.webview.load_uri('http://147.47.120.20/~tsquare/menu.php')
        scroll.add(self.webview)

        toolbar.show_all()
        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
        self.show_all()

        print "AT END OF THE CLASS"
예제 #6
0
    def _setup_toolbarbox(self):
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbarbox.toolbar.insert(ActivityToolbarButton(self), -1)
        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbarbox.toolbar.insert(StopButton(self), -1)

        names = ""
        parser = SafeConfigParser()
        parser.read("config.ini")
        for data in [("dic", "A"), ("dic", "E"), ("dic", "I"), ("dic", "O"),
                     ("dic", "U"), ("dic", "Y"), ("dic", "G")]:
            names += parser.get(*data) + " "

        names = names[:-1]

        help_button = HelpButton()
        help_button.add_paragraph(
            _("Para traducir algo, debes escribirlo en la entrada de abajo y luego presionar enter."
              ))
        help_button.add_paragraph(
            _("También puedes ver las traducciones abajo."))
        help_button.add_paragraph(
            _("Al precionar uno de los botones (%s), su texto se insertará en la entrada de escritura"
              % names))
        toolbarbox.toolbar.insert(help_button, 2)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, 3)

        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
예제 #7
0
    def build_toolbar(self):
        self.max_participants = 1

        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)

        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.blocklist = []
        self.radioList = {}
        for c in tools.allTools:
            button = ToolButton(c.icon)
            button.set_tooltip(_(c.toolTip))
            button.connect('clicked', self.radioClicked)
            toolbar_box.toolbar.insert(button, -1)
            button.show()
            self.radioList[button] = c.name

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
예제 #8
0
    def _setup_toolbarbox(self):
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbarbox.toolbar.insert(ActivityToolbarButton(self), -1)
        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbarbox.toolbar.insert(StopButton(self), -1)

        names = ""
        parser = SafeConfigParser()
        parser.read("config.ini")
        for data in [("dic", "A"), ("dic", "E"), ("dic", "I"), ("dic", "O"), ("dic", "U"), ("dic", "Y"), ("dic", "G")]:
            names += parser.get(*data) + " "
        
        names = names[:-1]

        help_button = HelpButton()
        help_button.add_paragraph(_("Para traducir algo, debes escribirlo en la entrada de abajo y luego presionar enter."))
        help_button.add_paragraph(_("También puedes ver las traducciones abajo."))
        help_button.add_paragraph(_("Al precionar uno de los botones (%s), su texto se insertará en la entrada de escritura" % names))
        toolbarbox.toolbar.insert(help_button, 2)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, 3)

        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
예제 #9
0
class CollabEditActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.toolbarbox = ToolbarBox()
        self.toolbar = self.toolbarbox.toolbar
        self.set_toolbar_box(self.toolbarbox)

        self.edit = collabedit.CollabEdit(self)
        self.edit.connect("cursor-position-changed", self._cursor_positon_changed_cb)
        self.set_canvas(self.edit)

        self.setup_toolbar()

        self.show_all()

    def _cursor_positon_changed_cb(self, edit, pos):
        self.button_bold.props.active = self.edit.check_tag_at_offset("bold", pos)
        self.button_italic.props.active = self.edit.check_tag_at_offset("italic", pos)
        self.button_underline.props.active = self.edit.check_tag_at_offset("underline", pos)

    def setup_toolbar(self):
        activity_button = ActivityToolbarButton(self)
        self.toolbar.insert(activity_button, -1)

        self.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        edit_toolbar = EditToolbar()
        self.toolbar.insert(ToolbarButton(page=edit_toolbar, icon_name="toolbar-edit"), -1)

        edit_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.button_bold = ToggleToolButton("format-text-bold")
        self.button_bold.set_tooltip(_("Bold"))
        self.button_bold.props.accelerator = "<Ctrl>B"
        self.button_bold.connect("toggled", lambda button: self.edit.toggle_bold())
        edit_toolbar.insert(self.button_bold, -1)

        self.button_italic = ToggleToolButton("format-text-italic")
        self.button_italic.set_tooltip(_("Italic"))
        self.button_italic.props.accelerator = "<Ctrl>I"
        self.button_italic.connect("toggled", lambda button: self.edit.toggle_italic())
        edit_toolbar.insert(self.button_italic, -1)

        self.button_underline = ToggleToolButton("format-text-underline")
        self.button_underline.set_tooltip(_("Underline"))
        self.button_underline.props.accelerator = "<Ctrl>B"
        self.button_underline.connect("toggled", lambda button: self.edit.toggle_underline())
        edit_toolbar.insert(self.button_underline, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        self.toolbar.insert(stop_button, -1)

        self.toolbarbox.show_all()
        edit_toolbar.show_all()
예제 #10
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self._selected_image = None

        self.max_participants = 1

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        activity_button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.save_button = ToolButton('image-save')
        self.save_button.set_tooltip(_('Save to Journal'))
        self.save_button.connect('clicked', self._save_to_journal)
        self.save_button.set_sensitive(False)
        self.save_button.show()
        toolbarbox.toolbar.insert(self.save_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbarbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC,
                                   Gtk.PolicyType.AUTOMATIC)
        self.set_canvas(scrolled_window)
        scrolled_window.show()

        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        icon_view = Gtk.IconView.new_with_model(store)
        icon_view.set_selection_mode(Gtk.SelectionMode.SINGLE)
        icon_view.connect('selection-changed', self._clipart_selected, store)
        icon_view.set_pixbuf_column(0)
        rgba = Gdk.RGBA()
        rgba.red, rgba.green, rgba.blue, rgba.alpha = 0.67, 0.67, 0.67, 1.0
        icon_view.override_background_color(Gtk.StateFlags.NORMAL, rgba)
        icon_view.grab_focus()
        scrolled_window.add(icon_view)
        icon_view.show()

        toolbarbox.show_all()
        self.show_all()

        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
        self._notify()

        GObject.idle_add(_fill_clipart_list, store)
예제 #11
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self._selected_image = None

        self.max_participants = 1

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        activity_button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.save_button = ToolButton('image-save')
        self.save_button.set_tooltip(_('Save to Journal'))
        self.save_button.connect('clicked', self._save_to_journal)
        self.save_button.set_sensitive(False)
        self.save_button.show()
        toolbarbox.toolbar.insert(self.save_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbarbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC,
                                   Gtk.PolicyType.AUTOMATIC)
        self.set_canvas(scrolled_window)
        scrolled_window.show()

        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        icon_view = Gtk.IconView.new_with_model(store)
        icon_view.set_selection_mode(Gtk.SelectionMode.SINGLE)
        icon_view.connect('selection-changed', self._clipart_selected, store)
        icon_view.set_pixbuf_column(0)
        rgba = Gdk.RGBA()
        rgba.red, rgba.green, rgba.blue, rgba.alpha = 0.67, 0.67, 0.67, 1.0
        icon_view.override_background_color(Gtk.StateFlags.NORMAL, rgba)
        icon_view.grab_focus()
        scrolled_window.add(icon_view)
        icon_view.show()

        toolbarbox.show_all()
        self.show_all()

        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
        self._notify()

        GObject.idle_add(_fill_clipart_list, store)
예제 #12
0
class JAMClock(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle, False)
        self.set_title('JAMClock')
        # self.set_toolbox(activity.ActivityToolbox(self))

        w = Gdk.Screen.width()
        h = Gdk.Screen.height() - 1 * GRID_CELL_SIZE

        # Start the Game activity
        self.game = Main((w, h))

        # Build the Pygame canvas and start the game running
        # (self.game.run is called when the activity constructor
        # returns).
        self._pygamecanvas = canvas.PygameCanvas(
            self, main=self.game.run, modules=[pygame.display])

        # Note that set_canvas implicitly calls read_file when
        # resuming from the Journal.

        self._pygamecanvas.set_size_request(w, h)
        self.set_canvas(self._pygamecanvas)
        self._pygamecanvas.grab_focus()

        # Build the activity toolbar.
        self.build_toolbar()

    def build_toolbar(self):
        self.toolbar_box = ToolbarBox()
        self.activity_button = ActivityToolbarButton(self)
        self.toolbar_box.toolbar.insert(self.activity_button, 0)
        self.activity_button.show()

        self._separator = Gtk.SeparatorToolItem()
        self._separator.props.draw = False
        self._separator.set_expand(True)
        self.toolbar_box.toolbar.insert(self._separator, -1)
        self._separator.show()

        self.stop = StopButton(self)
        self.toolbar_box.toolbar.insert(self.stop, -1)
        self.stop.show()
        
        self.set_toolbar_box(self.toolbar_box)
        self.toolbar_box.show_all()
        return self.toolbar_box

    def get_run_game(self):
        raise NotImplementedError
        pass

    def salir(self, widget):
        lambda w: Gtk.main_quit()
        sys.exit()
예제 #13
0
    def build_toolbar(self):
        """Build our Activity toolbar for the Sugar system."""

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        easier_button = ToolButton('create-easier')
        easier_button.set_tooltip(_('Easier level'))
        easier_button.connect('clicked', self._easier_button_cb)
        toolbar_box.toolbar.insert(easier_button, -1)

        harder_button = ToolButton('create-harder')
        harder_button.set_tooltip(_('Harder level'))
        harder_button.connect('clicked', self._harder_button_cb)
        toolbar_box.toolbar.insert(harder_button, -1)

        self._risk_button = ToggleToolButton('make-risk')
        self._risk_button.set_tooltip(_('Make risk'))
        if self.state and 'risk' in self.state:
            self._risk_button.set_active(self.state['risk'])
        self._risk_button.connect('toggled', self._make_risk_button_cb)
        toolbar_box.toolbar.insert(self._risk_button, -1)

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        self.show_trail_button = ToggleToolButton('show-trail')
        self.show_trail_button.set_tooltip(_('Show trail'))
        self.show_trail_button.set_active(True)
        self.show_trail_button.connect('toggled', self._toggled_show_trail_cb)
        toolbar_box.toolbar.insert(self.show_trail_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        return toolbar_box
예제 #14
0
    def build_toolbar(self):

        self.max_participants = 1

        toolbox = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, -1)
        activity_button.show()

        pano_toolbar = toolbox.toolbar

        new_button = ToolButton('stock_refresh')
        new_button.set_tooltip(_('New Panorama'))
        new_button.connect('clicked', self.new_event)
        pano_toolbar.insert(new_button, -1)
        new_button.show()

        capture_button = ToolButton('add_capture')
        capture_button.set_tooltip(_('Add a capture to the Panorama'))
        capture_button.connect('clicked', self.capture_event)
        pano_toolbar.insert(capture_button, -1)
        capture_button.show()

        stitch_button = ToolButton('format-columns-triple')
        stitch_button.set_tooltip(_('Stitch Panorama'))
        stitch_button.connect('clicked', self.stitch_event)
        pano_toolbar.insert(stitch_button, -1)
        stitch_button.show()

        stiching_auto = ToolButton('media-playback-start')
        stiching_auto.set_tooltip(_('Enable auto-stitch'))
        stiching_auto.connect('clicked', self.change_stich)
        pano_toolbar.insert(stiching_auto, -1)

        save_button = ToolButton('filesave')
        save_button.set_tooltip(_('Save Panorama'))
        save_button.connect('clicked', self.save_event)
        pano_toolbar.insert(save_button, -1)
        save_button.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        pano_toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        pano_toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbox)

        toolbox.show_all()
예제 #15
0
    def _setup_toolbar(self):
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbarbox.toolbar.insert(ActivityToolbarButton(self), -1)
        toolbarbox.toolbar.insert(StopButton(self), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, 1)

        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
예제 #16
0
    def build_toolbar(self, activity):
        # Prepare Primary Toolbar Container
        toolbar_box = ToolbarBox()

        # Create activity button
        toolbar_box.toolbar.insert(ActivityButton(activity), -1)

        # Video Toggle
        video_toggle_button = ToolButton()
        video_toggle_button.connect("clicked", self.toggle_video)
        toolbar_box.toolbar.insert(video_toggle_button, 1)
        self.toggle_video(video_toggle_button)

        # Audio Toggle
        audio_toggle_button = ToolButton()
        audio_toggle_button.connect("clicked", self.toggle_audio)
        toolbar_box.toolbar.insert(audio_toggle_button, 2)
        self.toggle_audio(audio_toggle_button)

        # Toggle Preview Display Button
        preview_toggle_button = ToolButton()
        preview_toggle_button.connect("clicked",
                                      self.toolbar_toggle_preview_visibility)
        toolbar_box.toolbar.insert(preview_toggle_button, 3)
        self.toolbar_toggle_preview_visibility(preview_toggle_button)

        # Forced Refresh
        reload_video = ToolButton("view-refresh")
        reload_video.set_tooltip_text(_("Reload Video"))
        reload_video.connect("clicked", self.force_redraw)
        toolbar_box.toolbar.insert(reload_video, -1)

        # Push stop button to far right
        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        # Create Share Button
        toolbar_box.toolbar.insert(ShareButton(activity), -1)

        # Create stop button
        toolbar_box.toolbar.insert(StopButton(activity), -1)

        # Add reference to toolbar items
        self.toolbar = toolbar_box.toolbar

        # Display all components & Return
        toolbar_box.show_all()
        return toolbar_box
예제 #17
0
    def build_toolbar(self, activity):
        # Prepare Primary Toolbar Container
        toolbar_box = ToolbarBox();

        # Create activity button
        toolbar_box.toolbar.insert(ActivityButton(activity), -1)

        # Video Toggle
        video_toggle_button = ToolButton()
        video_toggle_button.connect("clicked", self.toggle_video)
        toolbar_box.toolbar.insert(video_toggle_button, 1)
        self.toggle_video(video_toggle_button)

        # Audio Toggle
        audio_toggle_button = ToolButton()
        audio_toggle_button.connect("clicked", self.toggle_audio)
        toolbar_box.toolbar.insert(audio_toggle_button, 2)
        self.toggle_audio(audio_toggle_button)

        # Toggle Preview Display Button
        preview_toggle_button = ToolButton()
        preview_toggle_button.connect("clicked", self.toolbar_toggle_preview_visibility)
        toolbar_box.toolbar.insert(preview_toggle_button, 3)
        self.toolbar_toggle_preview_visibility(preview_toggle_button)

        # Forced Refresh
        reload_video = ToolButton("view-refresh")
        reload_video.set_tooltip_text(_("Reload Video"))
        reload_video.connect("clicked", self.force_redraw)
        toolbar_box.toolbar.insert(reload_video, -1)

        # Push stop button to far right
        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        # Create Share Button
        toolbar_box.toolbar.insert(ShareButton(activity), -1)

        # Create stop button
        toolbar_box.toolbar.insert(StopButton(activity), -1)

        # Add reference to toolbar items
        self.toolbar = toolbar_box.toolbar

        # Display all components & Return
        toolbar_box.show_all()
        return toolbar_box
예제 #18
0
    def __init__(self, handle, parent=None, **kwargs):
        gvr_gtk_glade.window_main.__init__(self)

        self._parent = parent
        self._parent.set_canvas(self)
        self.logger = logging.getLogger("gvr.gvr_gtk.WindowXO")

        # Get and set the sugar toolbar
        toolbarbox = ToolbarBox()
        self._parent.set_toolbar_box(toolbarbox)
        toolbarbox.show_all()

        toolbar = toolbarbox.toolbar

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)

        stop_button = StopButton(self._parent)
        toolbar.insert(stop_button, -1)

        toolbar.show_all()

        # remove seperator and 'quit' menu items as we have the sugar toolbox
        self.imagemenuitem49.destroy()

        # Embed webview as the lessons display
        self.WV = WebView()

        file = os.path.join(utils.get_rootdir(), 'docs', 'lessons', utils.get_locale()[:2], 'html', 'index.html')
        self.logger.debug("Looking for the lessons in %s" % file)
        if not os.path.exists(file):
            self.logger.debug("%s not found, loading default English lessons" % file)
            file = os.path.join(utils.get_rootdir(), 'docs', 'lessons', 'en', 'html', 'index.html')

        self.WV.open('file:///%s' % file)

        scroll = Gtk.ScrolledWindow()
        scroll.add(self.WV)

        vbox = Gtk.VBox(False, 4)
        vbox.pack_start(Widgets.WebToolbar(self.WV), False, False, 2)
        vbox.pack_start(scroll, True, True, 2)
        vbox.show_all()
        self.eventboxlessons.add(vbox)

        self.new()
        self.show_all()
예제 #19
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        #self.set_title('Blender Activity')

        os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (os.path.join(
            bundle_path, 'lib'), os.environ.get('LD_LIBRARY_PATH', ''))
        #os.environ['PATH'] = "%s:%s" % (os.path.join(bundle_path, ARCH, 'bin'), os.environ.get('PATH', ''))

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)
        toolbarbox.show_all()

        button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        button = StopButton(self)
        toolbarbox.toolbar.insert(button, -1)

        self.hbox = Gtk.HBox()
        self.set_canvas(self.hbox)

        self.vt = Vte.Terminal()
        self.vt.connect("child-exited", self._child_exited)
        self.vt.connect("realize", self.start_all)
        self.hbox.pack_start(self.vt, True, True, 0)

        self.vt.set_font(Pango.FontDescription("Monospace 13"))
        self.vt.set_audible_bell(False)

        foreground = Gdk.Color.parse('#000000')[1]
        background = Gdk.Color.parse('#E7E7E7')[1]

        if Vte._version == "2.91":
            foreground = Gdk.RGBA.from_color(foreground)
            background = Gdk.RGBA.from_color(background)

        self.vt.set_colors(foreground, background, [])

        scrollbar = Gtk.VScrollbar.new(self.vt.get_vadjustment())
        self.hbox.pack_start(scrollbar, False, False, 0)

        self.show_all()
    def __init__(self, handle):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle, False)
        self.max_participants = 1

        self._sequence = 0
        self.selected_book = None
        self.queryresults = None
        self._getter = None
        self.show_images = True
        self.languages = {}
        self._lang_code_handler = languagenames.LanguageNames()
        self.catalogs_configuration = {}
        self.catalog_history = []

        if os.path.exists('/etc/get-books.cfg'):
            self._read_configuration('/etc/get-books.cfg')
        else:
            self._read_configuration()

        toolbar_box = ToolbarBox()
        activity_button = ToolButton()
        color = profile.get_color()
        bundle = ActivityBundle(activity.get_bundle_path())
        icon = Icon(file=bundle.get_icon(), xo_color=color)
        activity_button.set_icon_widget(icon)
        activity_button.show()

        toolbar_box.toolbar.insert(activity_button, 0)
        self._add_search_controls(toolbar_box.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        self._books_toolbar = toolbar_box.toolbar

        self._create_controls()

        self.using_powerd = os.access(POWERD_INHIBIT_DIR, os.W_OK)

        self.__book_downloader = self.__image_downloader = None
예제 #21
0
    def build_toolbar(self):
        """Build our Activity toolbar for the Sugar system."""

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        easier_button = ToolButton('create-easier')
        easier_button.set_tooltip(_('Easier level'))
        easier_button.connect('clicked', self._easier_button_cb)
        toolbar_box.toolbar.insert(easier_button, -1)

        harder_button = ToolButton('create-harder')
        harder_button.set_tooltip(_('Harder level'))
        harder_button.connect('clicked', self._harder_button_cb)
        toolbar_box.toolbar.insert(harder_button, -1)

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        self.show_trail_button = ToggleToolButton('show-trail')
        self.show_trail_button.set_tooltip(_('Show trail'))
        self.show_trail_button.set_active(True)
        self.show_trail_button.connect('toggled', self._toggled_show_trail_cb)
        toolbar_box.toolbar.insert(self.show_trail_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        return toolbar_box
    def __init__(self, handle):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle, False)
        self.max_participants = 1

        self._sequence = 0
        self.selected_book = None
        self.queryresults = None
        self._getter = None
        self.show_images = True
        self.languages = {}
        self._lang_code_handler = languagenames.LanguageNames()
        self.catalogs_configuration = {}
        self.catalog_history = []

        if os.path.exists('/etc/get-books.cfg'):
            self._read_configuration('/etc/get-books.cfg')
        else:
            self._read_configuration()

        toolbar_box = ToolbarBox()
        activity_button = ToolButton()
        color = profile.get_color()
        bundle = ActivityBundle(activity.get_bundle_path())
        icon = Icon(file=bundle.get_icon(), xo_color=color)
        activity_button.set_icon_widget(icon)
        activity_button.show()

        toolbar_box.toolbar.insert(activity_button, 0)
        self._add_search_controls(toolbar_box.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        self._books_toolbar = toolbar_box.toolbar

        self._create_controls()

        self.using_powerd = os.access(POWERD_INHIBIT_DIR, os.W_OK)

        self.__book_downloader = self.__image_downloader = None
예제 #23
0
    def __init__(self, handle):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle)
        self._timeout = None

        self.accelerometer = False
        try:
            open(ACCELEROMETER_DEVICE).close()
            self.accelerometer = True
        except:
            pass

        if not self.accelerometer and not self.shared_activity:
            return self._incompatible()

        self.buddies = {}

        canvas = MyCanvas(self)
        self.set_canvas(canvas)
        canvas.show()

        toolbar_box = ToolbarBox()
        self.set_toolbar_box(toolbar_box)

        toolbar_box.toolbar.insert(ActivityButton(self), 0)
        toolbar_box.toolbar.insert(TitleEntry(self), -1)
        toolbar_box.toolbar.insert(DescriptionItem(self), -1)
        toolbar_box.toolbar.insert(ShareButton(self), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        toolbar_box.toolbar.insert(StopButton(self), -1)
        toolbar_box.show_all()

        self._udp = Udp()
        self.hosts = {}

        self._collab = CollabWrapper(self)
        self._collab.message.connect(self.__message_cb)
        self._collab.buddy_joined.connect(self.__buddy_joined_cb)
        self._collab.buddy_left.connect(self.__buddy_left_cb)
        self._collab.setup()

        self._fuse = 1
        self._timeout = GLib.timeout_add(100, self._timeout_cb, canvas)
예제 #24
0
    def crear_toolbars(self):
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
예제 #25
0
    def __init__(self, handle):
        import gi
        from gi.repository import Gtk
        from gi.repository import Gdk
        from gi.repository import GLib
        from gi.repository import Pango
        gi.require_version('Vte', '2.91')
        from gi.repository import Vte

        super(VteActivity, self).__init__(handle, create_jobject=False)
        self.__source_object_id = None

        # creates vte widget
        self._vte = Vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = ToolbarBox(self)
            self.set_toolbar_box(toolbox)

            self._vte.set_size(30, 5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(Pango.FontDescription(font))
            self._vte.set_colors(Gdk.color_parse('#E7E7E7'),
                                 Gdk.color_parse('#000000'), [])

            vtebox = Gtk.HBox()
            vtebox.pack_start(self._vte, True, True, 0)
            vtesb = Gtk.VScrollbar()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show_all()
            vtebox.show_all()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        self._pid = self._vte.spawn_sync(Vte.PtyFlags.DEFAULT, bundle_path, [
            '/bin/sh', '-c',
            'python %s/LemonadeStand.py --width=1200 \
                --height=900 --font=36' % bundle_path
        ], ["PYTHONPATH=%s/library" % bundle_path],
                                         GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                                         None, None)
예제 #26
0
    def crear_toolbars(self):
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
예제 #27
0
    def __init__(self, handle):
        from gi.repository import Gtk
        from gi.repository import Gdk
        from gi.repository import GLib
        from gi.repository import Pango
        from gi.repository import Vte

        super(VteActivity, self).__init__(handle, create_jobject=False)
        self.__source_object_id = None

        # creates vte widget
        self._vte = Vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = ToolbarBox(self)
            toolbar = toolbox.toolbar
            self.set_toolbar_box(toolbox)

            self._vte.set_size(30, 5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(Pango.FontDescription(font))
            self._vte.set_colors(Gdk.color_parse('#E7E7E7'),
                                 Gdk.color_parse('#000000'),
                                 [])

            vtebox = Gtk.HBox()
            vtebox.pack_start(self._vte, True, True, 0)
            vtesb = Gtk.VScrollbar()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show_all()
            vtebox.show_all()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        self._pid = self._vte.spawn_sync(
            Vte.PtyFlags.DEFAULT, bundle_path, [
                '/bin/sh', '-c', 'python %s/LemonadeStand.py --width=1200 --height=900 --font=36' %
                bundle_path], [
                "PYTHONPATH=%s/library" %
                bundle_path], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
예제 #28
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        #self.set_title('Blender Activity')

        os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (os.path.join(bundle_path, ARCH, 'lib'), os.environ.get('LD_LIBRARY_PATH', ''))
        #os.environ['PATH'] = "%s:%s" % (os.path.join(bundle_path, ARCH, 'bin'), os.environ.get('PATH', ''))

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)
        toolbarbox.show_all()

        button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        button = StopButton(self)
        toolbarbox.toolbar.insert(button, -1)

        self.hbox = Gtk.HBox()
        self.set_canvas(self.hbox)

        self.vt = Vte.Terminal()
        self.vt.connect("child-exited", self._child_exited)
        self.vt.connect("realize", self.start_all)
        self.hbox.pack_start(self.vt, True, True, 0)

        self.vt.set_font(Pango.FontDescription("Monospace 13"))
        self.vt.set_audible_bell(False)

        foreground = Gdk.Color.parse('#000000')[1]
        background = Gdk.Color.parse('#E7E7E7')[1]
        self.vt.set_colors(Gdk.RGBA.from_color(foreground),
                           Gdk.RGBA.from_color(background),
                           [])

        scrollbar = Gtk.VScrollbar.new(self.vt.get_vadjustment())
        self.hbox.pack_start(scrollbar, False, False, 0)

        self.show_all()
예제 #29
0
class HelpTemplate(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle, create_jobject=False)

        #following are essential for interface to Help
        self.help_x11 = None
        self.handle = handle
        self.help = Help(self)

        self.toolbarbox = ToolbarBox()
        self.toolbarbox.show_all()

        toolbar = Gtk.Toolbar()
        toolbar.insert(ToolbarButton(page=toolbar, icon_name='help-about'), -1)
        toolbar.show()

        label = Gtk.Button('Help Template')
        label.show()
        self.set_canvas(label)

        self.set_toolbar_box(self.toolbarbox)

    def _toolbar_changed_cb(self, widget, tab_no):
        if tab_no == HELP_TAB:
            self.help_selected()

    def set_toolbar(self, tab):
        self.toolbox.set_current_toolbar(tab)

    def py_stop(self):
        self.__stop_clicked_cb(None)

    def __stop_clicked_cb(self, button):
        _logger.debug('caught stop clicked call back')
        self.close(skip_save=True)

    ################  Help routines
    def help_selected(self):
        """
        if help is not created in a gtk.mainwindow then create it
        else just switch to that viewport
        """
        self.help.activate_help()
예제 #30
0
    def build_toolbar(self):
        # Prepare Primary Toolbar Container
        toolbar_box = ToolbarBox();

        # Create activity button
        toolbar_box.toolbar.insert(ActivityButton(self.activity), -1)

        # Storage for Toggle Buttons
        self.settings_buttons = {}

        # Video Toggle
        self.settings_buttons["toggle_video"] = ToolButton()
        self.settings_buttons["toggle_video"].connect("clicked", self.toggle_video)
        toolbar_box.toolbar.insert(self.settings_buttons["toggle_video"], -1)

        # Audio Toggle
        self.settings_buttons["toggle_audio"] = ToolButton()
        self.settings_buttons["toggle_audio"].connect("clicked", self.toggle_audio)
        toolbar_box.toolbar.insert(self.settings_buttons["toggle_audio"], -1)

        # Forced Refresh
        reload_video = ToolButton("view-refresh")
        reload_video.set_tooltip_text(_("Reload Video"))
        reload_video.connect("clicked", self.force_redraw)
        toolbar_box.toolbar.insert(reload_video, -1)

        # Push stop button to far right
        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        # Create stop button
        toolbar_box.toolbar.insert(StopButton(self.activity), -1)

        # Run Toggles
        self.run_toggles()

        # Display all components & Return
        toolbar_box.show_all()
        return toolbar_box
예제 #31
0
    def __init__(self, handle):
        print "running activity init", handle
        activity.Activity.__init__(self, handle)
        print "activity running"

        self.set_title('Hello World')

        # Creates the Toolbox. It contains the Activity Toolbar, which is the
        # bar that appears on every Sugar window and contains essential
        # functionalities, such as the 'Collaborate' and 'Close' buttons.
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbox)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        button = StopButton(self)
        toolbarbox.toolbar.insert(separator, -1)

        toolbarbox.show_all()

        # Creates a new button with the label "Hello World".
        self.button = Gtk.Button("Hello World")

        # When the button receives the "clicked" signal, it will call the
        # function hello() passing it None as its argument.  The hello()
        # function is defined above.
        self.button.connect("clicked", self.hello, None)

        # Set the button to be our canvas. The canvas is the main section of
        # every Sugar Window. It fills all the area below the toolbox.
        self.set_canvas(self.button)

        # The final step is to display this newly created widget.
        self.button.show()

        print "AT END OF THE CLASS"
예제 #32
0
    def build_toolbar(self):

        toolbox = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, -1)
        activity_button.show()

        barra = toolbox.toolbar

        separator2 = Gtk.SeparatorToolItem()
        separator2.props.draw = False
        separator2.set_expand(True)
        barra.insert(separator2, -1)

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        barra.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbox)

        toolbox.show_all()
예제 #33
0
    def _make_toolbars(self):
        """Prepare and set the toolbars of the activity.

        Load and show icons. Associate them to the call back methods.
        """
        self.max_participants = 1
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_button.show()
        toolbar_box.toolbar.insert(activity_button, 0)

        self._add_clock_controls(toolbar_box.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        return toolbar_box
예제 #34
0
    def _make_toolbars(self):
        """Prepare and set the toolbars of the activity.

        Load and show icons. Associate them to the call back methods.
        """
        self.max_participants = 1
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_button.show()
        toolbar_box.toolbar.insert(activity_button, 0)

        self._add_clock_controls(toolbar_box.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        return toolbar_box
예제 #35
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self.set_title('FotoToon')

        self._max_participants = 1
        self.page = None

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page
        toolbar_box.toolbar.insert(activity_button, 0)

        edit_toolbar_btn = ToolbarButton()
        edit_toolbar = Gtk.Toolbar()
        edit_toolbar_btn.props.page = edit_toolbar
        edit_toolbar_btn.props.icon_name = 'toolbar-edit'
        edit_toolbar_btn.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar_btn, -1)

        view_toolbar_btn = ToolbarButton()
        view_toolbar = Gtk.Toolbar()
        view_toolbar_btn.props.page = view_toolbar
        view_toolbar_btn.props.icon_name = 'toolbar-view'
        view_toolbar_btn.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar_btn, -1)

        slideview_btn = ToggleToolButton('slideshow')
        slideview_btn.set_tooltip(_('Slideshow'))
        slideview_btn.set_active(False)
        slideview_btn.connect('clicked', self._switch_view_mode, False)
        view_toolbar.insert(slideview_btn, -1)
        slideview_btn.show()

        slideview_timings_btn = ToggleToolButton('slideshow-stopwatch')
        slideview_timings_btn.set_tooltip(_('Slideshow with Timings'))
        slideview_timings_btn.set_active(False)
        slideview_timings_btn.connect('clicked', self._switch_view_mode, True)
        view_toolbar.insert(slideview_timings_btn, -1)
        slideview_timings_btn.show()

        time_button = ToolButton('stopwatch')
        time_button.set_tooltip(_('Set Image Duration in Slideshow (Seconds)'))
        view_toolbar.insert(time_button, -1)
        time_button.show()

        self._time_spin = Gtk.SpinButton.new_with_range(MIN_TIME, MAX_TIME, 1)
        self._time_spin.connect('value-changed', self.__time_spin_changed_cb)
        self._time_spin.props.value = DEFAULT_TIME
        self._time_spin.props.update_policy = \
            Gtk.SpinButtonUpdatePolicy.IF_VALID

        palette = time_button.get_palette()
        palette.connect('popup', self.__time_button_popup_cb)
        time_button.connect(
            'clicked', lambda *args:
            palette.popup(immediate=True, state=Palette.SECONDARY))

        alignment = Gtk.Alignment()
        alignment.set_padding(style.DEFAULT_PADDING, style.DEFAULT_PADDING,
                              style.DEFAULT_PADDING, style.DEFAULT_PADDING)
        alignment.add(self._time_spin)
        self._time_spin.show()
        palette.set_content(alignment)
        alignment.show()

        fullscreen_btn = ToolButton('view-fullscreen')
        fullscreen_btn.set_tooltip(_('Fullscreen'))
        fullscreen_btn.props.accelerator = '<Alt>Return'
        fullscreen_btn.connect('clicked', lambda w: self.fullscreen())
        view_toolbar.insert(fullscreen_btn, -1)
        fullscreen_btn.show()

        self.set_toolbar_box(toolbar_box)

        toolbar = toolbar_box.toolbar

        self.page = Page()

        self.globes_manager = GlobesManager(toolbar, edit_toolbar, self)

        # fonts
        self._text_button = ToolbarButton()
        self._text_button.props.page = TextToolbar(self.page)
        self._text_button.props.icon_name = 'format-text-size'
        self._text_button.props.label = _('Text')
        self._toolbar_box.toolbar.insert(self._text_button, -1)

        reorder_img_btn = ToolButton('thumbs-view')
        reorder_img_btn.set_icon_name('thumbs-view')
        reorder_img_btn.set_tooltip(_('Change image order'))
        reorder_img_btn.connect('clicked', self.__image_order_cb)
        edit_toolbar.insert(reorder_img_btn, -1)
        reorder_img_btn.show()

        bgchange = ToolButton(icon_name='contract-coordinates')
        bgchange.set_tooltip(_('Edit background image'))
        bgchange.connect('clicked', self.__bgchange_clicked_cb)
        edit_toolbar.insert(bgchange, -1)
        bgchange.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)

        toolbar_box.toolbar.insert(separator, -1)

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()

        # add export button

        separator_2 = Gtk.SeparatorToolItem()
        separator_2.show()
        activity_toolbar.insert(separator_2, -1)

        self.bt_save_as_image = ToolButton()
        self.bt_save_as_image.props.icon_name = 'save-as-image'
        self.bt_save_as_image.connect('clicked', self.write_image)
        self.bt_save_as_image.set_tooltip(_('Save as Image'))
        activity_toolbar.insert(self.bt_save_as_image, -1)
        self.bt_save_as_image.show()

        save_as_pdf = ToolButton()
        save_as_pdf.props.icon_name = 'save-as-pdf'
        save_as_pdf.connect('clicked', self._save_as_pdf)
        save_as_pdf.set_tooltip(_('Save as a Book (PDF)'))
        activity_toolbar.insert(save_as_pdf, -1)
        save_as_pdf.show()

        save_as_ogg = ToolButton()
        save_as_ogg.props.icon_name = 'save-as-ogg'
        save_as_ogg.connect('clicked', self.__save_as_ogg_cb)
        save_as_ogg.set_tooltip(_('Save as a Movie (OGG)'))
        activity_toolbar.insert(save_as_ogg, -1)
        save_as_ogg.show()

        activity_button.page.title.connect("focus-in-event", self.on_title)

        scrolled = Gtk.ScrolledWindow()
        # scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
        scrolled.add_with_viewport(self.page)
        scrolled.set_kinetic_scrolling(False)
        scrolled.show_all()

        self._slideview = SlideView(self)
        self._slideview.show_all()

        self._notebook = Gtk.Notebook()
        self._notebook.set_show_tabs(False)
        self._notebook.append_page(scrolled, None)
        self._notebook.append_page(self._slideview, None)
        self._notebook.show_all()

        if self._jobject.file_path is None or self._jobject.file_path == '':
            empty_widget = EmptyWidget()
            empty_widget.connect('choose-image', self.__add_image)
            self.set_canvas(empty_widget)
        else:
            self.set_canvas(self._notebook)

        self.show()
        self.metadata['mime_type'] = 'application/x-fototoon-activity'

        self.page.empty_page = handle.object_id is None
        self._key_press_signal_id = None
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        if HASTOOLBARBOX:
            self.max_participants = 1
            toolbar_box = ToolbarBox()
            self.set_toolbar_box(toolbar_box)
            activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)

            separator = Gtk.SeparatorToolItem()
            separator.props.draw = True
            activity_button.props.page.insert(separator, -1)
            separator.show()

            tool = ToolButton('pdf-export')
            tool.set_tooltip(_('Portable Document Format (PDF)'))
            tool.connect('clicked', self.__export_pdf_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolButton('png-export')
            tool.set_tooltip(_('Portable Network Graphic (PNG)'))
            tool.connect('clicked', self.__export_png_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolbarButton()
            self.edit_toolbar = EditToolbar(self)
            tool.props.page = self.edit_toolbar
            tool.props.icon_name = 'toolbar-edit'
            ##tool.props.label = _('Edit'),
            toolbar_box.toolbar.insert(tool, -1)

            #self._undo = UndoManager.UndoManager(self,
            #                                     self.edit_toolbar.undo.child,
            #                                     self.edit_toolbar.redo.child)

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo,
                                                 self.edit_toolbar.redo)

            self.__build_main_canvas_area()

            tool = ToolbarButton()
            tool.props.page = ViewToolbar(self._main_area)
            tool.props.icon_name = 'toolbar-view'
            tool.props.label = _('View')
            toolbar_box.toolbar.insert(tool, -1)

            tool = ToolbarButton()
            self.text_format_toolbar = TextAttributesToolbar(self._main_area)
            tool.props.page = self.text_format_toolbar
            tool.props.icon_name = 'toolbar-text'
            tool.props.label = _('Text')
            toolbar_box.toolbar.insert(tool, -1)
            # self._main_area.set_text_attributes(self.text_format_toolbar)

            self.thought_toolbar = ToolbarButton()
            self.thought_toolbar.props.page = ThoughtsToolbar(self)
            self.thought_toolbar.props.icon_name = 'thought'
            self.thought_toolbar.props.label = _('Thought Type')
            toolbar_box.toolbar.insert(self.thought_toolbar, -1)

            self.action_buttons = ActionButtons(self)

            toolbar_box.show_all()

        else:
            # Use old <= 0.84 toolbar design
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)

            activity_toolbar = toolbox.get_activity_toolbar()
            keep_palette = activity_toolbar.keep.get_palette()

            menu_item = MenuItem(_('Portable Document Format (PDF)'))
            menu_item.connect('activate', self.__export_pdf_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            menu_item = MenuItem(_('Portable Network Graphic (PNG)'))
            menu_item.connect('activate', self.__export_png_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            self.edit_toolbar = EditToolbar(self)
            toolbox.add_toolbar(_('Edit'), self.edit_toolbar)
            separator = Gtk.SeparatorToolItem()
            self.edit_toolbar.insert(separator, 0)
            self.edit_toolbar.show()

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo.child,
                                                 self.edit_toolbar.redo.child)

            self.__build_main_canvas_area()

            view_toolbar = ViewToolbar(self._main_area)
            toolbox.add_toolbar(_('View'), view_toolbar)

            activity_toolbar = toolbox.get_activity_toolbar()
            activity_toolbar.share.props.visible = False
            toolbox.set_current_toolbar(1)

        self.show_all()

        self.__configure_cb(None)

        self._mode = MMapArea.MODE_TEXT
        self._main_area.set_mode(self._mode)
        self.set_focus_child(self._main_area)
예제 #37
0
    def __init__(self, handle):
        pservice = presenceservice.get_instance()
        self.owner = pservice.get_owner()

        self._ebook_mode_detector = EbookModeDetector()

        self.chatbox = ChatBox(self.owner,
                               self._ebook_mode_detector.get_ebook_mode())
        self.chatbox.connect('open-on-journal', self.__open_on_journal)
        self.chatbox.connect('new-message',
                             self._search_entry_on_new_message_cb)

        super(Chat, self).__init__(handle)

        self._entry = None
        self._has_alert = False
        self._has_osk = False

        self._setup_canvas()

        self._entry.grab_focus()

        toolbar_box = ToolbarBox()
        self.set_toolbar_box(toolbar_box)

        self._activity_toolbar_button = ActivityToolbarButton(self)
        self._activity_toolbar_button.connect('clicked', self._fixed_resize_cb)

        toolbar_box.toolbar.insert(self._activity_toolbar_button, 0)
        self._activity_toolbar_button.show()

        self.search_entry = iconentry.IconEntry()
        self.search_entry.set_size_request(Gdk.Screen.width() / 3, -1)
        self.search_entry.set_icon_from_name(iconentry.ICON_ENTRY_PRIMARY,
                                             'entry-search')
        self.search_entry.add_clear_button()
        self.search_entry.connect('activate', self._search_entry_activate_cb)
        self.search_entry.connect('changed', self._search_entry_activate_cb)

        self.connect('key-press-event', self._search_entry_key_press_cb)

        self._search_item = Gtk.ToolItem()
        self._search_item.add(self.search_entry)
        toolbar_box.toolbar.insert(self._search_item, -1)

        self._search_prev = ToolButton('go-previous-paired')
        self._search_prev.set_tooltip(_('Previous'))
        self._search_prev.props.accelerator = "<Shift><Ctrl>g"
        self._search_prev.connect('clicked', self._search_prev_cb)
        self._search_prev.props.sensitive = False
        toolbar_box.toolbar.insert(self._search_prev, -1)

        self._search_next = ToolButton('go-next-paired')
        self._search_next.set_tooltip(_('Next'))
        self._search_next.props.accelerator = "<Ctrl>g"
        self._search_next.connect('clicked', self._search_next_cb)
        self._search_next.props.sensitive = False
        toolbar_box.toolbar.insert(self._search_next, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)
        toolbar_box.show_all()

        # Chat is room or one to one:
        self._chat_is_room = False
        self.text_channel = None

        if _HAS_SOUND:
            self.element = Gst.ElementFactory.make('playbin', 'Player')

        if self.shared_activity:
            # we are joining the activity following an invite
            self._alert(_('Off-line'), _('Joining the Chat.'))
            self._entry.props.placeholder_text = \
                _('Please wait for a connection before starting to chat.')
            self.connect('joined', self._joined_cb)
            if self.get_shared():
                # we have already joined
                self._joined_cb(self)
        elif handle.uri:
            # XMPP non-sugar3 incoming chat, not sharable
            self._activity_toolbar_button.props.page.share.props.visible = \
                False
            self._one_to_one_connection(handle.uri)
        else:
            # we are creating the activity
            if not self.metadata or self.metadata.get(
                    'share-scope', activity.SCOPE_PRIVATE) == \
                    activity.SCOPE_PRIVATE:
                # if we are in private session
                self._alert(_('Off-line'), _('Share, or invite someone.'))
            else:
                # resume of shared activity from journal object without invite
                self._entry.props.placeholder_text = \
                    _('Please wait for a connection before starting to chat.')
            self.connect('shared', self._shared_cb)
예제 #38
0
    def __init__(self, handle):
        # Initialize the parent
        Activity.__init__(self, handle)

        logger.debug('Initiating PlayGo')

        self.size = DEFAULT_SIZE
        self.komi = DEFAULT_KOMI

        # Set the activity toolbarbox
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbarbox.toolbar.insert(ActivityToolbarButton(self), -1)
        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.gameToolbar = GameToolbar(self)
        self.gameToolbar.connect('game-restart', self.restart_game)
        self.gameToolbar.connect('game-board-size', self.board_size_change)
        self.gameToolbar.connect('ai-activated', self.ai_activated_cb)
        self.gameToolbar.connect('ai-deactivated', self.ai_deactivated_cb)
        toolbarbox.toolbar.insert(
            ToolbarButton(page=self.gameToolbar, icon_name='txt'), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        toolbarbox.toolbar.insert(StopButton(self), -1)

        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
        self.gameToolbar.show_all()

        # Initialize the game
        self.game = GoGame(self.size)
        self.CurrentColor = 'B'
        self.PlayerColor = 'B'
        self.pass_count = 0
        self.ai_activated = False
        self.set_up_ui()

        if not handle.object_id:
            self.infopanel.show(_('Welcome to PlayGo!'))
        else:
            self.show_score()

        self.lastX = -1
        self.lastY = -1

        # Set keypad actions
        self._key_actions = {
            'KP_Up': 'move_up',
            'KP_Right': 'move_right',
            'KP_Down': 'move_down',
            'KP_Left': 'move_left',
            'KP_Home': 'place_stone',
            'KP_Next': 'undo',
            'KP_End': 'pass'
        }

        # Set up collaboration
        self.collaboration = CollaborationWrapper(self, self.buddy_joined,
                                                  self.buddy_left, self.Play,
                                                  self.game.undostack,
                                                  self.bootstrap)

        self.connect('shared', self.collaboration._shared_cb)
        if self.get_shared_activity():
            # We are joining the activity
            self.connect('joined', self.collaboration._joined_cb)
            if self.get_shared():
                # We've already joined
                self.collaboration._joined_cb()
예제 #39
0
    def _build_toolbox(self):
        toolbar_box = ToolbarBox()

        self.max_participants = 1

        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page

        self._toolbar = toolbar_box.toolbar
        self._toolbar.insert(activity_button, -1)

        self._secondary_toolbar = Gtk.Toolbar()
        self._secondary_toolbar_button = ToolbarButton(
            page=self._secondary_toolbar,
            icon_name='system-search')
        self._secondary_toolbar.show()
        self._toolbar.insert(self._secondary_toolbar_button, -1)
        self._secondary_toolbar_button.hide()

        show_list = ToggleToolButton('view-list')
        show_list.set_active(True)
        show_list.set_tooltip(_('Show list of files'))
        show_list.connect('toggled', self._list_toggled_cb)
        self._toolbar.insert(show_list, -1)
        show_list.show()

        copy = CopyButton()
        copy.connect('clicked', self.__copy_clicked_cb)
        self._toolbar.insert(copy, -1)

        wrap_btn = ToggleToolButton("format-wrap")
        wrap_btn.set_tooltip(_('Word Wrap'))
        wrap_btn.connect('clicked', self._wrap_cb)
        self._toolbar.insert(wrap_btn, -1)

        self.search_entry = iconentry.IconEntry()
        self.search_entry.set_size_request(Gdk.Screen.width() / 3, -1)
        self.search_entry.set_icon_from_name(
            iconentry.ICON_ENTRY_PRIMARY, 'entry-search')
        self.search_entry.add_clear_button()
        self.search_entry.connect('activate', self._search_entry_activate_cb)
        self.search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_item = Gtk.ToolItem()
        self._search_item.add(self.search_entry)
        self._toolbar.insert(self._search_item, -1)

        self._search_prev = ToolButton('go-previous-paired')
        self._search_prev.set_tooltip(_('Previous'))
        self._search_prev.connect('clicked', self._search_prev_cb)
        self._toolbar.insert(self._search_prev, -1)

        self._search_next = ToolButton('go-next-paired')
        self._search_next.set_tooltip(_('Next'))
        self._search_next.connect('clicked', self._search_next_cb)
        self._toolbar.insert(self._search_next, -1)

        self._update_search_buttons()

        self.collector_palette = CollectorPalette(self)
        collector_btn = ToolButton('log-export')
        collector_btn.set_palette(self.collector_palette)
        collector_btn.connect('clicked', self._logviewer_cb)
        collector_btn.show()
        activity_toolbar.insert(collector_btn, -1)

        self._delete_btn = ToolButton('list-remove')
        self._delete_btn.set_tooltip(_('Delete Log File'))
        self._delete_btn.connect('clicked', self._delete_log_cb)
        self._toolbar.insert(self._delete_btn, -1)

        self._separator = Gtk.SeparatorToolItem()
        self._separator.set_expand(True)
        self._separator.set_draw(False)
        self._toolbar.insert(self._separator, -1)

        self._stop_btn = StopButton(self)
        self._toolbar.insert(self._stop_btn, -1)

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)
예제 #40
0
파일: activity.py 프로젝트: godiard/physics
    def build_toolbar(self):
        self.max_participants = 4

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        create_toolbar = ToolbarButton()
        create_toolbar.props.page = Gtk.Toolbar()
        create_toolbar.props.icon_name = 'magicpen'
        create_toolbar.props.label = _('Create')
        toolbar_box.toolbar.insert(create_toolbar, -1)
        self._insert_create_tools(create_toolbar)

        self._insert_stop_play_button(toolbar_box.toolbar)

        clear_trace = ToolButton('clear-trace')
        clear_trace.set_tooltip(_('Clear Trace Marks'))
        clear_trace.set_accelerator(_('<ctrl>x'))
        clear_trace.connect('clicked', self.clear_trace_cb)
        clear_trace.set_sensitive(False)
        toolbar_box.toolbar.insert(clear_trace, -1)
        clear_trace.show()
        self.clear_trace = clear_trace

        self._insert_clear_all_button(toolbar_box.toolbar)

        load_example = ToolButton('load-sample')
        load_example.set_tooltip(_('Show sample projects'))
        load_example.connect('clicked', self._create_store)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(load_example, -1)
        load_example.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)
        stop.show()

        separator = Gtk.SeparatorToolItem()
        activity_button.props.page.insert(separator, -1)
        separator.show()

        export_json = ToolButton('save-as-json')
        export_json.set_tooltip(_('Export tracked objects to journal'))
        export_json.connect('clicked', self._export_json_cb)
        activity_button.props.page.insert(export_json, -1)
        export_json.show()

        export_csv = ToolButton('save-as-csv')
        export_csv.set_tooltip(_('Export tracked objects to journal'))
        export_csv.connect('clicked', self._export_csv_cb)
        activity_button.props.page.insert(export_csv, -1)
        export_csv.show()

        load_project = ToolButton('load-project')
        load_project.set_tooltip(_('Load project from journal'))
        load_project.connect('clicked', self._load_project)
        activity_button.props.page.insert(load_project, -1)
        load_project.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        create_toolbar.set_expanded(True)
        return toolbar_box
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self.set_title('FotoToon')

        self._max_participants = 1

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page
        toolbar_box.toolbar.insert(activity_button, 0)

        edit_toolbar_btn = ToolbarButton()
        edit_toolbar = Gtk.Toolbar()
        edit_toolbar_btn.props.page = edit_toolbar
        edit_toolbar_btn.props.icon_name = 'toolbar-edit'
        edit_toolbar_btn.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar_btn, -1)

        view_toolbar_btn = ToolbarButton()
        view_toolbar = Gtk.Toolbar()
        view_toolbar_btn.props.page = view_toolbar
        view_toolbar_btn.props.icon_name = 'toolbar-view'
        view_toolbar_btn.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar_btn, -1)

        slideview_btn = ToggleToolButton('slideshow')
        slideview_btn.set_tooltip(_('Slideshow'))
        slideview_btn.set_active(False)
        view_toolbar.insert(slideview_btn, -1)
        slideview_btn.show()

        fullscreen_btn = ToolButton('view-fullscreen')
        fullscreen_btn.set_tooltip(_('Fullscreen'))
        fullscreen_btn.props.accelerator = '<Alt>Return'
        fullscreen_btn.connect('clicked', lambda w: self.fullscreen())
        view_toolbar.insert(fullscreen_btn, -1)
        fullscreen_btn.show()

        self.set_toolbar_box(toolbar_box)

        toolbar = toolbar_box.toolbar

        self.page = Page()

        self.globes_manager = GlobesManager(toolbar, edit_toolbar, self)

        # fonts
        text_button = ToolbarButton()
        text_button.props.page = TextToolbar(self.page)
        text_button.props.icon_name = 'format-text-size'
        text_button.props.label = _('Text')
        slideview_btn.connect('clicked', self._switch_view_mode, text_button)
        toolbar_box.toolbar.insert(text_button, -1)

        reorder_img_btn = ToolButton('thumbs-view')
        reorder_img_btn.set_icon_name('thumbs-view')
        reorder_img_btn.set_tooltip(_('Change image order'))
        reorder_img_btn.connect('clicked', self.__image_order_cb)
        edit_toolbar.insert(reorder_img_btn, -1)
        reorder_img_btn.show()

        bgchange = ToolButton(icon_name='contract-coordinates')
        bgchange.set_tooltip(_('Edit background image'))
        bgchange.connect('clicked', self.__bgchange_clicked_cb)
        edit_toolbar.insert(bgchange, -1)
        bgchange.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)

        toolbar_box.toolbar.insert(separator, -1)

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()

        # add export button

        separator_2 = Gtk.SeparatorToolItem()
        separator_2.show()
        activity_toolbar.insert(separator_2, -1)

        self.bt_save_as_image = ToolButton()
        self.bt_save_as_image.props.icon_name = 'save-as-image'
        self.bt_save_as_image.connect('clicked', self.write_image)
        self.bt_save_as_image.set_tooltip(_('Save as Image'))
        activity_toolbar.insert(self.bt_save_as_image, -1)
        self.bt_save_as_image.show()

        save_as_pdf = ToolButton()
        save_as_pdf.props.icon_name = 'save-as-pdf'
        save_as_pdf.connect('clicked', self._save_as_pdf)
        save_as_pdf.set_tooltip(_('Save as a Book (PDF)'))
        activity_toolbar.insert(save_as_pdf, -1)
        save_as_pdf.show()

        activity_button.page.title.connect("focus-in-event", self.on_title)

        scrolled = Gtk.ScrolledWindow()
        #scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
        scrolled.add_with_viewport(self.page)
        scrolled.set_kinetic_scrolling(False)
        scrolled.show_all()

        self._slideview = SlideView(self)
        self._slideview.show_all()

        self._notebook = Gtk.Notebook()
        self._notebook.set_show_tabs(False)
        self._notebook.append_page(scrolled, None)
        self._notebook.append_page(self._slideview, None)
        self._notebook.show_all()

        self.set_canvas(self._notebook)
        self.show()
        self.metadata['mime_type'] = 'application/x-fototoon-activity'

        self.page.empty_page = handle.object_id is None
        self._key_press_signal_id = None
예제 #42
0
    def _build_toolbox(self):
        toolbar_box = ToolbarBox()

        self.max_participants = 1

        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page

        self._toolbar = toolbar_box.toolbar
        self._toolbar.insert(activity_button, -1)

        self._secondary_toolbar = Gtk.Toolbar()
        self._secondary_toolbar_button = ToolbarButton(
            page=self._secondary_toolbar,
            icon_name='system-search')
        self._secondary_toolbar.show()
        self._toolbar.insert(self._secondary_toolbar_button, -1)
        self._secondary_toolbar_button.hide()

        show_list = ToggleToolButton('view-list')
        show_list.set_active(True)
        show_list.set_tooltip(_('Show list of files'))
        show_list.connect('toggled', self._list_toggled_cb)
        self._toolbar.insert(show_list, -1)
        show_list.show()

        copy = CopyButton()
        copy.connect('clicked', self.__copy_clicked_cb)
        self._toolbar.insert(copy, -1)

        wrap_btn = ToggleToolButton("format-wrap")
        wrap_btn.set_tooltip(_('Word Wrap'))
        wrap_btn.connect('clicked', self._wrap_cb)
        self._toolbar.insert(wrap_btn, -1)

        self.search_entry = iconentry.IconEntry()
        self.search_entry.set_size_request(Gdk.Screen.width() / 3, -1)
        self.search_entry.set_icon_from_name(
            iconentry.ICON_ENTRY_PRIMARY, 'entry-search')
        self.search_entry.add_clear_button()
        self.search_entry.connect('activate', self._search_entry_activate_cb)
        self.search_entry.connect('changed', self._search_entry_changed_cb)
        self._search_item = Gtk.ToolItem()
        self._search_item.add(self.search_entry)
        self._toolbar.insert(self._search_item, -1)

        self._search_prev = ToolButton('go-previous-paired')
        self._search_prev.set_tooltip(_('Previous'))
        self._search_prev.connect('clicked', self._search_prev_cb)
        self._toolbar.insert(self._search_prev, -1)

        self._search_next = ToolButton('go-next-paired')
        self._search_next.set_tooltip(_('Next'))
        self._search_next.connect('clicked', self._search_next_cb)
        self._toolbar.insert(self._search_next, -1)

        self._update_search_buttons()

        self.collector_palette = CollectorPalette(self)
        collector_btn = ToolButton('log-export')
        collector_btn.set_palette(self.collector_palette)
        collector_btn.connect('clicked', self._logviewer_cb)
        collector_btn.show()
        activity_toolbar.insert(collector_btn, -1)

        self._delete_btn = ToolButton('list-remove')
        self._delete_btn = ToolButton('list-remove', accelerator='<ctrl>d')
        self._delete_btn.set_tooltip(_('Delete Log File'))
        self._delete_btn.connect('clicked', self._delete_log_cb)
        self._toolbar.insert(self._delete_btn, -1)

        self._separator = Gtk.SeparatorToolItem()
        self._separator.set_expand(True)
        self._separator.set_draw(False)
        self._toolbar.insert(self._separator, -1)

        self._stop_btn = StopButton(self)
        self._toolbar.insert(self._stop_btn, -1)

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)
class TypingTurtle(sugar3.activity.activity.Activity):
    def __init__(self, handle):
        sugar3.activity.activity.Activity.__init__(self, handle)
        self.set_title(_("Typing Turtle"))
        self.max_participants = 1

        self.build_toolbox()

        self.screens = []
        self.screenbox = Gtk.VBox()

        self.nick = profile.get_nick_name()

        self.wordlist = []

        # All data which is saved in the Journal entry is placed in this dictionary.
        self.data = {'motd': 'welcome', 'history': [], 'medals': {}}

        # This calls the read_file method when restoring from the Journal.
        self.set_canvas(self.screenbox)

        # Start with the main screen.
        self.mainscreen = mainscreen.MainScreen(self)
        self.push_screen(self.mainscreen)

        self.show_all()

        self.editorbtn = sugar3.graphics.toolbutton.ToolButton('view-source')
        self.editorbtn.set_tooltip(_("Edit Lessons"))
        self.editorbtn.connect('clicked', self.editor_clicked_cb)

        activity_toolbar = self.toolbar_box.toolbar
        activity_toolbar.insert(self.editorbtn, 1)

        self.editorbtn.show_all()

    def build_toolbox(self):
        self.toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        self.toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self.toolbar_box.toolbar.insert(separator, -1)

        self.toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(self.toolbar_box)
        self.toolbar_box.show_all()

    def editor_clicked_cb(self, btn):
        self.push_screen(
            editlessonlistscreen.EditLessonListScreen(self,
                                                      self.mainscreen.lessons))

    def push_screen(self, screen):
        if len(self.screens):
            oldscreen = self.screens[-1]

            try:
                oldscreen.leave()
            except:
                pass

            self.screenbox.remove(oldscreen)

        self.screenbox.pack_start(screen, True, True, 0)
        self.screens.append(screen)

        try:
            screen.enter()
        except:
            pass

    def pop_screen(self):
        oldscreen = self.screens.pop()

        try:
            oldscreen.leave()
        except:
            pass

        self.screenbox.remove(oldscreen)

        if len(self.screens):
            screen = self.screens[-1]

            try:
                screen.enter()
            except:
                pass

            self.screenbox.pack_start(screen, True, True, 0)

    def add_history(self, entry):
        self.data['history'].append(entry)

    def read_file(self, file_path):
        if self.metadata['mime_type'] != 'text/plain':
            return

        fd = open(file_path, 'r')
        try:
            text = fd.read()
            self.data = json.loads(text)
            if 'lessons' in self.data:
                self.mainscreen.lessons = self.data['lessons']
        finally:
            fd.close()

        self.mainscreen.show_next_lesson()

    def write_file(self, file_path):
        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'text/plain'

        fd = open(file_path, 'w')
        try:
            self.data['lessons'] = self.mainscreen.lessons
            text = json.dumps(self.data)
            fd.write(text)
        finally:
            fd.close()
예제 #44
0
class CalcLayout:

    FONT_SMALL_POINTS = 10
    FONT_SMALL = "sans %d" % FONT_SMALL_POINTS
    FONT_SMALL_NARROW = "sans italic %d" % FONT_SMALL_POINTS
    FONT_BIG_POINTS = 14
    FONT_BIG = "sans bold %d" % FONT_BIG_POINTS
    FONT_BIG_NARROW = "sans italic 14"
    FONT_BIGGER_POINTS = 18
    FONT_BIGGER = "sans bold %d" % FONT_BIGGER_POINTS

    def __init__(self, parent):
        self._parent = parent

        self._own_equations = []
        self._other_equations = []
        self._showing_history = True
        self._showing_all_history = True
        self._var_textviews = {}
        self.graph_selected = None

        self.create_dialog()

    def create_color(self, rf, gf, bf):
        return Gdk.Color(int(rf * 0xFFFF), int(gf * 0xFFFF),
                         int(bf * 0xFFFF))

    def create_button_data(self):
        """Create a list with button information. We need to do that here
        because we want to include the lambda functions."""

        mul_sym = self._parent.ml.mul_sym
        div_sym = self._parent.ml.div_sym
        equ_sym = self._parent.ml.equ_sym

        self.button_data = [
            # [x, y, width, label, bgcol, cb]
            [0, 0, 2, 1, u'\u2190', self.col_gray3,
                lambda w: self._parent.move_left()],
            [2, 0, 2, 1, u'\u2192', self.col_gray3,
                lambda w: self._parent.move_right()],
            [4, 0, 2, 1, u'\u232B', self.col_gray3,
                lambda w: self._parent.remove_character(-1)],

            [0, 1, 1, 2, '7', self.col_gray2,
                lambda w: self._parent.add_text('7')],
            [1, 1, 1, 2, '8', self.col_gray2,
                lambda w: self._parent.add_text('8')],
            [2, 1, 1, 2, '9', self.col_gray2,
                lambda w: self._parent.add_text('9')],

            [0, 3, 1, 2, '4', self.col_gray2,
                lambda w: self._parent.add_text('4')],
            [1, 3, 1, 2, '5', self.col_gray2,
                lambda w: self._parent.add_text('5')],
            [2, 3, 1, 2, '6', self.col_gray2,
                lambda w: self._parent.add_text('6')],

            [0, 5, 1, 2, '1', self.col_gray2,
                lambda w: self._parent.add_text('1')],
            [1, 5, 1, 2, '2', self.col_gray2,
                lambda w: self._parent.add_text('2')],
            [2, 5, 1, 2, '3', self.col_gray2,
                lambda w: self._parent.add_text('3')],

            [0, 7, 2, 2, '0', self.col_gray2,
                lambda w: self._parent.add_text('0')],
            [2, 7, 1, 2, '.', self.col_gray2,
                lambda w: self._parent.add_text('.')],

            [3, 1, 3, 2, _('Clear'), self.col_gray1,
             lambda w: self._parent.clear()],

            [3, 3, 1, 2, '+', self.col_gray3,
                lambda w: self._parent.add_text('+')],
            [4, 3, 1, 2, '-', self.col_gray3,
                lambda w: self._parent.add_text('-')],
            [5, 3, 1, 2, '(', self.col_gray3,
             lambda w: self._parent.add_text('(')],
            [3, 5, 1, 2, mul_sym, self.col_gray3,
                lambda w: self._parent.add_text(mul_sym)],
            [4, 5, 1, 2, div_sym, self.col_gray3,
                lambda w: self._parent.add_text(div_sym)],
            [5, 5, 1, 2, ')', self.col_gray3,
                lambda w: self._parent.add_text(')')],

            [3, 7, 3, 2, equ_sym, self.col_gray1,
                lambda w: self._parent.process()],
        ]

    def create_dialog(self):
        """Setup most of the dialog."""

# Toolbar
        self._toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self._parent)
        self._toolbar_box.toolbar.insert(activity_button, 0)

        def append(icon_name, label, page, position):
            toolbar_button = ToolbarButton()
            toolbar_button.props.page = page
            toolbar_button.props.icon_name = icon_name
            toolbar_button.props.label = label
            self._toolbar_box.toolbar.insert(toolbar_button, position)
        append('toolbar-edit',
               _('Edit'),
               EditToolbar(self._parent),
               -1)
        append('toolbar-algebra',
               _('Algebra'),
               AlgebraToolbar(self._parent),
               -1)
        append('toolbar-trigonometry',
               _('Trigonometry'),
               TrigonometryToolbar(self._parent),
               -1)
        append('toolbar-boolean',
               _('Boolean'),
               BooleanToolbar(self._parent),
               -1)
        self._misc_toolbar = MiscToolbar(
            self._parent,
            target_toolbar=self._toolbar_box.toolbar)
        append('toolbar-constants',
               _('Miscellaneous'),
               self._misc_toolbar,
               5)
        self._stop_separator = Gtk.SeparatorToolItem()
        self._stop_separator.props.draw = False
        self._stop_separator.set_expand(True)
        self._stop_separator.show()
        self._toolbar_box.toolbar.insert(self._stop_separator, -1)
        self._stop = StopButton(self._parent)
        self._toolbar_box.toolbar.insert(self._stop, -1)
        self._toolbar_box.show_all()
        self._parent.set_toolbar_box(self._toolbar_box)

# Some layout constants
        self.input_font = Pango.FontDescription('sans bold 12')
        self.button_font = Pango.FontDescription('sans bold 16')
        self.col_white = self.create_color(1.00, 1.00, 1.00)
        self.col_gray1 = self.create_color(0.76, 0.76, 0.76)
        self.col_gray2 = self.create_color(0.50, 0.50, 0.50)
        self.col_gray3 = self.create_color(0.25, 0.25, 0.25)
        self.col_black = self.create_color(0.00, 0.00, 0.00)
        self.col_red = self.create_color(1.00, 0.00, 0.00)

# Big - Table, 16 rows, 10 columns, homogeneously divided
        self.grid = Gtk.Grid()
        self.grid.set_column_homogeneous(True)
        self.grid.set_row_spacing(0)
        self.grid.set_column_spacing(4)

# Left part: container and input
        vc1 = Gtk.VBox(False, 0)
        hc1 = Gtk.HBox(False, 10)
        eb = Gtk.EventBox()
        eb.add(hc1)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = Gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        label1 = Gtk.Label(label=_('Label:'))
        label1.modify_fg(Gtk.StateType.NORMAL, self.col_white)
        label1.set_alignment(1, 0.5)
        hc1.pack_start(label1, expand=False, fill=False, padding=10)
        self.label_entry = Gtk.Entry()
        self.label_entry.modify_bg(Gtk.StateType.INSENSITIVE, self.col_black)
        hc1.pack_start(self.label_entry, expand=True, fill=True, padding=0)
        vc1.pack_start(eb2, False, True, 0)

        self.text_entry = Gtk.Entry()
        try:
            self.text_entry.props.im_module = 'gtk-im-context-simple'
        except AttributeError:
            pass
        self.text_entry.set_size_request(-1, 75)
        self.text_entry.connect('key_press_event', self._parent.ignore_key_cb)
        self.text_entry.modify_font(self.input_font)
        self.text_entry.modify_bg(Gtk.StateType.INSENSITIVE, self.col_black)
        eb = Gtk.EventBox()
        eb.add(self.text_entry)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = Gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        vc1.pack_start(eb2, expand=True, fill=True, padding=0)
        self.grid.attach(vc1, 0, 0, 7, 6)

# Left part: buttons
        self.pad = Gtk.Grid()
        self.pad.set_column_homogeneous(True)
        self.pad.set_row_spacing(6)
        self.pad.set_column_spacing(6)
        self.create_button_data()
        self.buttons = {}
        for x, y, w, h, cap, bgcol, cb in self.button_data:
            button = self.create_button(
                _(cap), cb, self.col_white, bgcol, w, h)
            self.buttons[cap] = button
            self.pad.attach(button, x, y, w, h)

        eb = Gtk.EventBox()
        eb.add(self.pad)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        self.grid.attach(eb, 0, 6, 7, 20)

# Right part: container and equation button
        hc2 = Gtk.HBox()
        combo = ComboBox()
        combo.append_item(0, _('All equations'))
        combo.append_item(1, _('My equations'))
        combo.append_item(2, _('Show variables'))
        combo.set_active(0)
        combo.connect('changed', self._history_filter_cb)
        hc2.pack_start(combo, True, True, 0)
        hc2.set_border_width(6)
        self.grid.attach(hc2, 7, 0, 4, 2)

# Right part: last equation
        self.last_eq = Gtk.TextView()
        self.last_eq.set_editable(False)
        self.last_eq.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
        self.last_eq.connect('realize', self._textview_realize_cb)
        self.last_eq.modify_base(Gtk.StateType.NORMAL, Gdk.color_parse(
                                 sugar3.profile.get_color().get_fill_color()))
        self.last_eq.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(
                               sugar3.profile.get_color().get_stroke_color()))
        self.last_eq.set_border_window_size(Gtk.TextWindowType.LEFT, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.RIGHT, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.TOP, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.BOTTOM, 4)

        # TODO Fix for old Sugar 0.82 builds, red_float not available
        xo_color = sugar3.profile.get_color()
        bright = (
            Gdk.color_parse(xo_color.get_fill_color()).red_float +
            Gdk.color_parse(xo_color.get_fill_color()).green_float +
            Gdk.color_parse(xo_color.get_fill_color()).blue_float) / 3.0
        if bright < 0.5:
            self.last_eq.modify_text(Gtk.StateType.NORMAL, self.col_white)
        else:
            self.last_eq.modify_text(Gtk.StateType.NORMAL, self.col_black)

        self.grid.attach(self.last_eq, 7, 2, 4, 5)

# Right part: history
        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.NEVER,
                                   Gtk.PolicyType.AUTOMATIC)

        self.history_vbox = Gtk.VBox()
        self.history_vbox.set_homogeneous(False)
        self.history_vbox.set_border_width(0)
        self.history_vbox.set_spacing(4)

        self.variable_vbox = Gtk.VBox()
        self.variable_vbox.set_homogeneous(False)
        self.variable_vbox.set_border_width(0)
        self.variable_vbox.set_spacing(4)

        vbox = Gtk.VBox()
        vbox.pack_start(self.history_vbox, True, True, 0)
        vbox.pack_start(self.variable_vbox, True, True, 0)
        scrolled_window.add_with_viewport(vbox)
        self.grid.attach(scrolled_window, 7, 7, 4, 19)

        Gdk.Screen.get_default().connect('size-changed',
                                         self._configure_cb)

    def _configure_cb(self, event):
        # Maybe redo layout
        self._toolbar_box.toolbar.remove(self._stop)
        self._toolbar_box.toolbar.remove(self._stop_separator)
        self._misc_toolbar.update_layout()
        self._toolbar_box.toolbar.insert(self._stop_separator, -1)
        self._toolbar_box.toolbar.insert(self._stop, -1)

    def show_it(self):
        """Show the dialog."""
        self._parent.set_canvas(self.grid)
        self._parent.show_all()
        self.show_history()
        self.text_entry.grab_focus()

    def showing_history(self):
        """Return whether we're currently showing the history (or otherwise
        the list of variables)."""
        return self._showing_history

    def show_history(self):
        """Show the history VBox."""
        self._showing_history = True
        self.variable_vbox.hide()
        self.history_vbox.show()

    def toggle_select_graph(self, widget, host=None):
        # if we have a graph already selected, we must deselect it first
        if self.graph_selected and self.graph_selected != widget:
            self.toggle_select_graph(self.graph_selected)

        if not self.graph_selected:
            widget.set_visible_window(True)
            widget.set_above_child(True)
            self.graph_selected = widget
            white = Gdk.color_parse('white')
            widget.modify_bg(Gtk.StateType.NORMAL, white)
        else:
            widget.set_visible_window(False)
            self.graph_selected = False

    def add_equation(self, textview, own, prepend=False):
        """Add a Gtk.TextView of an equation to the history_vbox."""

        GraphEventBox = None
        if isinstance(textview, Gtk.Image):
            # Add the image inside the eventBox
            GraphEventBox = Gtk.EventBox()
            GraphEventBox.add(textview)
            GraphEventBox.set_visible_window(False)
            GraphEventBox.connect(
                'button_press_event', self.toggle_select_graph)
            GraphEventBox.show()

        if prepend:
            if GraphEventBox:
                self.history_vbox.pack_start(GraphEventBox, False, True, 0)
                self.history_vbox.reorder_child(GraphEventBox, 0)
            else:
                self.history_vbox.pack_start(textview, False, True, 0)
                self.history_vbox.reorder_child(textview, 0)
        else:
            if GraphEventBox:
                self.history_vbox.pack_end(GraphEventBox, False, True)
            else:
                self.history_vbox.pack_end(textview, False, True)

        if own:
            if GraphEventBox:
                self._own_equations.append(GraphEventBox)
                GraphEventBox.get_child().show()
            else:
                self._own_equations.append(textview)
                textview.show()
        else:
            if self._showing_all_history:
                if GraphEventBox:
                    self._other_equations.append(GraphEventBox)
                    GraphEventBox.get_child().show()
                else:
                    self._other_equations.append(textview)
                    textview.show()

    def show_all_history(self):
        """Show both owned and other equations."""
        self._showing_all_history = True
        for key in self._other_equations:
            if isinstance(key, Gtk.EventBox):
                key.get_child().show()
            else:
                key.show()

    def show_own_history(self):
        """Show only owned equations."""
        self._showing_all_history = False
        for key in self._other_equations:
            if isinstance(key, Gtk.EventBox):
                key.get_child().hide()
            else:
                key.hide()

    def add_variable(self, varname, textview):
        """Add a Gtk.TextView of a variable to the variable_vbox."""

        if varname in self._var_textviews:
            self.variable_vbox.remove(self._var_textviews[varname])
            del self._var_textviews[varname]

        self._var_textviews[varname] = textview
        self.variable_vbox.pack_start(textview, False, True, 0)

        # Reorder textviews for a sorted list
        names = self._var_textviews.keys()
        names.sort()
        for i in range(len(names)):
            self.variable_vbox.reorder_child(self._var_textviews[names[i]], i)

        textview.show()

    def show_variables(self):
        """Show the variables VBox."""
        self._showing_history = False
        self.history_vbox.hide()
        self.variable_vbox.show()

    def create_button(self, cap, cb, fgcol, bgcol, width, height):
        """Create a button that is set up properly."""
        button = Gtk.Button(_(cap))
        self.modify_button_appearance(button, fgcol, bgcol, width, height)
        button.connect("clicked", cb)
        button.connect("key_press_event", self._parent.ignore_key_cb)
        return button

    def modify_button_appearance(self, button, fgcol, bgcol, width, height):
        """Modify button style."""
        width = 50 * width
        height = 50 * height
        button.get_child().set_size_request(width, height)
        button.get_child().modify_font(self.button_font)
        button.get_child().modify_fg(Gtk.StateType.NORMAL, fgcol)
        button.modify_bg(Gtk.StateType.NORMAL, bgcol)
        button.modify_bg(Gtk.StateType.PRELIGHT, bgcol)

    def _history_filter_cb(self, combo):
        selection = combo.get_active()
        if selection == 0:
            self.show_history()
            self.show_all_history()
        elif selection == 1:
            self.show_history()
            self.show_own_history()
        elif selection == 2:
            self.show_variables()

    def _textview_realize_cb(self, widget):
        '''Change textview properties once window is created.'''
        win = widget.get_window(Gtk.TextWindowType.TEXT)
        win.set_cursor(Gdk.Cursor.new(Gdk.CursorType.HAND1))
        return False
예제 #45
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close)
        Gst.init(None)

        self._what_list = []

        self.play_recording_thread = None

        self.playing_recording = False
        self.firstTime = False
        self.playing = False
        self.regularity = 0.7
        self._drums_store = []
        self.recording = False
        self.recorded_keys = []
        self.is_valid_recording = False

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1
        self.csnd = new_csound_client()
        self.rythmInstrument = 'drum1kick'
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        self.play_index = 0

        self.play_recording_button = ToolButton(
            icon_name='media-playback-start')
        self.play_recording_button.set_property('can-default', True)
        self.play_recording_button.show()
        self.record_button = ToggleToolButton(icon_name='media-record')
        self.record_button.set_property('can-default', True)
        self.record_button.show()
        self.play_recording_button.set_sensitive(False)

        self.record_button.connect('clicked', self.__record_button_click_cb)

        self.play_recording_button.connect('clicked',
                                           self.handlePlayRecordingButton)

        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        # TODO: disabe until is implemented with csnd6
        # self.createPercussionToolbar(toolbar_box)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        ti_notes_labels = RadioToolButton()
        ti_notes_labels.props.icon_name = 'ti_key'
        ti_notes_labels.props.group = keybord_labels
        ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb)
        toolbar_box.toolbar.insert(ti_notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        no_labels = RadioToolButton()
        no_labels.props.icon_name = 'edit-clear'
        no_labels.props.group = keybord_labels
        no_labels.connect('clicked', self.set_keyboard_no_labels_cb)
        toolbar_box.toolbar.insert(no_labels, -1)
        self._what_widget = Gtk.ToolItem()
        self._what_search_button = FilterToolItem(_('Select Instrument'),
                                                  'view-type',
                                                  _('Piano'),
                                                  self._what_widget)
        self._what_widget.show()
        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(self._what_search_button, -1)
        self._what_search_button.show()
        self._what_search_button.set_is_important(True)
        self._what_widget_contents = None
        self._what_drum_widget_contents = None

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(self.record_button, -1)
        toolbar_box.toolbar.insert(self.play_recording_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._save_as_audio_bt = ToolButton(icon_name='save-as-audio')
        self._save_as_audio_bt.props.tooltip = _('Save as audio')
        self._save_as_audio_bt.connect('clicked', self._save_ogg_cb)
        self._save_as_audio_bt.show()
        self._save_as_audio_bt.set_sensitive(False)
        activity_button.page.insert(self._save_as_audio_bt, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
                 ['FA#', 'SOLb'], 'SOL',
                 ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI']
        self.notes_labels = [notes, notes, ['DO']]

        # some countries use TI instead of SI
        ti_notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
                    ['FA#', 'SOLb'], 'SOL',
                    ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI']
        self.ti_notes_labels = [ti_notes, ti_notes, ['DO']]

        german_notes = ['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F',
                        ['F#', 'Gb'], 'G',
                        ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B']

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2, add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.beat = 4
        self.reverb = 0.1
        self.tempo = PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0

        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.drumFillin = Fillin(self.beat,
                                 self.tempo,
                                 self.rythmInstrument,
                                 self.reverb,
                                 self.drumVolume)

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        # TODO commented because apparently are not used in the activity
        # for i in range(10):
        #     self.csnd.load_instrument('guidice' + str(i + 1))

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        self._event_box = Gtk.EventBox()
        self._event_box.modify_bg(
            Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color())
        vbox.pack_start(self._event_box, False, False, 0)
        vbox.pack_end(self.piano, True, True, 0)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self._event_box.set_size_request(
            -1, Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
예제 #46
0
class JukeboxActivity(activity.Activity):

    __gsignals__ = {
        'playlist-finished': (GObject.SignalFlags.RUN_FIRST, None, []), }

    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.player = None

        self._alert = None
        self._playlist_jobject = None

        self.set_title(_('Jukebox Activity'))
        self.max_participants = 1

        self._toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page
        self._toolbar_box.toolbar.insert(activity_button, 0)
        self.title_entry = activity_toolbar.title

        self._view_toolbar = ViewToolbar()
        self._view_toolbar.connect('go-fullscreen',
                                   self.__go_fullscreen_cb)
        self._view_toolbar.connect('toggle-playlist',
                                   self.__toggle_playlist_cb)
        view_toolbar_button = ToolbarButton(
            page=self._view_toolbar,
            icon_name='toolbar-view')
        self._view_toolbar.show()
        self._toolbar_box.toolbar.insert(view_toolbar_button, -1)
        view_toolbar_button.show()

        self._control_toolbar = Gtk.Toolbar()
        self._control_toolbar_button = ToolbarButton(
            page=self._control_toolbar,
            icon_name='media-playback-start')
        self._control_toolbar.show()
        self._toolbar_box.toolbar.insert(self._control_toolbar_button, -1)
        self._control_toolbar_button.hide()

        self.set_toolbar_box(self._toolbar_box)
        self._toolbar_box.show_all()

        self.connect('key_press_event', self.__key_press_event_cb)
        self.connect('playlist-finished', self.__playlist_finished_cb)

        # We want to be notified when the activity gets the focus or
        # loses it. When it is not active, we don't need to keep
        # reproducing the video
        self.connect('notify::active', self.__notify_active_cb)

        self._video_canvas = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        self._playlist_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        self.playlist_widget = PlayList()
        self.playlist_widget.connect('play-index', self.__play_index_cb)
        self.playlist_widget.connect('missing-tracks',
                                     self.__missing_tracks_cb)
        self.playlist_widget.set_size_request(
            Gdk.Screen.width() * PLAYLIST_WIDTH_PROP, 0)
        self.playlist_widget.show()

        self._playlist_box.pack_start(self.playlist_widget, expand=True,
                                      fill=True, padding=0)

        self._playlist_toolbar = Gtk.Toolbar()

        move_up = ToolButton("go-up")
        move_up.set_tooltip(_("Move up"))
        move_up.connect("clicked", self._move_up_cb)
        self._playlist_toolbar.insert(move_up, 0)

        move_down = ToolButton("go-down")
        move_down.set_tooltip(_("Move down"))
        move_down.connect("clicked", self._move_down_cb)
        self._playlist_toolbar.insert(move_down, 1)

        self._playlist_box.pack_end(self._playlist_toolbar, False, False, 0)
        self._video_canvas.pack_start(self._playlist_box, False, False, 0)

        # Create the player just once
        logging.debug('Instantiating GstPlayer')
        self.player = GstPlayer()
        self.player.connect('eos', self.__player_eos_cb)
        self.player.connect('error', self.__player_error_cb)
        self.player.connect('play', self.__player_play_cb)

        self.control = Controls(self, self._toolbar_box.toolbar,
                                self._control_toolbar)

        self._separator = Gtk.SeparatorToolItem()
        self._separator.props.draw = False
        self._separator.set_expand(True)
        self._separator.show()
        self._toolbar_box.toolbar.insert(self._separator, -1)

        self._stop = StopButton(self)
        self._toolbar_box.toolbar.insert(self._stop, -1)

        self._empty_widget = Gtk.Label(label="")
        self._empty_widget.show()
        self.videowidget = VideoWidget()
        self.set_canvas(self._video_canvas)
        self._init_view_area()
        self.show_all()
        # need hide the playlist by default
        self._playlist_box.hide()

        self._configure_cb()

        self.player.init_view_area(self.videowidget)

        self._volume_monitor = Gio.VolumeMonitor.get()
        self._volume_monitor.connect('mount-added', self.__mount_added_cb)
        self._volume_monitor.connect('mount-removed', self.__mount_removed_cb)

        if handle.object_id is None:
            # The activity was launched from scratch. We need to show
            # the Empty Widget
            self.playlist_widget.hide()
            emptypanel.show(self, 'activity-jukebox',
                            _('No media'), _('Choose media files'),
                            self.control.show_picker_cb)

        self.control.check_if_next_prev()

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

    def _move_up_cb(self, button):
        self.playlist_widget.move_up()

    def _move_down_cb(self, button):
        self.playlist_widget.move_down()

    def _configure_cb(self, event=None):
        self._toolbar_box.toolbar.remove(self._stop)
        self._toolbar_box.toolbar.remove(self._separator)
        if Gdk.Screen.width() < Gdk.Screen.height():
            self._control_toolbar_button.show()
            self._control_toolbar_button.set_expanded(True)
            self.control.update_layout(landscape=False)
            self._toolbar_box.toolbar.insert(self._separator, -1)
        else:
            self._control_toolbar_button.set_expanded(False)
            self._control_toolbar_button.hide()
            self.control.update_layout(landscape=True)
        self._toolbar_box.toolbar.insert(self._stop, -1)

    def __notify_active_cb(self, widget, event):
        """Sugar notify us that the activity is becoming active or inactive.
        When we are inactive, we stop the player if it is reproducing
        a video.
        """

        logging.debug('JukeboxActivity notify::active signal received')

        if self.player.player.props.current_uri is not None and \
                self.player.playing_video():
            if not self.player.is_playing() and self.props.active:
                self.player.play()
            if self.player.is_playing() and not self.props.active:
                self.player.pause()

    def _init_view_area(self):
        """
        Use a notebook with two pages, one empty an another
        with the videowidget
        """
        self.view_area = Gtk.Notebook()
        self.view_area.set_show_tabs(False)
        self.view_area.append_page(self._empty_widget, None)
        self.view_area.append_page(self.videowidget, None)
        self._video_canvas.pack_end(self.view_area, expand=True,
                                    fill=True, padding=0)

    def _switch_canvas(self, show_video):
        """Show or hide the video visualization in the canvas.

        When hidden, the canvas is filled with an empty widget to
        ensure redrawing.

        """
        if show_video:
            self.view_area.set_current_page(1)
        else:
            self.view_area.set_current_page(0)
        self._video_canvas.queue_draw()

    def __key_press_event_cb(self, widget, event):
        keyname = Gdk.keyval_name(event.keyval)
        logging.info("Keyname Press: %s, time: %s", keyname, event.time)
        if self.title_entry.has_focus():
            return False

        if keyname == "space":
            self.control._button_clicked_cb(None)
            return True

    def __playlist_finished_cb(self, widget):
        self._switch_canvas(show_video=False)
        self._view_toolbar._show_playlist.set_active(True)
        self.unfullscreen()

        # Select the first stream to be played when Play button will
        # be pressed
        self.playlist_widget.set_current_playing(0)
        self.control.check_if_next_prev()

    def songchange(self, direction):
        current_playing = self.playlist_widget.get_current_playing()
        if direction == 'prev' and current_playing > 0:
            self.play_index(current_playing - 1)
        elif direction == 'next' and \
                current_playing < len(self.playlist_widget._items) - 1:
            self.play_index(current_playing + 1)
        else:
            self.emit('playlist-finished')

    def play_index(self, index):
        # README: this line is no more necessary because of the
        # .playing_video() method
        # self._switch_canvas(show_video=True)
        self.playlist_widget.set_current_playing(index)

        path = self.playlist_widget._items[index]['path']
        if self.playlist_widget.check_available_media(path):
            if self.playlist_widget.is_from_journal(path):
                path = self.playlist_widget.get_path_from_journal(path)
            self.control.check_if_next_prev()

            self.player.set_uri(path)
            self.player.play()
        else:
            self.songchange('next')

    def __play_index_cb(self, widget, index, path):
        # README: this line is no more necessary because of the
        # .playing_video() method
        # self._switch_canvas(show_video=True)
        self.playlist_widget.set_current_playing(index)

        if self.playlist_widget.is_from_journal(path):
            path = self.playlist_widget.get_path_from_journal(path)

        self.control.check_if_next_prev()

        self.player.set_uri(path)
        self.player.play()

    def __player_eos_cb(self, widget):
        self.songchange('next')

    def _show_error_alert(self, title, msg=None):
        self._alert = ErrorAlert()
        self._alert.props.title = title
        if msg is not None:
            self._alert.props.msg = msg
        self.add_alert(self._alert)
        self._alert.connect('response', self._alert_cancel_cb)
        self._alert.show()

    def __mount_added_cb(self, volume_monitor, device):
        logging.debug('Mountpoint added. Checking...')
        self.remove_alert(self._alert)
        self.playlist_widget.update()

    def __mount_removed_cb(self, volume_monitor, device):
        logging.debug('Mountpoint removed. Checking...')
        self.remove_alert(self._alert)
        self.playlist_widget.update()

    def __missing_tracks_cb(self, widget, tracks):
        self._show_missing_tracks_alert(tracks)

    def _show_missing_tracks_alert(self, tracks):
        self._alert = Alert()
        title = _('%s tracks not found.') % len(tracks)
        self._alert.props.title = title
        icon = Icon(icon_name='dialog-cancel')
        self._alert.add_button(Gtk.ResponseType.CANCEL, _('Dismiss'), icon)
        icon.show()

        icon = Icon(icon_name='dialog-ok')
        self._alert.add_button(Gtk.ResponseType.APPLY, _('Details'), icon)
        icon.show()
        self.add_alert(self._alert)
        self._alert.connect(
            'response', self.__missing_tracks_alert_response_cb, tracks)

    def __missing_tracks_alert_response_cb(self, alert, response_id, tracks):
        if response_id == Gtk.ResponseType.APPLY:
            vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            vbox.props.valign = Gtk.Align.CENTER
            label = Gtk.Label(label='')
            label.set_markup(_('<b>Missing tracks</b>'))
            vbox.pack_start(label, False, False, 15)

            for track in tracks:
                label = Gtk.Label(label=track['path'])
                vbox.add(label)

            _missing_tracks = Gtk.ScrolledWindow()
            _missing_tracks.add_with_viewport(vbox)
            _missing_tracks.show_all()

            self.view_area.append_page(_missing_tracks, None)

            self.view_area.set_current_page(2)

        self.remove_alert(alert)

    def _alert_cancel_cb(self, alert, response_id):
        self.remove_alert(alert)

    def __player_play_cb(self, widget):
        # Do not show the visualization widget if we are playing just
        # an audio stream

        def callback():
            if self.player.playing_video():
                self._switch_canvas(True)
            else:
                self._switch_canvas(False)
            return False

        # HACK: we need a timeout here because gstreamer returns
        # n-video = 0 if we call it immediately
        GObject.timeout_add(1000, callback)

    def __player_error_cb(self, widget, message, detail):
        self.player.stop()
        self.control.set_disabled()

        logging.error('ERROR MESSAGE: %s', message)
        logging.error('ERROR DETAIL: %s', detail)

        file_path = self.playlist_widget._items[
            self.playlist_widget.get_current_playing()]['path']
        mimetype = mime.get_for_file(file_path)

        title = _('Error')
        msg = _('This "%s" file can\'t be played') % mimetype
        self._switch_canvas(False)
        self._show_error_alert(title, msg)

    def can_close(self):
        # We need to put the Gst.State in NULL so gstreamer can
        # cleanup the pipeline
        self.player.stop()
        return True

    def read_file(self, file_path):
        """Load a file from the datastore on activity start."""
        logging.debug('JukeBoxAtivity.read_file: %s', file_path)

        title = self.metadata['title']
        self.playlist_widget.load_file(file_path, title)
        self._view_toolbar._show_playlist.set_active(True)

    def write_file(self, file_path):

        def write_playlist_to_file(file_path):
            """Open the file at file_path and write the playlist.

            It is saved in audio/x-mpegurl format.

            """

            list_file = open(file_path, 'w')
            for uri in self.playlist_widget._items:
                list_file.write('#EXTINF:%s\n' % uri['title'])
                list_file.write('%s\n' % uri['path'])
            list_file.close()

        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'audio/x-mpegurl'

        if self.metadata['mime_type'] == 'audio/x-mpegurl':
            write_playlist_to_file(file_path)

        else:
            if self._playlist_jobject is None:
                self._playlist_jobject = \
                    self.playlist_widget.create_playlist_jobject()

            # Add the playlist to the playlist jobject description.
            # This is only done if the activity was not started from a
            # playlist or from scratch:
            description = ''
            for uri in self.playlist_widget._items:
                description += '%s\n' % uri['title']
            self._playlist_jobject.metadata['description'] = description

            write_playlist_to_file(self._playlist_jobject.file_path)
            datastore.write(self._playlist_jobject)

    def __go_fullscreen_cb(self, toolbar):
        self.fullscreen()

    def __toggle_playlist_cb(self, toolbar):
        if self._view_toolbar._show_playlist.get_active():
            self._playlist_box.show_all()
        else:
            self._playlist_box.hide()
        self._video_canvas.queue_draw()
예제 #47
0
    def __init__(self, handle):
        """Set up the Develop activity."""
        self._dirty = False
        super(DevelopActivity, self).__init__(handle)
        self.max_participants = 1

        self.current_theme = "light"

        logging.info(repr(handle.get_dict()))

        # Source buffer
        self.editor = sourceview_editor.GtkSourceview2Editor()
        self.editor.connect('tab-changed', self.__editor_tab_changed_cb)
        self.editor.connect('changed', self.__editor_changed_cb)
        # Show tabs after Welcome Page
        self.editor.set_show_tabs(False)

        toolbarbox = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbarbox.toolbar.insert(activity_button, 0)
        self.set_toolbar_box(toolbarbox)

        view_btn = ToolbarButton()
        view_toolbar = DevelopViewToolbar(self)
        view_btn.props.page = view_toolbar
        view_btn.props.icon_name = 'toolbar-view'
        view_btn.props.label = _('View')
        view_toolbar.connect('theme-changed',
                             self.editor.theme_changed_cb)
        view_toolbar.connect('font-size-changed',
                             self.editor.font_changed_cb)
        toolbarbox.toolbar.insert(view_btn, -1)
        self.view_toolbar = view_toolbar

        edit_btn = ToolbarButton()
        edit_btn.props.page = DevelopEditToolbar(self)
        edit_btn.props.icon_name = 'toolbar-edit'
        edit_btn.props.label = _('Edit')
        toolbarbox.toolbar.insert(edit_btn, -1)

        search_btn = ToolbarButton()
        search_btn.props.page = DevelopSearchToolbar(self)
        search_btn.props.icon_name = 'search'
        search_btn.props.label = _('Search')
        toolbarbox.toolbar.insert(search_btn, -1)

        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        show_files_btn = RadioToolButton()
        show_files_btn.props.icon_name = 'sources'
        show_files_btn.props.group = show_files_btn
        show_files_btn.set_active(True)
        show_files_btn.set_tooltip(_('Show source files'))
        toolbarbox.toolbar.insert(show_files_btn, -1)
        show_files_btn.connect('clicked', self._change_treenotebook_page, 0)

        show_symbols_btn = RadioToolButton()
        show_symbols_btn.props.icon_name = 'symbols'
        show_symbols_btn.props.group = show_files_btn
        show_symbols_btn.set_active(False)
        show_symbols_btn.set_tooltip(_('Show file symbols'))
        toolbarbox.toolbar.insert(show_symbols_btn, -1)
        show_symbols_btn.connect('clicked', self._explore_code)

        show_log_btn = RadioToolButton()
        show_log_btn.props.icon_name = 'logs'
        show_log_btn.props.group = show_files_btn
        show_log_btn.set_active(False)
        show_log_btn.set_tooltip(_('Show log files'))
        toolbarbox.toolbar.insert(show_log_btn, -1)
        show_log_btn.connect('clicked', self._change_treenotebook_page, 2)

        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        create_file_btn = ToolButton('text-x-generic')
        create_file_btn.set_tooltip(_('Create empty file'))
        toolbarbox.toolbar.insert(create_file_btn, -1)
        create_file_btn.show()
        create_file_btn.connect('clicked', self.__create_empty_file_cb)

        erase_btn = ToolButton('erase')
        erase_btn.set_tooltip(_('Remove file'))
        toolbarbox.toolbar.insert(erase_btn, -1)
        erase_btn.show()
        erase_btn.connect('clicked', self.__remove_file_cb)

        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        run_btn = ToolButton('activity-start')
        run_btn.set_tooltip(_('Run activity'))
        toolbarbox.toolbar.insert(run_btn, -1)
        run_btn.connect('clicked', self.__run_actvity_cb)

        separator = Gtk.SeparatorToolItem()
        separator.set_draw(False)
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        stopbtn = StopButton(self)
        toolbarbox.toolbar.insert(stopbtn, -1)

        save_bundle_btn = ToolButton('save-as-bundle')
        save_bundle_btn.set_tooltip(_('Create bundle (.xo file)'))
        activity_button.get_page().insert(save_bundle_btn, -1)
        save_bundle_btn.connect('clicked', self.save_bundle)
        save_bundle_btn.show()

        toolbarbox.show_all()

        # Main layout.
        hbox = Gtk.HPaned()

        # The treeview and selected pane reflect each other.
        self.numb = False

        # Wait to save until first change, but save an unchanged
        # backup copy when that happens.
        self.save_unchanged = False

        # The sidebar
        sidebar = Gtk.VBox()
        self.treenotebook = notebook.Notebook(can_close_tabs=False)
        self.treenotebook.set_show_tabs(False)
        sidebar.pack_start(self.treenotebook, True, True, 0)

        self.activity_tree_view = FileViewer()
        self.treenotebook.add_page(_("Activity"), self.activity_tree_view)
        self.treenotebook.set_size_request(Gdk.Screen.width() / 5, -1)

        # Symbols tree
        self._symbolstree = SymbolsTree()
        self._symbolstree.connect('symbol-selected',
                                  self.editor.symbol_selected_cb)
        scrolled = Gtk.ScrolledWindow()
        scrolled.add(self._symbolstree)
        scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        self.treenotebook.add_page(_('Symbols Tree'), scrolled)

        hbox.pack1(sidebar, resize=True, shrink=False)
        # Show sidebar after welcome page ends
        # sidebar.show()
        self.sidebar = sidebar

        logging.info('finished check')
        self.editor.show()
        hbox.pack2(self.editor, resize=True, shrink=True)
        self.set_canvas(hbox)
        hbox.show()
        logging.critical('finished initialization')
        self.activity_dir = None
        self.show()

        if not handle.object_id or not self.metadata.get('source'):
            GObject.timeout_add(10, self._show_welcome)
예제 #48
0
    def __init__(self, handle):
        # Initialize the parent
        Activity.__init__(self, handle)

        logger.debug('Initiating PlayGo')

        self.size = DEFAULT_SIZE
        self.komi = DEFAULT_KOMI

        # Set the activity toolbarbox
        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbarbox.toolbar.insert(ActivityToolbarButton(self), -1)
        toolbarbox.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.gameToolbar = GameToolbar(self)
        self.gameToolbar.connect('game-restart', self.restart_game)
        self.gameToolbar.connect('game-board-size', self.board_size_change)
        self.gameToolbar.connect('ai-activated', self.ai_activated_cb)
        self.gameToolbar.connect('ai-deactivated', self.ai_deactivated_cb)
        toolbarbox.toolbar.insert(ToolbarButton(page=self.gameToolbar, icon_name='txt'), -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbarbox.toolbar.insert(separator, -1)

        toolbarbox.toolbar.insert(StopButton(self), -1)

        toolbarbox.show_all()
        toolbarbox.toolbar.show_all()
        self.gameToolbar.show_all()

        # Initialize the game
        self.game = GoGame(self.size)
        self.CurrentColor = 'B'
        self.PlayerColor = 'B'
        self.pass_count = 0
        self.ai_activated = False
        self.set_up_ui()

        if not handle.object_id:
            self.infopanel.show(_('Welcome to PlayGo!'))
        else:
            self.show_score()

        self.lastX = -1
        self.lastY = -1

        # Set keypad actions
        self._key_actions = {
            'KP_Up'     : 'move_up',
            'KP_Right'  : 'move_right',
            'KP_Down'   : 'move_down',
            'KP_Left'   : 'move_left',
            'KP_Home'   : 'place_stone',
            'KP_Next'   : 'undo',
            'KP_End'    : 'pass' }

        ##self._key_grabber = KeyGrabber()
        ##self._key_grabber.connect('key-pressed',
        ##                          self._key_pressed_cb)

        # New KeyGrabber API change (ticket #7999)
        ##try:
        ##    self._key_grabber.grab_keys(self._key_actions.keys())
        ##except:
        ##    for key in self._key_actions.keys():
        ##        self._key_grabber.grab(key)

        #Set up collaboration
        self.collaboration = CollaborationWrapper(self, 
                                                  self.buddy_joined, 
                                                  self.buddy_left, 
                                                  self.Play, 
                                                  self.game.undostack, 
                                                  self.bootstrap)

        self.connect('shared', self.collaboration._shared_cb)
        if self.get_shared_activity():
            # We are joining the activity
            self.connect('joined', self.collaboration._joined_cb)
            if self.get_shared():
                # We've already joined
                self.collaboration._joined_cb()
예제 #49
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close)
        Gst.init(None)

        self._what_list = []

        self.play_recording_thread = None

        self.playing_recording = False
        self.firstTime = False
        self.playing = False
        self.regularity = 0.7
        self._drums_store = []
        self.recording = False
        self.recorded_keys = []
        self.is_valid_recording = False

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1
        self.csnd = new_csound_client()
        self.rythmInstrument = 'drum1kick'
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        self.play_index = 0

        self.play_recording_button = ToolButton(
            icon_name='media-playback-start')
        self.play_recording_button.set_property('can-default', True)
        self.play_recording_button.show()
        self.record_button = ToggleToolButton(icon_name='media-record')
        self.record_button.set_property('can-default', True)
        self.record_button.show()
        self.play_recording_button.set_sensitive(False)

        self.record_button.connect('clicked', self.__record_button_click_cb)

        self.play_recording_button.connect('clicked',
                                           self.handlePlayRecordingButton)

        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        # TODO: disabe until is implemented with csnd6
        # self.createPercussionToolbar(toolbar_box)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        ti_notes_labels = RadioToolButton()
        ti_notes_labels.props.icon_name = 'ti_key'
        ti_notes_labels.props.group = keybord_labels
        ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb)
        toolbar_box.toolbar.insert(ti_notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        no_labels = RadioToolButton()
        no_labels.props.icon_name = 'edit-clear'
        no_labels.props.group = keybord_labels
        no_labels.connect('clicked', self.set_keyboard_no_labels_cb)
        toolbar_box.toolbar.insert(no_labels, -1)
        self._what_widget = Gtk.ToolItem()
        self._what_search_button = FilterToolItem(_('Select Instrument'),
                                                  'view-type', _('Piano'),
                                                  self._what_widget)
        self._what_widget.show()
        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(self._what_search_button, -1)
        self._what_search_button.show()
        self._what_search_button.set_is_important(True)
        self._what_widget_contents = None
        self._what_drum_widget_contents = None

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(self.record_button, -1)
        toolbar_box.toolbar.insert(self.play_recording_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._save_as_audio_bt = ToolButton(icon_name='save-as-audio')
        self._save_as_audio_bt.props.tooltip = _('Save as audio')
        self._save_as_audio_bt.connect('clicked', self._save_ogg_cb)
        self._save_as_audio_bt.show()
        self._save_as_audio_bt.set_sensitive(False)
        activity_button.page.insert(self._save_as_audio_bt, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI'
        ]
        self.notes_labels = [notes, notes, ['DO']]

        # some countries use TI instead of SI
        ti_notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI'
        ]
        self.ti_notes_labels = [ti_notes, ti_notes, ['DO']]

        german_notes = [
            'C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G',
            ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B'
        ]

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2,
                                   add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.beat = 4
        self.reverb = 0.1
        self.tempo = PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0

        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.drumFillin = Fillin(self.beat, self.tempo, self.rythmInstrument,
                                 self.reverb, self.drumVolume)

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        # TODO commented because apparently are not used in the activity
        # for i in range(10):
        #     self.csnd.load_instrument('guidice' + str(i + 1))

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        self._event_box = Gtk.EventBox()
        self._event_box.modify_bg(Gtk.StateType.NORMAL,
                                  style.COLOR_WHITE.get_gdk_color())
        vbox.pack_start(self._event_box, False, False, 0)
        vbox.pack_end(self.piano, True, True, 0)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self._event_box.set_size_request(
            -1,
            Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
예제 #50
0
class Finance(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self.set_title(_("Finance"))
        self.max_participants = 1

        # Initialize database.
        # data
        #   next_id
        #   transactions
        #     id, name, type, amount, date, category
        #   budgets
        #     category, period, amount, budget
        self.data = {
            'next_id': 0,
            'transactions': [],
            'budgets': {}
        }

        self.transaction_map = {}
        self.visible_transactions = []

        self.transaction_names = {}
        self.category_names = {}

        # self.create_test_data()

        # Initialize view period to the first of the month.
        self.period = MONTH
        self.period_start = self.get_this_period()

        # Create screens.
        self.register = registerscreen.RegisterScreen(self)
        self.chart = chartscreen.ChartScreen(self)
        self.budget = budgetscreen.BudgetScreen(self)

        self.build_toolbox()

        self.screenbox = Gtk.VBox()

        self.headerbox = self.build_header()
        self._active_panel = None

        # Add the summary data.

        self.startlabel = Gtk.Label()
        self.startamountlabel = Gtk.Label()
        self.creditslabel = Gtk.Label()
        self.debitslabel = Gtk.Label()
        self.balancelabel = Gtk.Label()
        self.balancelabel.props.margin_left = style.DEFAULT_SPACING
        self.balancelabel.props.margin_right = style.DEFAULT_SPACING

        font_size = int(style.FONT_SIZE * 1.25)
        font = Pango.FontDescription("Sans %d" % font_size)
        for label in (self.startlabel, self.startamountlabel,
                      self.creditslabel, self.debitslabel):
            label.modify_font(font)
            label.set_hexpand(True)
            label.set_halign(Gtk.Align.START)
            label.props.margin = style.DEFAULT_PADDING

        self.balance_evbox = Gtk.EventBox()
        self.balance_evbox.add(self.balancelabel)
        summarybox = Gtk.Grid()
        summarybox.attach(self.startlabel, 0, 0, 1, 1)
        summarybox.attach(self.startamountlabel, 0, 1, 1, 1)
        summarybox.attach(self.creditslabel, 1, 0, 1, 1)
        summarybox.attach(self.debitslabel, 1, 1, 1, 1)
        summarybox.attach(self.balance_evbox, 2, 0, 1, 2)
        self.balance_evbox.set_halign(Gtk.Align.END)

        summary_evbox = Gtk.EventBox()
        summary_evbox.add(summarybox)
        summary_evbox.modify_bg(Gtk.StateType.NORMAL,
                                style.Color('#666666').get_gdk_color())
        summary_evbox.set_size_request(-1, style.GRID_CELL_SIZE)

        vbox = Gtk.VBox()

        vbox.pack_start(self.headerbox, False, False, 0)
        vbox.pack_start(self.screenbox, True, True, 0)
        vbox.pack_start(summary_evbox, False, False, 0)

        # Start with the empty screen.
        self.empty_panel = emptypanel.create_empty_panel(
            'row-insert-credit',
            _('Add some credit or debit to get started!'),
            _('Add credit'), self.__empty_panel_btn_cb)

        self._set_internal_panel(self.empty_panel)

        # This has to happen last, because it calls the read_file
        # method when restoring from the Journal.
        self.set_canvas(vbox)

        self.show_all()
        self.show_header_controls()

    def build_toolbox(self):

        view_tool_group = None
        registerbtn = RadioToolButton()
        registerbtn.props.icon_name = 'view-list'
        registerbtn.props.label = _('Register')
        registerbtn.set_tooltip(_("Register"))
        registerbtn.props.group = view_tool_group
        view_tool_group = registerbtn
        registerbtn.props.accelerator = '<Ctrl>1'
        registerbtn.connect('clicked', self.register_cb)

        budgetbtn = RadioToolButton()
        budgetbtn.props.icon_name = 'budget'
        budgetbtn.props.label = _('Budget')
        budgetbtn.set_tooltip(_("Budget"))
        budgetbtn.props.group = view_tool_group
        budgetbtn.props.accelerator = '<Ctrl>2'
        budgetbtn.connect('clicked', self.budget_cb)

        chartbtn = RadioToolButton()
        chartbtn.props.icon_name = 'chart'
        chartbtn.props.label = _('Chart')
        chartbtn.set_tooltip(_("Chart"))
        chartbtn.props.group = view_tool_group
        chartbtn.props.accelerator = '<Ctrl>3'
        chartbtn.connect('clicked', self.chart_cb)

        helpbutton = self._create_help_button()
        helpbutton.show_all()

        self.toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        self.toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.toolbar_box.toolbar.insert(registerbtn, -1)
        self.toolbar_box.toolbar.insert(budgetbtn, -1)
        self.toolbar_box.toolbar.insert(chartbtn, -1)

        self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.toolbar_box.toolbar.insert(helpbutton, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self.toolbar_box.toolbar.insert(separator, -1)

        self.toolbar_box.toolbar.insert(StopButton(self), -1)
        self.set_toolbar_box(self.toolbar_box)

        activity_button.page.insert(self._create_export_button(), -1)

        self.toolbar_box.show_all()

    def _create_export_button(self):
        # Add expoprt button
        export_data = ToolButton('save-as-data')

        export_data.props.tooltip = _('Export data')
        export_data.props.hide_tooltip_on_click = False
        export_data.palette_invoker.props.toggle_palette = True
        export_data.show()

        menu_box = PaletteMenuBox()
        export_data.props.palette.set_content(menu_box)

        menu_item = PaletteMenuItem(text_label=_('Export credits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'credit', DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'debit', DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export credits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'credit', MONTH)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb,
                          'debit', MONTH)
        menu_box.append_item(menu_item)

        menu_box.show_all()
        return export_data

    def _create_help_button(self):
        helpitem = HelpButton()
        helpitem.add_section(_('Register'), icon='view-list')
        helpitem.add_paragraph(registerscreen.REGISTER_HELP)
        helpitem.add_section(_('Budget'), icon='budget')
        helpitem.add_paragraph(budgetscreen.BUDGET_HELP)
        helpitem.add_section(_('Chart'), icon='chart')
        helpitem.add_paragraph(chartscreen.CHART_HELP)
        return helpitem

    def build_header(self):
        # Add the header.
        self.periodlabel = Gtk.Label()
        self.periodlabel.set_padding(10, 0)
        self._period_label_item = Gtk.ToolItem()
        self._period_label_item.add(self.periodlabel)
        self.periodlabel.set_halign(Gtk.Align.END)
        self._period_label_item.set_size_request(style.GRID_CELL_SIZE * 5, -1)

        headerbox = Gtk.Toolbar()
        headerbox.modify_bg(Gtk.StateType.NORMAL,
                            style.Color('#424242').get_gdk_color())
        headerbox.set_size_request(-1, style.GRID_CELL_SIZE)

        # register buttons
        self.newcreditbtn = ToolButton('row-insert-credit')
        self.newcreditbtn.set_tooltip(_("New Credit"))
        self.newcreditbtn.props.accelerator = '<Ctrl>A'
        self.newcreditbtn.connect('clicked', self.__newcredit_cb)

        self.newdebitbtn = ToolButton('row-insert-debit')
        self.newdebitbtn.set_tooltip(_("New Debit"))
        self.newdebitbtn.props.accelerator = '<Ctrl>D'
        self.newdebitbtn.connect('clicked', self.__newdebit_cb)

        self.eraseitembtn = ToolButton('basket')
        self.eraseitembtn.set_tooltip(_("Erase Transaction"))
        self.eraseitembtn.props.accelerator = '<Ctrl>E'
        self.eraseitembtn.connect('clicked', self.__eraseitem_cb)

        headerbox.insert(self.newcreditbtn, -1)
        headerbox.insert(self.newdebitbtn, -1)
        headerbox.insert(self.eraseitembtn, -1)

        self.header_separator_visible = Gtk.SeparatorToolItem()
        headerbox.insert(self.header_separator_visible, -1)

        self.export_image = ToolButton('save-as-image')
        self.export_image.set_tooltip(_("Save as Image"))
        self.export_image.connect('clicked', self.__save_image_cb)
        headerbox.insert(self.export_image, -1)

        self._header_separator = Gtk.SeparatorToolItem()
        self._header_separator.props.draw = False
        self._header_separator.set_expand(True)
        headerbox.insert(self._header_separator, -1)

        # period controls
        self.thisperiodbtn = ToolButton('go-down')
        self.thisperiodbtn.props.accelerator = '<Ctrl>Down'
        self.thisperiodbtn.connect('clicked', self.thisperiod_cb)

        self.prevperiodbtn = ToolButton('go-previous-paired')
        self.prevperiodbtn.props.accelerator = '<Ctrl>Left'
        self.prevperiodbtn.connect('clicked', self.prevperiod_cb)

        self.nextperiodbtn = ToolButton('go-next-paired')
        self.nextperiodbtn.props.accelerator = '<Ctrl>Right'
        self.nextperiodbtn.connect('clicked', self.nextperiod_cb)

        period_options = {DAY: _('Day'), WEEK: _('Week'), MONTH: _('Month'),
                          YEAR: _('Year'), FOREVER: _('Forever')}
        periodcombo = FilterToolItem('calendar', MONTH, period_options,
                                     _('Select period'))

        periodcombo.connect('changed', self.__period_changed_cb)

        headerbox.insert(periodcombo, -1)
        headerbox.insert(self.prevperiodbtn, -1)
        headerbox.insert(self.nextperiodbtn, -1)
        headerbox.insert(self.thisperiodbtn, -1)

        headerbox.insert(self._period_label_item, -1)
        return headerbox

    def show_header_controls(self):
        for child in self.headerbox.get_children():
            child.show()
            if self._active_panel in (self.register, self.empty_panel):
                if child in (self.header_separator_visible,
                             self.export_image):
                    child.hide()
            elif self._active_panel == self.budget:
                if child in (self.newcreditbtn, self.newdebitbtn,
                             self.eraseitembtn, self.header_separator_visible,
                             self.export_image):
                    child.hide()
            elif self._active_panel == self.chart:
                # Use NOT here
                if child not in (self.newcreditbtn, self.newdebitbtn,
                                 self.header_separator_visible,
                                 self.export_image):
                    child.hide()

    def register_cb(self, widget):
        self._set_internal_panel(self.register)
        self.show_header_controls()
        self.newcreditbtn.set_tooltip(_("New Credit"))
        self.newdebitbtn.set_tooltip(_("New Debit"))

    def budget_cb(self, widget):
        self._set_internal_panel(self.budget)
        self.show_header_controls()

    def chart_cb(self, widget):
        self._set_internal_panel(self.chart)
        self.show_header_controls()
        self.newcreditbtn.set_tooltip(_("Show Credits"))
        self.newdebitbtn.set_tooltip(_("Show Debits"))

    def _set_internal_panel(self, widget):
        if self.screenbox.get_children():
            self.screenbox.remove(self.screenbox.get_children()[0])
        self.screenbox.pack_start(widget, True, True, 0)
        widget.show_all()
        self._active_panel = widget
        self.build_screen()

    def build_screen(self):
        self.build_visible_transactions()

        if hasattr(self._active_panel, 'build'):
            self._active_panel.build()

        self.update_header()
        self.update_summary()
        self.update_toolbar()

    def __empty_panel_btn_cb(self, button):
        self._set_internal_panel(self.register)
        self.register.new_credit()

    def __newcredit_cb(self, widget):
        if self._active_panel == self.chart:
            # in the case of chart, select the graphic
            self.chart.set_mode(self.chart.CHART_CREDIT)
            return

        # this check is used when the emptypanle is visible
        if self._active_panel != self.register:
            self._set_internal_panel(self.register)
        self.register.new_credit()

    def __newdebit_cb(self, widget):
        if self._active_panel == self.chart:
            # in the case of chart, select the graphic
            self.chart.set_mode(self.chart.CHART_DEBIT)
            return

        # this check is used when the emptypanle is visible
        if self._active_panel != self.register:
            self._set_internal_panel(self.register)
        self.register.new_debit()

    def __eraseitem_cb(self, widget):
        self.register.erase_item()
        self.build_screen()

    def update_header(self):
        if self.period == DAY:
            # TRANS: representation of the "Day" period
            text = self.period_start.strftime(_("%B %d, %Y"))

        elif self.period == WEEK:
            # TRANS: representation of the "Week of" period
            text = _('Week of') + self.period_start.strftime(_(" %B %d, %Y"))

        elif self.period == MONTH:
            # TRANS: representation of the "Month" period
            text = self.period_start.strftime(_("%B, %Y"))

        elif self.period == YEAR:
            # TRANS: representation of the "Year" period
            text = self.period_start.strftime(_("%Y"))

        elif self.period == FOREVER:
            text = _('Forever')

        self.periodlabel.set_markup(
            "<span size='xx-large' color='white'><b>" + text + "</b></span>")

    def update_summary(self):
        # Calculate starting balance.
        start = 0.0
        for t in self.data['transactions']:
            d = t['date']
            if d < self.period_start.toordinal():
                if t['type'] == 'credit':
                    start += t['amount']
                else:
                    start -= t['amount']

        # Calculate totals for this period.
        credit_count = 0
        credit_total = 0.0
        debit_count = 0
        debit_total = 0.0
        total = start
        for t in self.visible_transactions:
            if t['type'] == 'credit':
                credit_count += 1
                credit_total += t['amount']
                total += t['amount']
            else:
                debit_count += 1
                debit_total += t['amount']
                total -= t['amount']

        # Update Balance.
        if total >= 0.0:
            balancecolor = colors.CREDIT_COLOR
        else:
            balancecolor = colors.DEBIT_COLOR
        balance = \
            "<span size='xx-large' foreground='white'><b>%s %s</b></span>" % \
            (_('Balance: '), locale.currency(total))
        self.balancelabel.set_markup(balance)

        self.balance_evbox.modify_bg(
            Gtk.StateType.NORMAL, style.Color(balancecolor).get_gdk_color())

        self.startlabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            _('Starting Balance:'))
        self.startamountlabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            locale.currency(start))

        self.creditslabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            (_('%s in %d credits') % (locale.currency(credit_total),
                                      credit_count)))
        self.debitslabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            (_('%s in %d debits') % (locale.currency(debit_total),
                                     debit_count)))

    def update_toolbar(self):
        # Disable the navigation when Forever is selected.
        next_prev = self.period != FOREVER
        self.prevperiodbtn.set_sensitive(next_prev)
        self.thisperiodbtn.set_sensitive(next_prev)
        self.nextperiodbtn.set_sensitive(next_prev)

        # This is a HACK to translate the string properly
        # http://bugs.sugarlabs.org/ticket/3190
        if self.period == MONTH:
            text_previous_period = _('Previous Month')
            text_this_period = _('This Month')
            text_next_period = _('Next Month')
        elif self.period == WEEK:
            text_previous_period = _('Previous Week')
            text_this_period = _('This Week')
            text_next_period = _('Next Week')
        elif self.period == DAY:
            text_previous_period = _('Previous Day')
            text_this_period = _('This Day')
            text_next_period = _('Next Day')
        elif self.period == YEAR:
            text_previous_period = _('Previous Year')
            text_this_period = _('This Year')
            text_next_period = _('Next Year')

        # Update the label self.period to reflect the period.
        self.prevperiodbtn.set_tooltip(text_previous_period)
        self.thisperiodbtn.set_tooltip(text_this_period)
        self.nextperiodbtn.set_tooltip(text_next_period)

    def get_this_period(self):
        today = datetime.date.today()

        if self.period == DAY:
            return today

        elif self.period == WEEK:
            while today.weekday() != 0:
                today -= datetime.timedelta(days=1)
            return today

        elif self.period == MONTH:
            return datetime.date(today.year, today.month, 1)

        elif self.period == YEAR:
            return datetime.date(today.year, 1, 1)

        elif self.period == FOREVER:
            return datetime.date(1900, 1, 1)

    def get_next_period(self, start):
        if self.period == DAY:
            return start + datetime.timedelta(days=1)

        elif self.period == WEEK:
            return start + datetime.timedelta(days=7)

        elif self.period == MONTH:
            if start.month == 12:
                return datetime.date(start.year + 1, 1, 1)
            else:
                return datetime.date(start.year, start.month + 1, 1)

        elif self.period == YEAR:
            return datetime.date(start.year + 1, 1, 1)

    def get_prev_period(self, start):
        if self.period == DAY:
            return start - datetime.timedelta(days=1)

        elif self.period == WEEK:
            return start - datetime.timedelta(days=7)

        elif self.period == MONTH:
            if start.month == 1:
                return datetime.date(start.year - 1, 12, 1)
            else:
                return datetime.date(start.year, start.month - 1, 1)

        elif self.period == YEAR:
            return datetime.date(start.year - 1, 1, 1)

    def thisperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_this_period()
            self.build_screen()

    def nextperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_next_period(self.period_start)
            self.build_screen()

    def prevperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_prev_period(self.period_start)
            self.build_screen()

    def __period_changed_cb(self, widget, value):
        self.period = int(value)
        self.update_toolbar()

        # Jump to 'this period'.
        self.period_start = self.get_this_period()
        self.build_screen()

    def build_visible_transactions(self):
        if self.period == FOREVER:
            self.visible_transactions = self.data['transactions']

        else:
            period_start_ord = self.period_start.toordinal()
            period_end_ord = self.get_next_period(
                self.period_start).toordinal()

            self.visible_transactions = []
            for t in self.data['transactions']:
                d = t['date']
                if d >= period_start_ord and d < period_end_ord:
                    self.visible_transactions.append(t)

        self.visible_transactions.sort(lambda a, b: a['date'] - b['date'])

    def build_transaction_map(self):
        self.transaction_map = {}
        for t in self.data['transactions']:
            self.transaction_map[t['id']] = t

    def create_transaction(self, name='', type='debit', amount=0,
                           category='', date=datetime.date.today()):
        id = self.data['next_id']
        self.data['next_id'] += 1

        t = {
            'id': id,
            'name': name,
            'type': type,
            'amount': amount,
            'date': date.toordinal(),
            'category': category
        }
        self.data['transactions'].append(t)
        self.transaction_map[id] = t

        self.build_visible_transactions()

        return id

    def destroy_transaction(self, id):
        t = self.transaction_map[id]
        self.data['transactions'].remove(t)
        del self.transaction_map[id]

    def build_names(self):
        self.transaction_names = {}
        self.category_names = {}
        for t in self.data['transactions']:
            self.transaction_names[t['name']] = 1
            self.category_names[t['category']] = 1

    def create_test_data(self):
        cur_date = datetime.date.today()
        cur_date = datetime.date(cur_date.year, cur_date.month, 1)
        self.create_transaction('Initial Balance', type='credit', amount=632,
                                category='Initial Balance', date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Fix Car', amount=75.84,
                                category='Transportation', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Adopt Cat', amount=100, category='Pets',
                                date=cur_date)
        self.create_transaction('New Coat', amount=25.53, category='Clothing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent', amount=500, category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe', amount=5.20, category='Food',
                                date=cur_date)
        self.create_transaction('Groceries', amount=50.92, category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food', amount=5.40, category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck', type='credit', amount=700,
                                category='Paycheck', date=cur_date)
        self.create_transaction('Gas', amount=21.20, category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys', amount=10.95, category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister', amount=23.20,
                                category='Gifts', date=cur_date)

        self.build_transaction_map()
        self.build_names()

    def read_file(self, file_path):
        if self.metadata['mime_type'] != 'text/plain':
            return

        fd = open(file_path, 'r')
        try:
            text = fd.read()
            self.data = json.loads(text)
        finally:
            fd.close()

        if self.data['transactions']:
            self._set_internal_panel(self.register)
        self.show_header_controls()

        self.build_transaction_map()
        self.build_names()
        self.build_screen()

    def write_file(self, file_path):
        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'text/plain'

        fd = open(file_path, 'w')
        try:
            text = json.dumps(self.data)
            fd.write(text)
        finally:
            fd.close()

    def __save_image_cb(self, widget):
        image_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = self.chart.title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'image/png'

        # generate the image
        self.chart.generate_image(image_file.file, 800, 600)
        image_file.file.close()
        journal_entry.file_path = image_file.name

        # generate the preview
        preview_str = StringIO.StringIO()
        self.chart.generate_image(preview_str, activity.PREVIEW_SIZE[0],
                                  activity.PREVIEW_SIZE[1])
        journal_entry.metadata['preview'] = dbus.ByteArray(
            preview_str.getvalue())

        logging.error('Create %s image file', image_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(
            _('Chart created'), _('Open in the Journal'),
            journal_entry.object_id)

    def _show_journal_alert(self, title, msg, object_id):
        open_alert = Alert()
        open_alert.props.title = title
        open_alert.props.msg = msg
        open_icon = Icon(icon_name='zoom-activity')
        open_alert.add_button(Gtk.ResponseType.APPLY,
                              _('Show in Journal'), open_icon)
        open_icon.show()
        ok_icon = Icon(icon_name='dialog-ok')
        open_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
        ok_icon.show()
        # Remove other alerts
        for alert in self._alerts:
            self.remove_alert(alert)

        self.add_alert(open_alert)
        open_alert.connect('response', self.__open_response_cb, object_id)
        open_alert.show()

    def __open_response_cb(self, alert, response_id, object_id):
        if response_id is Gtk.ResponseType.APPLY:
            activity.show_object_in_journal(object_id)
        self.remove_alert(alert)

    def __export_data_to_chart_cb(self, widget, type_movement, period):
        """
        type_movement = 'debit' or 'credit'
        period
            DAY = 0
            MONTH = 2
        """
        logging.debug('export data %s %s', type_movement, period)

        chart_params = {}
        axis = {'tickFont': 'Sans', 'labelFont': 'Sans', 'labelFontSize': 14,
                'labelColor': '#666666', 'lineColor': '#b3b3b3',
                'tickColor': '#000000', 'tickFontSize': 12}
        chart_params['font_options'] = {
            'titleFont': 'Sans', 'titleFontSize': 12, 'titleColor': '#000000',
            'axis': axis}

        if type_movement == 'credit':
            what_filter = 'Credits'
        elif type_movement == 'debit':
            what_filter = 'Debits'
        else:
            logging.error('ERROR type_movement should be credit or debit')

        if period == DAY:
            when = 'day'
        elif period == MONTH:
            when = 'month'
        else:
            logging.error('ERROR period should be DAY or MONTH')

        title = _('%s by %s') % (what_filter, when)
        chart_params['title'] = title
        chart_params['x_label'] = ''
        chart_params['y_label'] = ''
        chart_params['current_chart.type'] = 1
        xo_color = profile.get_color()
        chart_params['chart_line_color'] = xo_color.get_stroke_color()
        chart_params['chart_color'] = xo_color.get_fill_color()

        """
        'chart_data': [
            ['hello', 200.0],
            ['mrch', 100.0]],
        """
        transactions = self.data['transactions']

        groups = {}
        for transaction in transactions:
            if transaction['type'] == type_movement:
                date = transaction['date']
                if period == DAY:
                    group = date
                elif period == MONTH:
                    d = datetime.date.fromordinal(date)
                    group = datetime.date(d.year, d.month, 1).toordinal()
                if group in groups.keys():
                    groups[group] = groups[group] + transaction['amount']
                else:
                    groups[group] = transaction['amount']

        data = []
        for group in sorted(groups.keys()):
            if period == DAY:
                label = datetime.date.fromordinal(group).isoformat()
            elif period == MONTH:
                d = datetime.date.fromordinal(group)
                label = '%s-%s' % (d.year, d.month)

            data.append([label, groups[group]])

        chart_params['chart_data'] = data

        logging.debug('chart_data %s', chart_params)

        # save to the journal
        data_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.json')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'application/x-chart-activity'
        journal_entry.metadata['activity'] = 'org.sugarlabs.SimpleGraph'

        json.dump(chart_params, data_file.file)
        data_file.file.close()
        journal_entry.file_path = data_file.name

        logging.debug('Create %s data file', data_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(
            _('Exported data'), _('Open in the Journal'),
            journal_entry.object_id)
예제 #51
0
    def build_toolbar(self):
        self.max_participants = 4

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        create_toolbar = ToolbarButton()
        create_toolbar.props.page = Gtk.Toolbar()
        create_toolbar.props.icon_name = 'magicpen'
        create_toolbar.props.label = _('Create')
        toolbar_box.toolbar.insert(create_toolbar, -1)
        self._insert_create_tools(create_toolbar)

        color = ColorToolButton('color')
        color.connect('notify::color', self.__color_notify_cb)
        toolbar_box.toolbar.insert(color, -1)
        color.show()

        random = ToggleToolButton('colorRandom')
        random.set_tooltip(_('Toggle random color'))
        toolbar_box.toolbar.insert(random, -1)
        random.set_active(True)
        random.connect('toggled', self.__random_toggled_cb)
        random.show()

        color.random = random
        random.color = color

        random.timeout_id = GLib.timeout_add(100, self.__timeout_cb, random)

        self._insert_stop_play_button(toolbar_box.toolbar)

        clear_trace = ToolButton('clear-trace')
        clear_trace.set_tooltip(_('Clear Trace Marks'))
        clear_trace.set_accelerator(_('<ctrl>x'))
        clear_trace.connect('clicked', self.clear_trace_cb)
        clear_trace.set_sensitive(False)
        toolbar_box.toolbar.insert(clear_trace, -1)
        clear_trace.show()
        self.clear_trace = clear_trace

        self._insert_clear_all_button(toolbar_box.toolbar)

        load_example = ToolButton('load-sample')
        load_example.set_tooltip(_('Show sample projects'))
        load_example.connect('clicked', self._create_store)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(load_example, -1)
        load_example.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)
        stop.show()

        separator = Gtk.SeparatorToolItem()
        activity_button.props.page.insert(separator, -1)
        separator.show()

        export_json = ToolButton('save-as-json')
        export_json.set_tooltip(_('Export tracked objects to journal'))
        export_json.connect('clicked', self._export_json_cb)
        activity_button.props.page.insert(export_json, -1)
        export_json.show()

        load_project = ToolButton('load-project')
        load_project.set_tooltip(_('Load project from journal'))
        load_project.connect('clicked', self._load_project)
        activity_button.props.page.insert(load_project, -1)
        load_project.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        create_toolbar.set_expanded(True)
        return toolbar_box
예제 #52
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self._book_model = BookModel()
        self._actual_page = 1

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1

        # get the language configured by the user
        # will be used to translate the names of the media files
        locale = os.environ.get('LANG', '')
        language_location = locale.split('.', 1)[0].lower()
        self._language = language_location.split('_')[0]
        if self._language == 'en':
            # we don't need translate the file names if langauage is 'en'
            self._language = None
        self._translations = None
        if self._language is not None:
            # read the translations file if available
            dict_path = os.path.join(activity.get_bundle_path(), 'data',
                                     "%s_dict.csv" % self._language)
            logging.debug('Looking for media translation dictionary %s',
                          dict_path)
            if os.path.exists(dict_path):
                logging.debug('Loading translations')
                self._translations = {}
                with open(dict_path) as dict_file:
                    for line in dict_file:
                        words = line.split(',')
                        self._translations[words[0]] = words[1].strip()

        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        self._edit_toolbar = EditToolbar()
        edit_toolbar_button = ToolbarButton(
            page=self._edit_toolbar, icon_name='toolbar-edit')
        toolbar_box.toolbar.insert(edit_toolbar_button, 1)

        set_background_button = ToolButton('set-background')
        set_background_button.set_tooltip(_('Set the background'))
        set_background_button.connect('clicked',
                                      self.__set_background_clicked_cb)
        toolbar_box.toolbar.insert(set_background_button, -1)

        insert_picture_button = ToolButton('insert-picture')
        insert_picture_button.set_tooltip(_('Add a picture'))
        insert_picture_button.connect('clicked',
                                      self.__add_image_clicked_cb)
        toolbar_box.toolbar.insert(insert_picture_button, -1)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self._duplicate_page_button = ToolButton()
        icon = Icon(icon_name='edit-duplicate', xo_color=profile.get_color())
        self._duplicate_page_button.set_icon_widget(icon)

        self._duplicate_page_button.set_tooltip(_('Duplicate page'))
        self._duplicate_page_button.connect(
            'clicked', self.__duplicate_page_clicked_cb)
        toolbar_box.toolbar.insert(self._duplicate_page_button, -1)

        self._add_page_button = ToolButton('list-add')
        self._add_page_button.set_tooltip(_('Add a page'))
        self._add_page_button.connect('clicked', self.__add_page_clicked_cb)
        toolbar_box.toolbar.insert(self._add_page_button, -1)

        self._remove_button = ToolButton('edit-delete')
        self._remove_button.set_tooltip(_('Remove an image or page'))
        self._remove_button.connect('clicked', self.__remove_clicked_cb)
        toolbar_box.toolbar.insert(self._remove_button, -1)

        self._prev_page_button = ToolButton('go-previous-paired')
        self._prev_page_button.set_tooltip(_('Previous page'))
        self._prev_page_button.connect('clicked', self.__prev_page_clicked_cb)
        toolbar_box.toolbar.insert(self._prev_page_button, -1)

        self._next_page_button = ToolButton('go-next-paired')
        self._next_page_button.set_tooltip(_('Next page'))
        self._next_page_button.connect('clicked', self.__next_page_clicked_cb)
        toolbar_box.toolbar.insert(self._next_page_button, -1)

        self._view_list_button = ToggleToolButton('view-list')
        self._view_list_button.set_tooltip(_('View pages'))
        self._view_list_button.connect('toggled', self.__view_list_toggled_cb)
        toolbar_box.toolbar.insert(self._view_list_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)

        # add export buttons
        activity_toolbar = activity_button.props.page
        epub_button = ToolButton('save-as-epub')
        epub_button.set_tooltip(_('Save as EPUB book'))
        epub_button.connect('clicked', self.__save_ebook_clicked_cb)
        activity_toolbar.insert(epub_button, -1)
        epub_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        edition_canvas = self.create_edition_canvas()

        hbox = Gtk.HBox()
        self._preview_panel = PreviewPanel(self._book_model.get_pages())
        self._preview_panel.connect('page-activated', self.__page_activated_cb)
        self._preview_panel.connect('page-moved', self.__page_moved_cb)
        hbox.pack_start(self._preview_panel, False, False, 0)
        hbox.pack_start(edition_canvas, True, True, 0)

        self.set_canvas(hbox)
        self.prepare_edit_toolbar()
        self._update_page_buttons()

        self.show_all()
        self._preview_panel.hide()
예제 #53
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self.set_title('FotoToon')

        self._max_participants = 1
        self.page = None

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page
        toolbar_box.toolbar.insert(activity_button, 0)

        edit_toolbar_btn = ToolbarButton()
        edit_toolbar = Gtk.Toolbar()
        edit_toolbar_btn.props.page = edit_toolbar
        edit_toolbar_btn.props.icon_name = 'toolbar-edit'
        edit_toolbar_btn.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar_btn, -1)

        view_toolbar_btn = ToolbarButton()
        view_toolbar = Gtk.Toolbar()
        view_toolbar_btn.props.page = view_toolbar
        view_toolbar_btn.props.icon_name = 'toolbar-view'
        view_toolbar_btn.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar_btn, -1)

        slideview_btn = ToggleToolButton('slideshow')
        slideview_btn.set_tooltip(_('Slideshow'))
        slideview_btn.set_active(False)
        slideview_btn.connect('clicked', self._switch_view_mode, False)
        view_toolbar.insert(slideview_btn, -1)
        slideview_btn.show()

        slideview_timings_btn = ToggleToolButton('slideshow-stopwatch')
        slideview_timings_btn.set_tooltip(_('Slideshow with Timings'))
        slideview_timings_btn.set_active(False)
        slideview_timings_btn.connect('clicked', self._switch_view_mode, True)
        view_toolbar.insert(slideview_timings_btn, -1)
        slideview_timings_btn.show()

        time_button = ToolButton('stopwatch')
        time_button.set_tooltip(_('Set Image Duration in Slideshow (Seconds)'))
        view_toolbar.insert(time_button, -1)
        time_button.show()

        self._time_spin = Gtk.SpinButton.new_with_range(MIN_TIME, MAX_TIME, 1)
        self._time_spin.connect('value-changed', self.__time_spin_changed_cb)
        self._time_spin.props.value = DEFAULT_TIME
        self._time_spin.props.update_policy = \
            Gtk.SpinButtonUpdatePolicy.IF_VALID

        palette = time_button.get_palette()
        palette.connect('popup', self.__time_button_popup_cb)
        time_button.connect(
            'clicked', lambda *args: palette.popup(immediate=True,
                                                   state=Palette.SECONDARY))

        alignment = Gtk.Alignment()
        alignment.set_padding(style.DEFAULT_PADDING, style.DEFAULT_PADDING,
                              style.DEFAULT_PADDING, style.DEFAULT_PADDING)
        alignment.add(self._time_spin)
        self._time_spin.show()
        palette.set_content(alignment)
        alignment.show()

        fullscreen_btn = ToolButton('view-fullscreen')
        fullscreen_btn.set_tooltip(_('Fullscreen'))
        fullscreen_btn.props.accelerator = '<Alt>Return'
        fullscreen_btn.connect('clicked', lambda w: self.fullscreen())
        view_toolbar.insert(fullscreen_btn, -1)
        fullscreen_btn.show()

        self.set_toolbar_box(toolbar_box)

        toolbar = toolbar_box.toolbar

        self.page = Page()

        self.globes_manager = GlobesManager(toolbar, edit_toolbar, self)

        # fonts
        self._text_button = ToolbarButton()
        self._text_button.props.page = TextToolbar(self.page)
        self._text_button.props.icon_name = 'format-text-size'
        self._text_button.props.label = _('Text')
        self._toolbar_box.toolbar.insert(self._text_button, -1)

        reorder_img_btn = ToolButton('thumbs-view')
        reorder_img_btn.set_icon_name('thumbs-view')
        reorder_img_btn.set_tooltip(_('Change image order'))
        reorder_img_btn.connect('clicked', self.__image_order_cb)
        edit_toolbar.insert(reorder_img_btn, -1)
        reorder_img_btn.show()

        bgchange = ToolButton(icon_name='contract-coordinates')
        bgchange.set_tooltip(_('Edit background image'))
        bgchange.connect('clicked', self.__bgchange_clicked_cb)
        edit_toolbar.insert(bgchange, -1)
        bgchange.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)

        toolbar_box.toolbar.insert(separator, -1)

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()

        # add export button

        separator_2 = Gtk.SeparatorToolItem()
        separator_2.show()
        activity_toolbar.insert(separator_2, -1)

        self.bt_save_as_image = ToolButton()
        self.bt_save_as_image.props.icon_name = 'save-as-image'
        self.bt_save_as_image.connect('clicked', self.write_image)
        self.bt_save_as_image.set_tooltip(_('Save as Image'))
        activity_toolbar.insert(self.bt_save_as_image, -1)
        self.bt_save_as_image.show()

        save_as_pdf = ToolButton()
        save_as_pdf.props.icon_name = 'save-as-pdf'
        save_as_pdf.connect('clicked', self._save_as_pdf)
        save_as_pdf.set_tooltip(_('Save as a Book (PDF)'))
        activity_toolbar.insert(save_as_pdf, -1)
        save_as_pdf.show()

        save_as_ogg = ToolButton()
        save_as_ogg.props.icon_name = 'save-as-ogg'
        save_as_ogg.connect('clicked', self.__save_as_ogg_cb)
        save_as_ogg.set_tooltip(_('Save as a Movie (OGG)'))
        activity_toolbar.insert(save_as_ogg, -1)
        Gst.init(None)
        if Gst.version_string() != 'GStreamer 1.0.10':
            save_as_ogg.show()

        activity_button.page.title.connect("focus-in-event", self.on_title)

        scrolled = Gtk.ScrolledWindow()
        # scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
        scrolled.add_with_viewport(self.page)
        scrolled.set_kinetic_scrolling(False)
        scrolled.show_all()

        self._slideview = SlideView(self)
        self._slideview.show_all()

        self._notebook = Gtk.Notebook()
        self._notebook.set_show_tabs(False)
        self._notebook.append_page(scrolled, None)
        self._notebook.append_page(self._slideview, None)
        self._notebook.show_all()

        if self._jobject.file_path is None or self._jobject.file_path == '':
            empty_widget = EmptyWidget()
            empty_widget.connect('choose-image', self.__add_image)
            self.set_canvas(empty_widget)
        else:
            self.set_canvas(self._notebook)

        self.show()
        self.metadata['mime_type'] = 'application/x-fototoon-activity'

        self.page.empty_page = handle.object_id is None
        self._key_press_signal_id = None
예제 #54
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        if HASTOOLBARBOX:
            self.max_participants = 1
            toolbar_box = ToolbarBox()
            self.set_toolbar_box(toolbar_box)
            activity_button = ActivityToolbarButton(self)
            toolbar_box.toolbar.insert(activity_button, 0)

            separator = Gtk.SeparatorToolItem()
            separator.props.draw = True
            activity_button.props.page.insert(separator, -1)
            separator.show()

            tool = ToolButton('pdf-export')
            tool.set_tooltip(_('Portable Document Format (PDF)'))
            tool.connect('clicked', self.__export_pdf_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolButton('png-export')
            tool.set_tooltip(_('Portable Network Graphic (PNG)'))
            tool.connect('clicked', self.__export_png_cb)
            activity_button.props.page.insert(tool, -1)
            tool.show()

            tool = ToolbarButton()
            self.edit_toolbar = EditToolbar(self)
            tool.props.page = self.edit_toolbar
            tool.props.icon_name = 'toolbar-edit'
            ##tool.props.label = _('Edit'),
            toolbar_box.toolbar.insert(tool, -1)

            #self._undo = UndoManager.UndoManager(self,
            #                                     self.edit_toolbar.undo.child,
            #                                     self.edit_toolbar.redo.child)

            self._undo = UndoManager.UndoManager(self, self.edit_toolbar.undo,
                                                 self.edit_toolbar.redo)

            self.__build_main_canvas_area()

            tool = ToolbarButton()
            tool.props.page = ViewToolbar(self._main_area)
            tool.props.icon_name = 'toolbar-view'
            tool.props.label = _('View')
            toolbar_box.toolbar.insert(tool, -1)

            tool = ToolbarButton()
            self.text_format_toolbar = TextAttributesToolbar(self._main_area)
            tool.props.page = self.text_format_toolbar
            tool.props.icon_name = 'toolbar-text'
            tool.props.label = _('Text')
            toolbar_box.toolbar.insert(tool, -1)
            # self._main_area.set_text_attributes(self.text_format_toolbar)

            self.thought_toolbar = ToolbarButton()
            self.thought_toolbar.props.page = ThoughtsToolbar(self)
            self.thought_toolbar.props.icon_name = 'thought'
            self.thought_toolbar.props.label = _('Thought Type')
            toolbar_box.toolbar.insert(self.thought_toolbar, -1)

            self.action_buttons = ActionButtons(self)

            toolbar_box.show_all()

        else:
            # Use old <= 0.84 toolbar design
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)

            activity_toolbar = toolbox.get_activity_toolbar()
            keep_palette = activity_toolbar.keep.get_palette()

            menu_item = MenuItem(_('Portable Document Format (PDF)'))
            menu_item.connect('activate', self.__export_pdf_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            menu_item = MenuItem(_('Portable Network Graphic (PNG)'))
            menu_item.connect('activate', self.__export_png_cb)
            keep_palette.menu.append(menu_item)
            menu_item.show()

            self.edit_toolbar = EditToolbar(self)
            toolbox.add_toolbar(_('Edit'), self.edit_toolbar)
            separator = Gtk.SeparatorToolItem()
            self.edit_toolbar.insert(separator, 0)
            self.edit_toolbar.show()

            self._undo = UndoManager.UndoManager(self,
                                                 self.edit_toolbar.undo.child,
                                                 self.edit_toolbar.redo.child)

            self.__build_main_canvas_area()

            view_toolbar = ViewToolbar(self._main_area)
            toolbox.add_toolbar(_('View'), view_toolbar)

            activity_toolbar = toolbox.get_activity_toolbar()
            activity_toolbar.share.props.visible = False
            toolbox.set_current_toolbar(1)

        self.show_all()

        self.__configure_cb(None)

        self._mode = MMapArea.MODE_TEXT
        self._main_area.set_mode(self._mode)
        self.set_focus_child(self._main_area)
예제 #55
0
    def build_toolbar(self):

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, -1)
        activity_button.show()

        barra = toolbar_box.toolbar

        separador1 = Gtk.SeparatorToolItem()
        separador1.props.draw = True
        barra.insert(separador1, 1)

        item1 = Gtk.ToolItem()
        self.label_radio1 = Gtk.Label()
        self.label_radio1.set_text(_('Circles between') + ' ')
        item1.add(self.label_radio1)
        barra.insert(item1, 2)

        grayed = Gdk.Color(20000.0, 20000.0, 20000.0)

        item2 = Gtk.ToolItem()
        self.cradio1 = Gtk.SpinButton()
        self.cradio1.modify_bg(Gtk.StateType.NORMAL, grayed)
        self.cradio1.set_range(1, 20)
        self.cradio1.set_increments(1, 2)
        self.cradio1.props.value = self.radio_uno
        self.cradio1_handler = self.cradio1.connect('notify::value', self.cradio1_valor)
        item2.add(self.cradio1)
        barra.insert(item2, 3)

        item3 = Gtk.ToolItem()
        self.label_and = Gtk.Label()
        self.label_and.set_text(' ' + _('and') + ' ')
        item3.add(self.label_and)
        barra.insert(item3, 4)

        item4 = Gtk.ToolItem()
        self.cradio2 = Gtk.SpinButton()
        self.cradio2.modify_bg(Gtk.StateType.NORMAL, grayed)
        self.cradio2.set_range(1, 20)
        self.cradio2.set_increments(1, 2)
        self.cradio2.props.value = self.radio_dos
        self.cradio2_handler = self.cradio2.connect('notify::value', self.cradio2_valor)
        item4.add(self.cradio2)
        barra.insert(item4, 5)

        separator1 = Gtk.SeparatorToolItem()
        separator1.props.draw = True
        separator1.set_expand(False)
        barra.insert(separator1,6)

        save_button = ToolButton('filesave')
        save_button.set_tooltip(_('Save Image'))
        save_button.connect('clicked', self._savebutton_cb)
        barra.insert(save_button, 7)
        save_button.show()

        separator2 = Gtk.SeparatorToolItem()
        separator2.props.draw = False
        separator2.set_expand(True)
        barra.insert(separator2,8)

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        barra.insert(stop_button, 9)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)

        toolbar_box.show_all()
예제 #56
0
파일: activity.py 프로젝트: sugarlabs/chat
    def __init__(self, handle):
        pservice = presenceservice.get_instance()
        self.owner = pservice.get_owner()

        self._ebook_mode_detector = EbookModeDetector()

        self.chatbox = ChatBox(
            self.owner, self._ebook_mode_detector.get_ebook_mode())
        self.chatbox.connect('open-on-journal', self.__open_on_journal)

        super(Chat, self).__init__(handle)

        self._entry = None
        self._has_alert = False
        self._has_osk = False

        self._setup_canvas()

        self._entry.grab_focus()

        toolbar_box = ToolbarBox()
        self.set_toolbar_box(toolbar_box)

        self.activity_button = ActivityButton(self)
        toolbar_box.toolbar.insert(self.activity_button, 0)
        self.activity_button.show()

        title_entry = TitleEntry(self)
        toolbar_box.toolbar.insert(title_entry, -1)
        title_entry.show()

        description_item = DescriptionItem(self)
        toolbar_box.toolbar.insert(description_item, -1)
        description_item.show()

        self._share_button = ShareButton(self)
        toolbar_box.toolbar.insert(self._share_button, -1)
        self._share_button.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)
        toolbar_box.show_all()

        # Chat is room or one to one:
        self._chat_is_room = False
        self.text_channel = None

        if _HAS_SOUND:
            self.element = Gst.ElementFactory.make('playbin', 'Player')

        if self.shared_activity:
            # we are joining the activity following an invite
            self._entry.props.placeholder_text = \
                _('Please wait for a connection before starting to chat.')
            self.connect('joined', self._joined_cb)
            if self.get_shared():
                # we have already joined
                self._joined_cb(self)
        elif handle.uri:
            # XMPP non-sugar3 incoming chat, not sharable
            self._share_button.props.visible = False
            self._one_to_one_connection(handle.uri)
        else:
            # we are creating the activity
            if not self.metadata or self.metadata.get(
                    'share-scope', activity.SCOPE_PRIVATE) == \
                    activity.SCOPE_PRIVATE:
                # if we are in private session
                self._alert(_('Off-line'), _('Share, or invite someone.'))
            else:
                # resume of shared activity from journal object without invite
                self._entry.props.placeholder_text = \
                    _('Please wait for a connection before starting to chat.')
            self.connect('shared', self._shared_cb)
예제 #57
0
class Finance(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self.set_title(_("Finance"))
        self.max_participants = 1

        # Initialize database.
        # data
        #   next_id
        #   transactions
        #     id, name, type, amount, date, category
        #   budgets
        #     category, period, amount, budget
        self.data = {'next_id': 0, 'transactions': [], 'budgets': {}}

        self.transaction_map = {}
        self.visible_transactions = []

        self.undo_transaction_map = []
        self.undo_id_map = []

        self.redo_id_map = []
        self.redo_transaction_map = []

        self.transaction_names = {}
        self.category_names = {}

        # Initialize view period to the first of the month.
        self.period = MONTH
        self.period_start = self.get_this_period()

        # Create screens.
        self.register = registerscreen.RegisterScreen(self)
        self.chart = chartscreen.ChartScreen(self)
        self.budget = budgetscreen.BudgetScreen(self)

        self.build_toolbox()

        self.screenbox = Gtk.VBox()

        self.headerbox = self.build_header()
        self._active_panel = None

        # Add the summary data.

        self.startlabel = Gtk.Label()
        self.startamountlabel = Gtk.Label()
        self.creditslabel = Gtk.Label()
        self.debitslabel = Gtk.Label()
        self.balancelabel = Gtk.Label()
        self.balancelabel.props.margin_left = style.DEFAULT_SPACING
        self.balancelabel.props.margin_right = style.DEFAULT_SPACING

        font_size = int(style.FONT_SIZE * 1.25)
        font = Pango.FontDescription("Sans %d" % font_size)
        for label in (self.startlabel, self.startamountlabel,
                      self.creditslabel, self.debitslabel):
            label.modify_font(font)
            label.set_hexpand(True)
            label.set_halign(Gtk.Align.START)
            label.props.margin = style.DEFAULT_PADDING

        self.balance_evbox = Gtk.EventBox()
        self.balance_evbox.add(self.balancelabel)
        summarybox = Gtk.Grid()
        summarybox.attach(self.startlabel, 0, 0, 1, 1)
        summarybox.attach(self.startamountlabel, 0, 1, 1, 1)
        summarybox.attach(self.creditslabel, 1, 0, 1, 1)
        summarybox.attach(self.debitslabel, 1, 1, 1, 1)
        summarybox.attach(self.balance_evbox, 2, 0, 1, 2)
        self.balance_evbox.set_halign(Gtk.Align.END)

        summary_evbox = Gtk.EventBox()
        summary_evbox.add(summarybox)
        summary_evbox.modify_bg(Gtk.StateType.NORMAL,
                                style.Color('#666666').get_gdk_color())
        summary_evbox.set_size_request(-1, style.GRID_CELL_SIZE)

        vbox = Gtk.VBox()

        vbox.pack_start(self.headerbox, False, False, 0)
        vbox.pack_start(self.screenbox, True, True, 0)
        vbox.pack_start(summary_evbox, False, False, 0)

        # Start with the empty screen.
        self.empty_panel = emptypanel.create_empty_panel(
            'row-insert-credit', _('Add some credit or debit to get started!'),
            _('Add credit'), self.__empty_panel_btn_cb)

        self._set_internal_panel(self.empty_panel)

        # This has to happen last, because it calls the read_file
        # method when restoring from the Journal.
        self.set_canvas(vbox)

        self.show_all()
        self.show_header_controls()

        if os.getenv('FINANCE_TEST'):
            self.create_test_data()
            self._set_internal_panel(self.register)

    def build_toolbox(self):

        view_tool_group = None
        registerbtn = RadioToolButton()
        registerbtn.props.icon_name = 'view-list'
        registerbtn.props.label = _('Register')
        registerbtn.set_tooltip(_("Register"))
        registerbtn.props.group = view_tool_group
        view_tool_group = registerbtn
        registerbtn.props.accelerator = '<Ctrl>1'
        registerbtn.connect('clicked', self.register_cb)

        budgetbtn = RadioToolButton()
        budgetbtn.props.icon_name = 'budget'
        budgetbtn.props.label = _('Budget')
        budgetbtn.set_tooltip(_("Budget"))
        budgetbtn.props.group = view_tool_group
        budgetbtn.props.accelerator = '<Ctrl>2'
        budgetbtn.connect('clicked', self.budget_cb)

        chartbtn = RadioToolButton()
        chartbtn.props.icon_name = 'chart'
        chartbtn.props.label = _('Chart')
        chartbtn.set_tooltip(_("Chart"))
        chartbtn.props.group = view_tool_group
        chartbtn.props.accelerator = '<Ctrl>3'
        chartbtn.connect('clicked', self.chart_cb)

        helpbutton = self._create_help_button()
        helpbutton.show_all()

        self.toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        self.toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.toolbar_box.toolbar.insert(registerbtn, -1)
        self.toolbar_box.toolbar.insert(budgetbtn, -1)
        self.toolbar_box.toolbar.insert(chartbtn, -1)

        self.toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.toolbar_box.toolbar.insert(helpbutton, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self.toolbar_box.toolbar.insert(separator, -1)

        self.toolbar_box.toolbar.insert(StopButton(self), -1)
        self.set_toolbar_box(self.toolbar_box)

        activity_button.page.insert(self._create_export_button(), -1)

        self.toolbar_box.show_all()

    def _create_export_button(self):
        # Add expoprt button
        export_data = ToolButton('save-as-data')

        export_data.props.tooltip = _('Export data')
        export_data.props.hide_tooltip_on_click = False
        export_data.palette_invoker.props.toggle_palette = True
        export_data.show()

        menu_box = PaletteMenuBox()
        export_data.props.palette.set_content(menu_box)

        menu_item = PaletteMenuItem(text_label=_('Export credits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb, 'credit',
                          DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by day'))
        menu_item.connect('activate', self.__export_data_to_chart_cb, 'debit',
                          DAY)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export credits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb, 'credit',
                          MONTH)
        menu_box.append_item(menu_item)

        menu_item = PaletteMenuItem(text_label=_('Export debits by month'))
        menu_item.connect('activate', self.__export_data_to_chart_cb, 'debit',
                          MONTH)
        menu_box.append_item(menu_item)

        menu_box.show_all()
        return export_data

    def _create_help_button(self):
        helpitem = HelpButton()
        helpitem.add_section(_('Register'), icon='view-list')
        helpitem.add_paragraph(registerscreen.REGISTER_HELP)
        helpitem.add_section(_('Budget'), icon='budget')
        helpitem.add_paragraph(budgetscreen.BUDGET_HELP)
        helpitem.add_section(_('Chart'), icon='chart')
        helpitem.add_paragraph(chartscreen.CHART_HELP)
        return helpitem

    def build_header(self):
        # Add the header.
        self.periodlabel = Gtk.Label()
        self.periodlabel.set_padding(10, 0)
        self._period_label_item = Gtk.ToolItem()
        self._period_label_item.add(self.periodlabel)
        self.periodlabel.set_halign(Gtk.Align.END)
        self._period_label_item.set_size_request(style.GRID_CELL_SIZE * 5, -1)

        headerbox = Gtk.Toolbar()
        headerbox.modify_bg(Gtk.StateType.NORMAL,
                            style.Color('#424242').get_gdk_color())
        headerbox.set_size_request(-1, style.GRID_CELL_SIZE)

        # register buttons
        self.newcreditbtn = ToolButton('row-insert-credit')
        self.newcreditbtn.set_tooltip(_("New Credit"))
        self.newcreditbtn.props.accelerator = '<Ctrl>A'
        self.newcreditbtn.connect('clicked', self.__newcredit_cb)

        self.newdebitbtn = ToolButton('row-insert-debit')
        self.newdebitbtn.set_tooltip(_("New Debit"))
        self.newdebitbtn.props.accelerator = '<Ctrl>D'
        self.newdebitbtn.connect('clicked', self.__newdebit_cb)

        self.undoactionbtn = UndoButton()
        self.undoactionbtn.connect('clicked', self.__undoaction_cb)

        self.redoactionbtn = RedoButton()
        self.redoactionbtn.connect('clicked', self.__redoaction_cb)

        self.eraseitembtn = ToolButton('basket')
        self.eraseitembtn.set_tooltip(_("Erase Transaction"))
        self.eraseitembtn.props.accelerator = '<Ctrl>E'
        self.eraseitembtn.connect('clicked', self.__eraseitem_cb)

        headerbox.insert(self.newcreditbtn, -1)
        headerbox.insert(self.newdebitbtn, -1)
        headerbox.insert(self.eraseitembtn, -1)
        headerbox.insert(self.undoactionbtn, -1)
        headerbox.insert(self.redoactionbtn, -1)

        self.header_separator_visible = Gtk.SeparatorToolItem()
        headerbox.insert(self.header_separator_visible, -1)

        self.export_image = ToolButton('save-as-image')
        self.export_image.set_tooltip(_("Save as Image"))
        self.export_image.connect('clicked', self.__save_image_cb)
        headerbox.insert(self.export_image, -1)

        self._header_separator = Gtk.SeparatorToolItem()
        self._header_separator.props.draw = False
        self._header_separator.set_expand(True)
        headerbox.insert(self._header_separator, -1)

        # period controls
        self.thisperiodbtn = ToolButton('go-down')
        self.thisperiodbtn.props.accelerator = '<Ctrl>Down'
        self.thisperiodbtn.connect('clicked', self.thisperiod_cb)

        self.prevperiodbtn = ToolButton('go-previous-paired')
        self.prevperiodbtn.props.accelerator = '<Ctrl>Left'
        self.prevperiodbtn.connect('clicked', self.prevperiod_cb)

        self.nextperiodbtn = ToolButton('go-next-paired')
        self.nextperiodbtn.props.accelerator = '<Ctrl>Right'
        self.nextperiodbtn.connect('clicked', self.nextperiod_cb)

        period_options = {
            DAY: _('Day'),
            WEEK: _('Week'),
            MONTH: _('Month'),
            YEAR: _('Year'),
            FOREVER: _('Forever')
        }
        periodcombo = FilterToolItem('calendar', MONTH, period_options,
                                     _('Select period'))

        periodcombo.connect('changed', self.__period_changed_cb)

        headerbox.insert(periodcombo, -1)
        headerbox.insert(self.prevperiodbtn, -1)
        headerbox.insert(self.nextperiodbtn, -1)
        headerbox.insert(self.thisperiodbtn, -1)

        headerbox.insert(self._period_label_item, -1)
        return headerbox

    def show_header_controls(self):
        for child in self.headerbox.get_children():
            child.show()
            if self._active_panel in (self.register, self.empty_panel):
                if child in (self.header_separator_visible, self.export_image):
                    child.hide()
            elif self._active_panel == self.budget:
                if child in (self.newcreditbtn, self.newdebitbtn,
                             self.eraseitembtn, self.undoactionbtn,
                             self.redoactionbtn, self.header_separator_visible,
                             self.export_image):
                    child.hide()
            elif self._active_panel == self.chart:
                # Use NOT here
                if child not in (self.newcreditbtn, self.newdebitbtn,
                                 self.header_separator_visible,
                                 self.export_image):
                    child.hide()

    def register_cb(self, widget):
        self._set_internal_panel(self.register)
        self.show_header_controls()
        self.newcreditbtn.set_tooltip(_("New Credit"))
        self.newdebitbtn.set_tooltip(_("New Debit"))

    def budget_cb(self, widget):
        self._set_internal_panel(self.budget)
        self.show_header_controls()

    def chart_cb(self, widget):
        self._set_internal_panel(self.chart)
        self.show_header_controls()
        self.newcreditbtn.set_tooltip(_("Show Credits"))
        self.newdebitbtn.set_tooltip(_("Show Debits"))

    def _set_internal_panel(self, widget):
        if self.screenbox.get_children():
            self.screenbox.remove(self.screenbox.get_children()[0])
        self.screenbox.pack_start(widget, True, True, 0)
        widget.show_all()
        self._active_panel = widget
        self.build_screen()

    def build_screen(self):
        self.build_visible_transactions()

        if hasattr(self._active_panel, 'build'):
            self._active_panel.build()

        self.update_header()
        self.update_summary()
        self.update_toolbar()

    def __empty_panel_btn_cb(self, button):
        self._set_internal_panel(self.register)
        self.register.new_credit()

    def __newcredit_cb(self, widget):
        if self._active_panel == self.chart:
            # in the case of chart, select the graphic
            self.chart.set_mode(self.chart.CHART_CREDIT)
            return

        # this check is used when the emptypanel is visible
        if self._active_panel != self.register:
            self._set_internal_panel(self.register)
        self.register.new_credit()

    def __newdebit_cb(self, widget):
        if self._active_panel == self.chart:
            # in the case of chart, select the graphic
            self.chart.set_mode(self.chart.CHART_DEBIT)
            return

        # this check is used when the emptypanel is visible
        if self._active_panel != self.register:
            self._set_internal_panel(self.register)
        self.register.new_debit()

    def __undoaction_cb(self, widget):
        self.undo_transaction()
        self.build_screen()

    def __redoaction_cb(self, widget):
        self.redo_transaction()
        self.build_screen()

    def __eraseitem_cb(self, widget):
        self.register.erase_item()
        self.build_screen()

    def update_header(self):
        if self.period == DAY:
            # TRANS: representation of the "Day" period
            text = self.period_start.strftime(_("%B %d, %Y"))

        elif self.period == WEEK:
            # TRANS: representation of the "Week of" period
            text = _('Week of') + self.period_start.strftime(_(" %B %d, %Y"))

        elif self.period == MONTH:
            # TRANS: representation of the "Month" period
            text = self.period_start.strftime(_("%B, %Y"))

        elif self.period == YEAR:
            # TRANS: representation of the "Year" period
            text = self.period_start.strftime(_("%Y"))

        elif self.period == FOREVER:
            text = _('Forever')

        self.periodlabel.set_markup("<span size='xx-large' color='white'><b>" +
                                    text + "</b></span>")

    def update_summary(self):
        # Calculate starting balance.
        start = 0.0
        for t in self.data['transactions']:
            d = t['date']
            if d < self.period_start.toordinal():
                if t['type'] == 'credit':
                    start += t['amount']
                else:
                    start -= t['amount']

        # Calculate totals for this period.
        credit_count = 0
        credit_total = 0.0
        debit_count = 0
        debit_total = 0.0
        total = start
        for t in self.visible_transactions:
            if t['type'] == 'credit':
                credit_count += 1
                credit_total += t['amount']
                total += t['amount']
            else:
                debit_count += 1
                debit_total += t['amount']
                total -= t['amount']

        # Update Balance.
        if total >= 0.0:
            balancecolor = colors.CREDIT_COLOR
        else:
            balancecolor = colors.DEBIT_COLOR
        balance = \
            "<span size='xx-large' foreground='white'><b>%s %s</b></span>" % \
            (_('Balance: '), locale.currency(total))
        self.balancelabel.set_markup(balance)

        self.balance_evbox.modify_bg(Gtk.StateType.NORMAL,
                                     style.Color(balancecolor).get_gdk_color())

        self.startlabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            _('Starting Balance:'))
        self.startamountlabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            locale.currency(start))

        self.creditslabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            (_('%(credit_total)s in %(credit_count)d credits') % {
                'credit_total': locale.currency(credit_total),
                'credit_count': credit_count
            }))

        self.debitslabel.set_markup(
            "<span foreground='white'><b>%s</b></span>" %
            (_('%(debit_total)s in %(debit_count)d debits') % {
                'debit_total': locale.currency(debit_total),
                'debit_count': debit_count
            }))

    def update_toolbar(self):
        # Disable the navigation when Forever is selected.
        next_prev = self.period != FOREVER
        self.prevperiodbtn.set_sensitive(next_prev)
        self.thisperiodbtn.set_sensitive(next_prev)
        self.nextperiodbtn.set_sensitive(next_prev)

        # This is a HACK to translate the string properly
        # http://bugs.sugarlabs.org/ticket/3190
        if self.period == MONTH:
            text_previous_period = _('Previous Month')
            text_this_period = _('This Month')
            text_next_period = _('Next Month')
        elif self.period == WEEK:
            text_previous_period = _('Previous Week')
            text_this_period = _('This Week')
            text_next_period = _('Next Week')
        elif self.period == DAY:
            text_previous_period = _('Previous Day')
            text_this_period = _('This Day')
            text_next_period = _('Next Day')
        elif self.period == YEAR:
            text_previous_period = _('Previous Year')
            text_this_period = _('This Year')
            text_next_period = _('Next Year')

        if self.period != FOREVER:
            self.prevperiodbtn.set_tooltip(text_previous_period)
            self.thisperiodbtn.set_tooltip(text_this_period)
            self.nextperiodbtn.set_tooltip(text_next_period)

    # Update the label self.period to reflect the period.
    def get_this_period(self):
        today = datetime.date.today()

        if self.period == DAY:
            return today

        elif self.period == WEEK:
            while today.weekday() != 0:
                today -= datetime.timedelta(days=1)
            return today

        elif self.period == MONTH:
            return datetime.date(today.year, today.month, 1)

        elif self.period == YEAR:
            return datetime.date(today.year, 1, 1)

        elif self.period == FOREVER:
            return datetime.date(1900, 1, 1)

    def get_next_period(self, start):
        if self.period == DAY:
            return start + datetime.timedelta(days=1)

        elif self.period == WEEK:
            return start + datetime.timedelta(days=7)

        elif self.period == MONTH:
            if start.month == 12:
                return datetime.date(start.year + 1, 1, 1)
            else:
                return datetime.date(start.year, start.month + 1, 1)

        elif self.period == YEAR:
            return datetime.date(start.year + 1, 1, 1)

    def get_prev_period(self, start):
        if self.period == DAY:
            return start - datetime.timedelta(days=1)

        elif self.period == WEEK:
            return start - datetime.timedelta(days=7)

        elif self.period == MONTH:
            if start.month == 1:
                return datetime.date(start.year - 1, 12, 1)
            else:
                return datetime.date(start.year, start.month - 1, 1)

        elif self.period == YEAR:
            return datetime.date(start.year - 1, 1, 1)

    def thisperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_this_period()
            self.build_screen()

    def nextperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_next_period(self.period_start)
            self.build_screen()

    def prevperiod_cb(self, widget):
        if self.period != FOREVER:
            self.period_start = self.get_prev_period(self.period_start)
            self.build_screen()

    def __period_changed_cb(self, widget, value):
        self.period = int(value)
        self.update_toolbar()

        # Jump to 'this period'.
        self.period_start = self.get_this_period()
        self.build_screen()

    def build_visible_transactions(self):
        self.build_undo_buttons()

        if self.period == FOREVER:
            self.visible_transactions = self.data['transactions']

        else:
            period_start_ord = self.period_start.toordinal()
            period_end_ord = self.get_next_period(
                self.period_start).toordinal()

            self.visible_transactions = []
            for t in self.data['transactions']:
                d = t['date']
                if d >= period_start_ord and d < period_end_ord:
                    self.visible_transactions.append(t)

        self.visible_transactions.sort(key=lambda a: a['date'])

    def build_transaction_map(self):
        self.transaction_map = {}
        for t in self.data['transactions']:
            self.transaction_map[t['id']] = t

    def create_transaction(self,
                           name='',
                           type='debit',
                           amount=0,
                           category='',
                           date=datetime.date.today()):
        id = self.data['next_id']
        self.data['next_id'] += 1

        t = {
            'id': id,
            'name': name,
            'type': type,
            'amount': amount,
            'date': date.toordinal(),
            'category': category
        }
        self.data['transactions'].append(t)
        self.transaction_map[id] = t

        self.undo_id_map.append(id)
        self.undo_transaction_map.append('Erase')
        self.redo_transaction_map = []
        self.redo_id_map = []

        self.build_visible_transactions()

        return id

    def destroy_transaction(self, id):
        t = self.transaction_map[id]
        self.data['transactions'].remove(t)
        del self.transaction_map[id]

    def undo_redo_action(self, id, t, isin=False):
        # if we're updating the transaction
        if t == 'Erase':
            self.destroy_transaction(id)
        elif isin:
            for i in range(len(self.data['transactions'])):
                if id == self.data['transactions'][i]['id']:
                    self.data['transactions'][i] = t
                    break
        else:
            # Have to insert it back into the right position
            flag = 1
            for i in range(len(self.data['transactions'])):
                if id < self.data['transactions'][i]['id']:
                    self.data['transactions'].insert(i, t)
                    flag = 0
                    break
            if flag:
                self.data['transactions'].append(t)

    def undo_transaction(self):
        if len(self.undo_transaction_map) == 0:
            return False

        id = self.undo_id_map.pop()
        t = self.undo_transaction_map.pop()

        self.redo_id_map.append(id)
        isin = False
        if id in self.transaction_map.keys():
            self.redo_transaction_map.append(
                copy.deepcopy(self.transaction_map[id]))
            isin = True
        else:
            self.redo_transaction_map.append('Erase')

        copy_t = copy.deepcopy(t)
        self.undo_redo_action(id, copy_t, isin)

        if t != 'Erase':
            self.transaction_map[id] = copy_t
        return True

    def redo_transaction(self):
        if len(self.redo_transaction_map) == 0:
            return False

        id = self.redo_id_map.pop()
        t = self.redo_transaction_map.pop()

        self.undo_id_map.append(id)
        isin = False
        if id in self.transaction_map.keys():
            self.undo_transaction_map.append(
                copy.deepcopy(self.transaction_map[id]))
            isin = True
        else:
            self.undo_transaction_map.append('Erase')

        self.undo_redo_action(id, t, isin)

        if t != 'Erase':
            self.transaction_map[id] = copy.deepcopy(t)
        return True

    def build_undo_buttons(self):
        if len(self.undo_transaction_map) == 0:
            self.undoactionbtn.set_sensitive(False)
        else:
            self.undoactionbtn.set_sensitive(True)
        if len(self.redo_transaction_map) == 0:
            self.redoactionbtn.set_sensitive(False)
        else:
            self.redoactionbtn.set_sensitive(True)

    def build_names(self):
        self.transaction_names = {}
        self.category_names = {}
        for t in self.data['transactions']:
            self.transaction_names[t['name']] = 1
            self.category_names[t['category']] = 1

    def create_test_data(self):
        cur_date = datetime.date.today()
        cur_date = datetime.date(cur_date.year, cur_date.month, 1)
        self.create_transaction('Initial Balance',
                                type='credit',
                                amount=632,
                                category='Initial Balance',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Fix Car',
                                amount=75.84,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Adopt Cat',
                                amount=100,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('New Coat',
                                amount=25.53,
                                category='Clothing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Pay Rent',
                                amount=500,
                                category='Housing',
                                date=cur_date)

        cur_date += datetime.timedelta(days=1)
        self.create_transaction('Funky Cafe',
                                amount=5.20,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Groceries',
                                amount=50.92,
                                category='Food',
                                date=cur_date)
        self.create_transaction('Cat Food',
                                amount=5.40,
                                category='Pets',
                                date=cur_date)

        cur_date += datetime.timedelta(days=4)
        self.create_transaction('Paycheck',
                                type='credit',
                                amount=700,
                                category='Paycheck',
                                date=cur_date)
        self.create_transaction('Gas',
                                amount=21.20,
                                category='Transportation',
                                date=cur_date)

        cur_date += datetime.timedelta(days=2)
        self.create_transaction('Cat Toys',
                                amount=10.95,
                                category='Pets',
                                date=cur_date)
        self.create_transaction('Gift for Sister',
                                amount=23.20,
                                category='Gifts',
                                date=cur_date)

        self.build_transaction_map()
        self.build_names()

    def read_file(self, file_path):
        if self.metadata['mime_type'] != 'text/plain':
            return

        fd = open(file_path, 'r')
        try:
            text = fd.read()
            self.data = json.loads(text)
        finally:
            fd.close()

        if self.data['transactions']:
            self._set_internal_panel(self.register)
        self.show_header_controls()

        self.build_transaction_map()
        self.build_names()
        self.build_screen()

    def write_file(self, file_path):
        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'text/plain'

        fd = open(file_path, 'w')
        try:
            text = json.dumps(self.data)
            fd.write(text)
        finally:
            fd.close()

    def __save_image_cb(self, widget):
        image_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = self.chart.title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'image/png'

        # generate the image
        self.chart.generate_image(image_file.file, 800, 600)
        image_file.file.close()
        journal_entry.file_path = image_file.name

        # generate the preview
        preview_str = io.BytesIO()
        self.chart.generate_image(preview_str, activity.PREVIEW_SIZE[0],
                                  activity.PREVIEW_SIZE[1])
        journal_entry.metadata['preview'] = dbus.ByteArray(
            preview_str.getvalue())

        logging.debug('Create %s image file', image_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(_('Chart created'), _('Open in the Journal'),
                                 journal_entry.object_id)

    def _show_journal_alert(self, title, msg, object_id):
        open_alert = Alert()
        open_alert.props.title = title
        open_alert.props.msg = msg
        open_icon = Icon(icon_name='zoom-activity')
        open_alert.add_button(Gtk.ResponseType.APPLY, _('Show in Journal'),
                              open_icon)
        open_icon.show()
        ok_icon = Icon(icon_name='dialog-ok')
        open_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
        ok_icon.show()
        # Remove other alerts
        for alert in self._alerts:
            self.remove_alert(alert)

        self.add_alert(open_alert)
        open_alert.connect('response', self.__open_response_cb, object_id)
        open_alert.show()

    def __open_response_cb(self, alert, response_id, object_id):
        if response_id is Gtk.ResponseType.APPLY:
            activity.show_object_in_journal(object_id)
        self.remove_alert(alert)

    def __export_data_to_chart_cb(self, widget, type_movement, period):
        """
        type_movement = 'debit' or 'credit'
        period
            DAY = 0
            MONTH = 2
        """
        logging.debug('export data %s %s', type_movement, period)

        chart_params = {}
        axis = {
            'tickFont': 'Sans',
            'labelFont': 'Sans',
            'labelFontSize': 14,
            'labelColor': '#666666',
            'lineColor': '#b3b3b3',
            'tickColor': '#000000',
            'tickFontSize': 12
        }
        chart_params['font_options'] = {
            'titleFont': 'Sans',
            'titleFontSize': 12,
            'titleColor': '#000000',
            'axis': axis
        }

        if type_movement == 'credit':
            what_filter = 'Credits'
        elif type_movement == 'debit':
            what_filter = 'Debits'
        else:
            logging.debug('ERROR type_movement should be credit or debit')

        if period == DAY:
            when = 'day'
        elif period == MONTH:
            when = 'month'
        else:
            logging.debug('ERROR period should be DAY or MONTH')

        title = _('%(what_filter)s by %(when)s') % {
            'what_filter': what_filter,
            'when': when
        }
        chart_params['title'] = title
        chart_params['x_label'] = ''
        chart_params['y_label'] = ''
        chart_params['current_chart.type'] = 1
        xo_color = profile.get_color()
        chart_params['chart_line_color'] = xo_color.get_stroke_color()
        chart_params['chart_color'] = xo_color.get_fill_color()
        """
        'chart_data': [
            ['hello', 200.0],
            ['mrch', 100.0]],
        """
        transactions = self.data['transactions']

        groups = {}
        for transaction in transactions:
            if transaction['type'] == type_movement:
                date = transaction['date']
                if period == DAY:
                    group = date
                elif period == MONTH:
                    d = datetime.date.fromordinal(date)
                    group = datetime.date(d.year, d.month, 1).toordinal()
                if group in list(groups.keys()):
                    groups[group] = groups[group] + transaction['amount']
                else:
                    groups[group] = transaction['amount']

        data = []
        for group in sorted(groups.keys()):
            if period == DAY:
                label = datetime.date.fromordinal(group).isoformat()
            elif period == MONTH:
                d = datetime.date.fromordinal(group)
                label = '%s-%s' % (d.year, d.month)

            data.append([label, groups[group]])

        chart_params['chart_data'] = data

        logging.debug('chart_data %s', chart_params)

        # save to the journal
        data_file = tempfile.NamedTemporaryFile(mode='w', suffix='.json')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'application/x-chart-activity'
        journal_entry.metadata['activity'] = 'org.sugarlabs.SimpleGraph'

        json.dump(chart_params, data_file.file)
        data_file.file.close()
        journal_entry.file_path = data_file.name

        logging.debug('Create %s data file', data_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(_('Exported data'), _('Open in the Journal'),
                                 journal_entry.object_id)
예제 #58
0
    def build_toolbar(self):

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, -1)
        activity_button.show()

        barra = toolbar_box.toolbar

        separador1 = Gtk.SeparatorToolItem()
        separador1.props.draw = True
        barra.insert(separador1, 1)

        item1 = Gtk.ToolItem()
        self.label_radio1 = Gtk.Label()
        self.label_radio1.set_text(_('Circles between') + ' ')
        item1.add(self.label_radio1)
        barra.insert(item1, 2)

        grayed = Gdk.Color(20000.0, 20000.0, 20000.0)

        item2 = Gtk.ToolItem()
        self.cradio1 = Gtk.SpinButton()
        self.cradio1.modify_bg(Gtk.StateType.NORMAL, grayed)
        self.cradio1.set_range(1, 20)
        self.cradio1.set_increments(1, 2)
        self.cradio1.props.value = self.radio_uno
        self.cradio1_handler = self.cradio1.connect('notify::value',
                                                    self.cradio1_valor)
        item2.add(self.cradio1)
        barra.insert(item2, 3)

        item3 = Gtk.ToolItem()
        self.label_and = Gtk.Label()
        self.label_and.set_text(' ' + _('and') + ' ')
        item3.add(self.label_and)
        barra.insert(item3, 4)

        item4 = Gtk.ToolItem()
        self.cradio2 = Gtk.SpinButton()
        self.cradio2.modify_bg(Gtk.StateType.NORMAL, grayed)
        self.cradio2.set_range(1, 20)
        self.cradio2.set_increments(1, 2)
        self.cradio2.props.value = self.radio_dos
        self.cradio2_handler = self.cradio2.connect('notify::value',
                                                    self.cradio2_valor)
        item4.add(self.cradio2)
        barra.insert(item4, 5)

        separator1 = Gtk.SeparatorToolItem()
        separator1.props.draw = True
        separator1.set_expand(False)
        barra.insert(separator1, 6)

        save_button = ToolButton('filesave')
        save_button.set_tooltip(_('Save Image'))
        save_button.connect('clicked', self._savebutton_cb)
        barra.insert(save_button, 7)
        save_button.show()

        separator2 = Gtk.SeparatorToolItem()
        separator2.props.draw = False
        separator2.set_expand(True)
        barra.insert(separator2, 8)

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        barra.insert(stop_button, 9)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)

        toolbar_box.show_all()
예제 #59
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        # abiword uses the current directory for all its file dialogs
        os.chdir(os.path.expanduser('~'))

        # create our main abiword canvas
        self.abiword_canvas = DocumentView()
        self._new_instance = True
        toolbar_box = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(self.activity_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.show()
        self.activity_button.props.page.insert(separator, 2)
        ExportButtonFactory(self, self.abiword_canvas)
        self.activity_button.show()

        edit_toolbar = ToolbarButton()
        edit_toolbar.props.page = EditToolbar(self, toolbar_box)
        edit_toolbar.props.icon_name = 'toolbar-edit'
        edit_toolbar.props.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar, -1)

        view_toolbar = ToolbarButton()
        view_toolbar.props.page = ViewToolbar(self.abiword_canvas)
        view_toolbar.props.icon_name = 'toolbar-view'
        view_toolbar.props.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar, -1)

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.speech_toolbar_button = ToolbarButton(icon_name='speak')
            toolbar_box.toolbar.insert(self.speech_toolbar_button, -1)
            self._init_speech()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        text_toolbar = ToolbarButton()
        text_toolbar.props.page = TextToolbar(self.abiword_canvas)
        text_toolbar.props.icon_name = 'format-text'
        text_toolbar.props.label = _('Text')
        toolbar_box.toolbar.insert(text_toolbar, -1)

        para_toolbar = ToolbarButton()
        para_toolbar.props.page = ParagraphToolbar(self.abiword_canvas)
        para_toolbar.props.icon_name = 'paragraph-bar'
        para_toolbar.props.label = _('Paragraph')
        toolbar_box.toolbar.insert(para_toolbar, -1)

        insert_toolbar = ToolbarButton()
        insert_toolbar.props.page = InsertToolbar(self.abiword_canvas)
        insert_toolbar.props.icon_name = 'insert-table'
        insert_toolbar.props.label = _('Table')
        toolbar_box.toolbar.insert(insert_toolbar, -1)

        image = ToolButton('insert-picture')
        image.set_tooltip(_('Insert Image'))
        self._image_id = image.connect('clicked', self._image_cb)
        toolbar_box.toolbar.insert(image, -1)

        palette = image.get_palette()
        content_box = Gtk.VBox()
        palette.set_content(content_box)
        image_floating_checkbutton = Gtk.CheckButton(_('Floating'))
        image_floating_checkbutton.connect(
            'toggled', self._image_floating_checkbutton_toggled_cb)
        content_box.pack_start(image_floating_checkbutton, True, True, 0)
        content_box.show_all()
        self.floating_image = False

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        separator.show()
        toolbar_box.toolbar.insert(separator, -1)

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)

        # add a overlay to be able to show a icon while joining a shared doc
        overlay = Gtk.Overlay()
        overlay.add(self.abiword_canvas)
        overlay.show()

        self._connecting_box = ConnectingBox()
        overlay.add_overlay(self._connecting_box)

        self.set_canvas(overlay)

        # we want a nice border so we can select paragraphs easily
        self.abiword_canvas.set_show_margin(True)

        # Read default font face and size
        client = GConf.Client.get_default()
        self._default_font_face = client.get_string(
            '/desktop/sugar/activities/write/font_face')
        if not self._default_font_face:
            self._default_font_face = 'Sans'
        self._default_font_size = client.get_int(
            '/desktop/sugar/activities/write/font_size')
        if self._default_font_size == 0:
            self._default_font_size = 12

        # activity sharing
        self.participants = {}
        self.joined = False

        self.connect('shared', self._shared_cb)

        if self.shared_activity:
            # we are joining the activity
            logger.error('We are joining an activity')
            # display a icon while joining
            self._connecting_box.show()
            # disable the abi widget
            self.abiword_canvas.set_sensitive(False)
            self._new_instance = False
            self.connect('joined', self._joined_cb)
            self.shared_activity.connect('buddy-joined',
                                         self._buddy_joined_cb)
            self.shared_activity.connect('buddy-left', self._buddy_left_cb)
            if self.get_shared():
                self._joined_cb(self)
        else:
            # we are creating the activity
            logger.error("We are creating an activity")

        self.abiword_canvas.zoom_width()
        self.abiword_canvas.show()
        self.connect_after('map-event', self.__map_activity_event_cb)

        self.abiword_canvas.connect('size-allocate', self.size_allocate_cb)
예제 #60
0
class CalcLayout:

    FONT_SMALL_POINTS = 10
    FONT_SMALL = "sans %d" % FONT_SMALL_POINTS
    FONT_SMALL_NARROW = "sans italic %d" % FONT_SMALL_POINTS
    FONT_BIG_POINTS = 14
    FONT_BIG = "sans bold %d" % FONT_BIG_POINTS
    FONT_BIG_NARROW = "sans italic 14"
    FONT_BIGGER_POINTS = 18
    FONT_BIGGER = "sans bold %d" % FONT_BIGGER_POINTS

    def __init__(self, parent):
        self._parent = parent

        self._own_equations = []
        self._other_equations = []
        self._showing_history = True
        self._showing_all_history = True
        self._var_textviews = {}
        self.graph_selected = None

        self.create_dialog()

    def create_color(self, rf, gf, bf):
        return Gdk.Color(int(rf * 0xFFFF), int(gf * 0xFFFF), int(bf * 0xFFFF))

    def create_button_data(self):
        """Create a list with button information. We need to do that here
        because we want to include the lambda functions."""

        mul_sym = self._parent.ml.mul_sym
        div_sym = self._parent.ml.div_sym
        equ_sym = self._parent.ml.equ_sym

        self.button_data = [
            # [x, y, width, label, bgcol, cb]
            [
                0, 0, 2, 1, u'\u2190', self.col_gray3,
                lambda w: self._parent.move_left()
            ],
            [
                2, 0, 2, 1, u'\u2192', self.col_gray3,
                lambda w: self._parent.move_right()
            ],
            [
                4, 0, 2, 1, u'\u232B', self.col_gray3,
                lambda w: self._parent.remove_character(-1)
            ],
            [
                0, 1, 1, 2, '7', self.col_gray2,
                lambda w: self._parent.add_text('7')
            ],
            [
                1, 1, 1, 2, '8', self.col_gray2,
                lambda w: self._parent.add_text('8')
            ],
            [
                2, 1, 1, 2, '9', self.col_gray2,
                lambda w: self._parent.add_text('9')
            ],
            [
                0, 3, 1, 2, '4', self.col_gray2,
                lambda w: self._parent.add_text('4')
            ],
            [
                1, 3, 1, 2, '5', self.col_gray2,
                lambda w: self._parent.add_text('5')
            ],
            [
                2, 3, 1, 2, '6', self.col_gray2,
                lambda w: self._parent.add_text('6')
            ],
            [
                0, 5, 1, 2, '1', self.col_gray2,
                lambda w: self._parent.add_text('1')
            ],
            [
                1, 5, 1, 2, '2', self.col_gray2,
                lambda w: self._parent.add_text('2')
            ],
            [
                2, 5, 1, 2, '3', self.col_gray2,
                lambda w: self._parent.add_text('3')
            ],
            [
                0, 7, 2, 2, '0', self.col_gray2,
                lambda w: self._parent.add_text('0')
            ],
            [
                2, 7, 1, 2, '.', self.col_gray2,
                lambda w: self._parent.add_text('.')
            ],
            [
                3, 1, 3, 2,
                _('Clear'), self.col_gray1, lambda w: self._parent.clear()
            ],
            [
                3, 3, 1, 2, '+', self.col_gray3,
                lambda w: self._parent.add_text('+')
            ],
            [
                4, 3, 1, 2, '-', self.col_gray3,
                lambda w: self._parent.add_text('-')
            ],
            [
                5, 3, 1, 2, '(', self.col_gray3,
                lambda w: self._parent.add_text('(')
            ],
            [
                3, 5, 1, 2, mul_sym, self.col_gray3,
                lambda w: self._parent.add_text(mul_sym)
            ],
            [
                4, 5, 1, 2, div_sym, self.col_gray3,
                lambda w: self._parent.add_text(div_sym)
            ],
            [
                5, 5, 1, 2, ')', self.col_gray3,
                lambda w: self._parent.add_text(')')
            ],
            [
                3, 7, 3, 2, equ_sym, self.col_gray1,
                lambda w: self._parent.process()
            ],
        ]

    def create_dialog(self):
        """Setup most of the dialog."""

        # Toolbar
        self._toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self._parent)
        self._toolbar_box.toolbar.insert(activity_button, 0)

        def append(icon_name, label, page, position):
            toolbar_button = ToolbarButton()
            toolbar_button.props.page = page
            toolbar_button.props.icon_name = icon_name
            toolbar_button.props.label = label
            self._toolbar_box.toolbar.insert(toolbar_button, position)

        append('toolbar-edit', _('Edit'), EditToolbar(self._parent), -1)
        append('toolbar-algebra', _('Algebra'), AlgebraToolbar(self._parent),
               -1)
        append('toolbar-trigonometry', _('Trigonometry'),
               TrigonometryToolbar(self._parent), -1)
        append('toolbar-boolean', _('Boolean'), BooleanToolbar(self._parent),
               -1)
        self._misc_toolbar = MiscToolbar(
            self._parent, target_toolbar=self._toolbar_box.toolbar)
        append('toolbar-constants', _('Miscellaneous'), self._misc_toolbar, 5)
        self._stop_separator = Gtk.SeparatorToolItem()
        self._stop_separator.props.draw = False
        self._stop_separator.set_expand(True)
        self._stop_separator.show()
        self._toolbar_box.toolbar.insert(self._stop_separator, -1)
        self._stop = StopButton(self._parent)
        self._toolbar_box.toolbar.insert(self._stop, -1)
        self._toolbar_box.show_all()
        self._parent.set_toolbar_box(self._toolbar_box)

        # Some layout constants
        self.input_font = Pango.FontDescription('sans bold 12')
        self.button_font = Pango.FontDescription('sans bold 16')
        self.col_white = self.create_color(1.00, 1.00, 1.00)
        self.col_gray1 = self.create_color(0.76, 0.76, 0.76)
        self.col_gray2 = self.create_color(0.50, 0.50, 0.50)
        self.col_gray3 = self.create_color(0.25, 0.25, 0.25)
        self.col_black = self.create_color(0.00, 0.00, 0.00)
        self.col_red = self.create_color(1.00, 0.00, 0.00)

        # Big - Table, 16 rows, 10 columns, homogeneously divided
        self.grid = Gtk.Grid()
        self.grid.set_column_homogeneous(True)
        self.grid.set_row_spacing(0)
        self.grid.set_column_spacing(4)

        # Left part: container and input
        vc1 = Gtk.VBox(False, 0)
        hc1 = Gtk.HBox(False, 10)
        eb = Gtk.EventBox()
        eb.add(hc1)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = Gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        label1 = Gtk.Label(label=_('Label:'))
        label1.modify_fg(Gtk.StateType.NORMAL, self.col_white)
        label1.set_alignment(1, 0.5)
        hc1.pack_start(label1, expand=False, fill=False, padding=10)
        self.label_entry = Gtk.Entry()
        self.label_entry.modify_bg(Gtk.StateType.INSENSITIVE, self.col_black)
        hc1.pack_start(self.label_entry, expand=True, fill=True, padding=0)
        vc1.pack_start(eb2, False, True, 0)

        self.text_entry = Gtk.Entry()
        try:
            self.text_entry.props.im_module = 'gtk-im-context-simple'
        except AttributeError:
            pass
        self.text_entry.set_size_request(-1, 75)
        self.text_entry.connect('key_press_event', self._parent.ignore_key_cb)
        self.text_entry.modify_font(self.input_font)
        self.text_entry.modify_bg(Gtk.StateType.INSENSITIVE, self.col_black)
        eb = Gtk.EventBox()
        eb.add(self.text_entry)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        eb.set_border_width(12)
        eb2 = Gtk.EventBox()
        eb2.add(eb)
        eb2.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        vc1.pack_start(eb2, expand=True, fill=True, padding=0)
        self.grid.attach(vc1, 0, 0, 7, 6)

        # Left part: buttons
        self.pad = Gtk.Grid()
        self.pad.set_column_homogeneous(True)
        self.pad.set_row_spacing(6)
        self.pad.set_column_spacing(6)
        self.create_button_data()
        self.buttons = {}
        for x, y, w, h, cap, bgcol, cb in self.button_data:
            button = self.create_button(_(cap), cb, self.col_white, bgcol, w,
                                        h)
            self.buttons[cap] = button
            self.pad.attach(button, x, y, w, h)

        eb = Gtk.EventBox()
        eb.add(self.pad)
        eb.modify_bg(Gtk.StateType.NORMAL, self.col_black)
        self.grid.attach(eb, 0, 6, 7, 20)

        # Right part: container and equation button
        hc2 = Gtk.HBox()
        combo = ComboBox()
        combo.append_item(0, _('All equations'))
        combo.append_item(1, _('My equations'))
        combo.append_item(2, _('Show variables'))
        combo.set_active(0)
        combo.connect('changed', self._history_filter_cb)
        hc2.pack_start(combo, True, True, 0)
        hc2.set_border_width(6)
        self.grid.attach(hc2, 7, 0, 4, 2)

        # Right part: last equation
        self.last_eq = Gtk.TextView()
        self.last_eq.set_editable(False)
        self.last_eq.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
        self.last_eq.connect('realize', self._textview_realize_cb)
        self.last_eq.modify_base(
            Gtk.StateType.NORMAL,
            Gdk.color_parse(sugar3.profile.get_color().get_fill_color()))
        self.last_eq.modify_bg(
            Gtk.StateType.NORMAL,
            Gdk.color_parse(sugar3.profile.get_color().get_stroke_color()))
        self.last_eq.set_border_window_size(Gtk.TextWindowType.LEFT, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.RIGHT, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.TOP, 4)
        self.last_eq.set_border_window_size(Gtk.TextWindowType.BOTTOM, 4)

        # TODO Fix for old Sugar 0.82 builds, red_float not available
        xo_color = sugar3.profile.get_color()
        bright = (Gdk.color_parse(xo_color.get_fill_color()).red_float +
                  Gdk.color_parse(xo_color.get_fill_color()).green_float +
                  Gdk.color_parse(xo_color.get_fill_color()).blue_float) / 3.0
        if bright < 0.5:
            self.last_eq.modify_text(Gtk.StateType.NORMAL, self.col_white)
        else:
            self.last_eq.modify_text(Gtk.StateType.NORMAL, self.col_black)

        self.grid.attach(self.last_eq, 7, 2, 4, 5)

        # Right part: history
        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.NEVER,
                                   Gtk.PolicyType.AUTOMATIC)

        self.history_vbox = Gtk.VBox()
        self.history_vbox.set_homogeneous(False)
        self.history_vbox.set_border_width(0)
        self.history_vbox.set_spacing(4)

        self.variable_vbox = Gtk.VBox()
        self.variable_vbox.set_homogeneous(False)
        self.variable_vbox.set_border_width(0)
        self.variable_vbox.set_spacing(4)

        vbox = Gtk.VBox()
        vbox.pack_start(self.history_vbox, True, True, 0)
        vbox.pack_start(self.variable_vbox, True, True, 0)
        scrolled_window.add_with_viewport(vbox)
        self.grid.attach(scrolled_window, 7, 7, 4, 19)

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

    def _configure_cb(self, event):
        # Maybe redo layout
        self._toolbar_box.toolbar.remove(self._stop)
        self._toolbar_box.toolbar.remove(self._stop_separator)
        self._misc_toolbar.update_layout()
        self._toolbar_box.toolbar.insert(self._stop_separator, -1)
        self._toolbar_box.toolbar.insert(self._stop, -1)

    def show_it(self):
        """Show the dialog."""
        self._parent.set_canvas(self.grid)
        self._parent.show_all()
        self.show_history()
        self.text_entry.grab_focus()

    def showing_history(self):
        """Return whether we're currently showing the history (or otherwise
        the list of variables)."""
        return self._showing_history

    def show_history(self):
        """Show the history VBox."""
        self._showing_history = True
        self.variable_vbox.hide()
        self.history_vbox.show()

    def toggle_select_graph(self, widget, host=None):
        # if we have a graph already selected, we must deselect it first
        if self.graph_selected and self.graph_selected != widget:
            self.toggle_select_graph(self.graph_selected)

        if not self.graph_selected:
            widget.set_visible_window(True)
            widget.set_above_child(True)
            self.graph_selected = widget
            white = Gdk.color_parse('white')
            widget.modify_bg(Gtk.StateType.NORMAL, white)
        else:
            widget.set_visible_window(False)
            self.graph_selected = False

    def add_equation(self, textview, own, prepend=False):
        """Add a Gtk.TextView of an equation to the history_vbox."""

        GraphEventBox = None
        if isinstance(textview, Gtk.Image):
            # Add the image inside the eventBox
            GraphEventBox = Gtk.EventBox()
            GraphEventBox.add(textview)
            GraphEventBox.set_visible_window(False)
            GraphEventBox.connect('button_press_event',
                                  self.toggle_select_graph)
            GraphEventBox.show()

        if prepend:
            if GraphEventBox:
                self.history_vbox.pack_start(GraphEventBox, False, True, 0)
                self.history_vbox.reorder_child(GraphEventBox, 0)
            else:
                self.history_vbox.pack_start(textview, False, True, 0)
                self.history_vbox.reorder_child(textview, 0)
        else:
            if GraphEventBox:
                self.history_vbox.pack_end(GraphEventBox, False, True)
            else:
                self.history_vbox.pack_end(textview, False, True)

        if own:
            if GraphEventBox:
                self._own_equations.append(GraphEventBox)
                GraphEventBox.get_child().show()
            else:
                self._own_equations.append(textview)
                textview.show()
        else:
            if self._showing_all_history:
                if GraphEventBox:
                    self._other_equations.append(GraphEventBox)
                    GraphEventBox.get_child().show()
                else:
                    self._other_equations.append(textview)
                    textview.show()

    def show_all_history(self):
        """Show both owned and other equations."""
        self._showing_all_history = True
        for key in self._other_equations:
            if isinstance(key, Gtk.EventBox):
                key.get_child().show()
            else:
                key.show()

    def show_own_history(self):
        """Show only owned equations."""
        self._showing_all_history = False
        for key in self._other_equations:
            if isinstance(key, Gtk.EventBox):
                key.get_child().hide()
            else:
                key.hide()

    def add_variable(self, varname, textview):
        """Add a Gtk.TextView of a variable to the variable_vbox."""

        if varname in self._var_textviews:
            self.variable_vbox.remove(self._var_textviews[varname])
            del self._var_textviews[varname]

        self._var_textviews[varname] = textview
        self.variable_vbox.pack_start(textview, False, True, 0)

        # Reorder textviews for a sorted list
        names = self._var_textviews.keys()
        names.sort()
        for i in range(len(names)):
            self.variable_vbox.reorder_child(self._var_textviews[names[i]], i)

        textview.show()

    def show_variables(self):
        """Show the variables VBox."""
        self._showing_history = False
        self.history_vbox.hide()
        self.variable_vbox.show()

    def create_button(self, cap, cb, fgcol, bgcol, width, height):
        """Create a button that is set up properly."""
        button = Gtk.Button(_(cap))
        self.modify_button_appearance(button, fgcol, bgcol, width, height)
        button.connect("clicked", cb)
        button.connect("key_press_event", self._parent.ignore_key_cb)
        return button

    def modify_button_appearance(self, button, fgcol, bgcol, width, height):
        """Modify button style."""
        width = 50 * width
        height = 50 * height
        button.get_child().set_size_request(width, height)
        button.get_child().modify_font(self.button_font)
        button.get_child().modify_fg(Gtk.StateType.NORMAL, fgcol)
        button.modify_bg(Gtk.StateType.NORMAL, bgcol)
        button.modify_bg(Gtk.StateType.PRELIGHT, bgcol)

    def _history_filter_cb(self, combo):
        selection = combo.get_active()
        if selection == 0:
            self.show_history()
            self.show_all_history()
        elif selection == 1:
            self.show_history()
            self.show_own_history()
        elif selection == 2:
            self.show_variables()

    def _textview_realize_cb(self, widget):
        '''Change textview properties once window is created.'''
        win = widget.get_window(Gtk.TextWindowType.TEXT)
        win.set_cursor(Gdk.Cursor.new(Gdk.CursorType.HAND1))
        return False