def __configure_cb(self, event): """ Screen size has changed """ self.write_file(os.path.join(activity.get_activity_root(), "data", "data")) w = Gdk.Screen.width() h = Gdk.Screen.height() - 2 * GRID_CELL_SIZE pygame.display.set_mode((w, h), pygame.RESIZABLE) self.read_file(os.path.join(activity.get_activity_root(), "data", "data")) self.game.run(True)
def __configure_cb(self, event): ''' Screen size has changed ''' self.write_file(os.path.join( activity.get_activity_root(), 'data', 'data')) pygame.display.set_mode((Gdk.Screen.width(), Gdk.Screen.height() - 2 * GRID_CELL_SIZE), pygame.RESIZABLE) self.read_file(os.path.join( activity.get_activity_root(), 'data', 'data')) self.game.run(True)
def favicon(self, webview, icono): d = urllib.urlopen(icono) if os.path.exists(activity.get_activity_root() + "/data/Favicons/" + icono.split("/")[-1]): os.remove("Favicons/" + icono.split("/")[-1]) fav = open(activity.get_activity_root() + "/data/Favicons/" + icono.split("/")[-1], "a") for x in d.readlines(): fav.write(x) fav.close() self.favicon_i.set_from_file(activity.get_activity_root() + "/data/Favicons/" + icono.split("/")[-1])
def __init__(self, download, browser): self._download = download self._activity = browser.get_toplevel() self._source = download.get_uri() self._download.connect('notify::status', self.__state_change_cb) self._download.connect('error', self.__error_cb) self.datastore_deleted_handler = None self.dl_jobject = None self._object_id = None self._stop_alert = None self._progress = 0 self._last_update_progress = 0 self._progress_sid = None # figure out download URI self.temp_path = os.path.join(activity.get_activity_root(), 'instance') if not os.path.exists(self.temp_path): os.makedirs(self.temp_path) fd, self._dest_path = tempfile.mkstemp( dir=self.temp_path, suffix=download.get_suggested_filename(), prefix='tmp') os.close(fd) logging.debug('Download destination path: %s' % self._dest_path) # We have to start the download to get 'total-size' # property. It not, 0 is returned self._download.set_destination_uri('file://' + self._dest_path) self._download.start()
def run(self): jobject = None _file = None try: result = ObjectChooser.run(self) if result == Gtk.ResponseType.ACCEPT: jobject = self.get_selected_object() logging.debug('FilePicker.show: %r', jobject) if jobject and jobject.file_path: tmp_dir = tempfile.mkdtemp(prefix='', \ dir=os.path.join(get_activity_root(), 'tmp')) _file = os.path.join(tmp_dir, _basename_strip(jobject)) os.rename(jobject.file_path, _file) global _temp_dirs_to_clean _temp_dirs_to_clean.append(tmp_dir) logging.debug('FilePicker.show: file=%r', _file) finally: if jobject is not None: jobject.destroy() return _file
def __init__(self, handle): ''' Initialize the toolbar ''' try: super(OneSupportActivity, self).__init__(handle) except dbus.exceptions.DBusException as e: _logger.error(str(e)) self.connect('realize', self.__realize_cb) if hasattr(self, 'metadata') and 'font_size' in self.metadata: self.font_size = int(self.metadata['font_size']) else: self.font_size = 8 self.zoom_level = self.font_size / float(len(FONT_SIZES)) _logger.debug('zoom level is %f' % self.zoom_level) # _check_gconf_settings() # For debugging purposes self._setup_toolbars() self.modify_bg(Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color()) self.bundle_path = activity.get_bundle_path() self.tmp_path = os.path.join(activity.get_activity_root(), 'tmp') self._copy_entry = None self._paste_entry = None self._about_panel_visible = False self._webkit = None self._clipboard_text = '' self._fixed = None self._notify_transfer_status = False get_power_manager().inhibit_suspend() self._launch_task_master()
def _download_from_http(self, remote_uri): """Download the PDF from a remote location to a temporal file.""" # Display a message self._message_box = PDFProgressMessageBox( message=_("Downloading document..."), button_callback=self.close_tab) self.pack_start(self._message_box, True, True, 0) self._message_box.show() # Figure out download URI temp_path = os.path.join(activity.get_activity_root(), 'instance') if not os.path.exists(temp_path): os.makedirs(temp_path) fd, dest_path = tempfile.mkstemp(dir=temp_path) self._pdf_uri = 'file://' + dest_path network_request = WebKit.NetworkRequest.new(remote_uri) self._download = WebKit.Download.new(network_request) self._download.set_destination_uri('file://' + dest_path) # FIXME: workaround for SL #4385 # self._download.connect('notify::progress', # self.__download_progress_cb) self._download.connect('notify::current-size', self.__current_size_changed_cb) self._download.connect('notify::status', self.__download_status_cb) self._download.connect('error', self.__download_error_cb) self._download.start()
def __init__(self, handle): super(PhysicsActivity, self).__init__(handle) self.metadata['mime_type'] = 'application/x-physics-activity' self.add_events(Gdk.EventMask.ALL_EVENTS_MASK | Gdk.EventMask.VISIBILITY_NOTIFY_MASK) self.connect('visibility-notify-event', self._focus_event) self.connect('window-state-event', self._window_event) self.game_canvas = sugargame.canvas.PygameCanvas(self) self.game = physics.main(self) self.preview = None self._sample_window = None self._fixed = Gtk.Fixed() self._fixed.put(self.game_canvas, 0, 0) w = Gdk.Screen.width() h = Gdk.Screen.height() - 2 * GRID_CELL_SIZE self.game_canvas.set_size_request(w, h) self._constructors = {} self.build_toolbar() self.set_canvas(self._fixed) Gdk.Screen.get_default().connect('size-changed', self.__configure_cb) logging.debug(os.path.join( activity.get_activity_root(), 'data', 'data')) self.game_canvas.run_pygame(self.game.run) GObject.idle_add(self._setup_sharing) self.show_all()
def __copy_activate_cb(self, menu_item): file_name = os.path.basename(urlparse.urlparse(self._url).path) if '.' in file_name: base_name, extension = file_name.split('.') extension = '.' + extension else: base_name = file_name extension = '' temp_path = os.path.join(activity.get_activity_root(), 'instance') fd, temp_file = tempfile.mkstemp(dir=temp_path, prefix=base_name, suffix=extension) os.close(fd) os.chmod(temp_file, 0664) cls = components.classes['@mozilla.org/network/io-service;1'] io_service = cls.getService(interfaces.nsIIOService) uri = io_service.newURI(self._url, None, None) cls = components.classes['@mozilla.org/file/local;1'] target_file = cls.createInstance(interfaces.nsILocalFile) target_file.initWithPath(temp_file) cls = components.classes[ \ '@mozilla.org/embedding/browser/nsWebBrowserPersist;1'] persist = cls.createInstance(interfaces.nsIWebBrowserPersist) persist.persistFlags = 1 # PERSIST_FLAGS_FROM_CACHE listener = xpcom.server.WrapObject(_ImageProgressListener(temp_file), interfaces.nsIWebProgressListener) persist.progressListener = listener persist.saveURI(uri, None, None, None, None, target_file)
def writer(view, result): temp_path = os.path.join(activity.get_activity_root(), 'instance') file_path = os.path.join(temp_path, '%i' % time.time()) file_handle = file(file_path, 'w') file_handle.write(view.get_data_finish(result)) file_handle.close() async_cb(file_path)
def get_path(activity, subpath): """ Find a Rainbow-approved place for temporary files. """ try: return(os.path.join(activity.get_activity_root(), subpath)) except: # Early versions of Sugar didn't support get_activity_root() return(os.path.join( os.environ['HOME'], ".sugar/default", SERVICE, subpath))
def set_activity(self, activity): self.activity = activity if os.path.exists(os.path.join(activity.get_activity_root(), 'instance', 'pitch.txt')): f = open(os.path.join(activity.get_activity_root(), 'instance', 'pitch.txt'), 'r') line = f.readline() pitch = int(line.strip()) self.pitchadj.set_value(pitch) speech.pitch = pitch f.close() if os.path.exists(os.path.join(activity.get_activity_root(), 'instance', 'rate.txt')): f = open(os.path.join(activity.get_activity_root(), 'instance', 'rate.txt'), 'r') line = f.readline() rate = int(line.strip()) self.rateadj.set_value(rate) speech.rate = rate f.close() self.pitchadj.connect("value_changed", self.pitch_adjusted_cb) self.rateadj.connect("value_changed", self.rate_adjusted_cb)
def get_document_path(self, async_cb, async_err_cb): html_uri = self._web_view.get_uri() rst_path = html_uri.replace('file:///', '/') rst_path = rst_path.replace('html/', 'source/') rst_path = rst_path.replace('.html', '.rst') tmp_path = os.path.join(activity.get_activity_root(), 'instance', 'source.rst') os.symlink(rst_path, tmp_path) async_cb(tmp_path)
def get_qr(self): photo_filename = os.path.join(activity.get_activity_root(), "instance", "qr.png") if os.path.exists(photo_filename): os.remove(photo_filename) self.camerabin.set_property("location", photo_filename) self.camerabin.emit("start-capture") return photo_filename
def write(self, file_path): instance_path = os.path.join(activity.get_activity_root(), 'instance') book_data = {} book_data['version'] = '1' book_data['cover_path'] = self.cover_path pages = [] for page in self._pages: page_data = {} page_data['text'] = page.text page_data['background_path'] = page.background_path page_data['images'] = [] for image in page.images: image_data = {} image_data['x'] = image.x image_data['y'] = image.y image_data['path'] = image.path image_data['width'] = image.width image_data['height'] = image.height image_data['h_mirrored'] = image.h_mirrored image_data['v_mirrored'] = image.v_mirrored image_data['angle'] = image.angle page_data['images'].append(image_data) pages.append(page_data) book_data['pages'] = pages logging.debug('book_data %s', book_data) data_file_name = 'data.json' f = open(os.path.join(instance_path, data_file_name), 'w') try: json.dump(book_data, f) finally: f.close() logging.debug('file_path %s', file_path) z = zipfile.ZipFile(file_path, 'w') z.write(os.path.join(instance_path, data_file_name), data_file_name) # zip the cover image if self.cover_path and os.path.exists(self.cover_path): z.write(self.cover_path, os.path.basename(self.cover_path)) # zip the pages for page in self._pages: if page.background_path is not None and \ page.background_path != '': z.write(page.background_path, os.path.basename(page.background_path)) for image in page.images: if image.path is not None and image.path != '': z.write(image.path, os.path.basename(image.path)) z.close()
def get_source(self, async_cb, async_err_cb): data_source = self.get_main_frame().get_data_source() data = data_source.get_data() if data_source.is_loading() or data is None: async_err_cb() temp_path = os.path.join(activity.get_activity_root(), 'instance') file_path = os.path.join(temp_path, '%i' % time.time()) file_handle = file(file_path, 'w') file_handle.write(data.str) file_handle.close() async_cb(file_path)
def get_thumbnail(self): if self.thumbnail is None: instance_path = os.path.join(activity.get_activity_root(), 'instance') if (not self.image_name.startswith(instance_path)): self.thumbnail = GdkPixbuf.Pixbuf.new_from_file_at_size( os.path.join(instance_path, self.image_name), THUMB_SIZE[0], THUMB_SIZE[1]) else: self.thumbnail = GdkPixbuf.Pixbuf.new_from_file_at_size( self.image_name, THUMB_SIZE[0], THUMB_SIZE[1]) return self.thumbnail
def _on_send_button_clicked_cb(self, button): window = self._activity.get_window() old_cursor = window.get_cursor() window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) Gdk.flush() identifier = str(int(time.time())) filename = '%s.zip' % identifier filepath = os.path.join(activity.get_activity_root(), filename) success = True # FIXME: subprocess or thread try: self._collector.write_logs(archive=filepath, logbytes=0) except: success = False self.popdown(True) if not success: title = _('Logs not captured') msg = _('The logs could not be captured.') notify = NotifyAlert() notify.props.title = title notify.props.msg = msg notify.connect('response', _notify_response_cb, self._activity) self._activity.add_alert(notify) jobject = datastore.create() metadata = { 'title': _('log-%s') % filename, 'title_set_by_user': '******', 'suggested_filename': filename, 'mime_type': 'application/zip', } for k, v in metadata.items(): jobject.metadata[k] = v jobject.file_path = filepath datastore.write(jobject) self._last_log = jobject.object_id jobject.destroy() activity.show_object_in_journal(self._last_log) os.remove(filepath) window.set_cursor(old_cursor) Gdk.flush()
def __init__(self, filepath=None): PREINSTALLED = [ (_('Giraffe'), "giraffe-blank.dita") ] root = os.path.join(get_activity_root(), 'tmp', 'book') shutil.rmtree(root, True) if not filepath: Book.__init__(self, PREINSTALLED, root) else: zip = zipfile.ZipFile(filepath, 'r') for i in zip.namelist(): path = os.path.join(root, i) os.makedirs(os.path.dirname(path), 0775) file(path, 'wb').write(zip.read(i)) zip.close() Book.__init__(self, [], root)
def create_playlist_jobject(self): """Create an object in the Journal to store the playlist. This is needed if the activity was not started from a playlist or from scratch. """ jobject = datastore.create() jobject.metadata['mime_type'] = "audio/x-mpegurl" jobject.metadata['title'] = _('Jukebox playlist') temp_path = os.path.join(activity.get_activity_root(), 'instance') if not os.path.exists(temp_path): os.makedirs(temp_path) jobject.file_path = tempfile.mkstemp(dir=temp_path)[1] return jobject
def read(self, file_path): instance_path = os.path.join(activity.get_activity_root(), 'instance') z = zipfile.ZipFile(file_path, 'r') for file_path in z.namelist(): if (file_path != './'): try: logging.debug('extracting %s', file_path) # la version de python en las xo no permite hacer # extract :( # z.extract(file_path,instance_path) data = z.read(file_path) fout = open(os.path.join(instance_path, file_path), 'w') fout.write(data) fout.close() except: logging.error('Error extracting %s', file_path) z.close() data_file_path = 'data.json' book_data = {} with open(os.path.join(instance_path, data_file_path)) as f: book_data = json.load(f) self.cover_path = book_data['cover_path'] self._pages = [] for page_data in book_data['pages']: page = Page() page.background_path = page_data['background_path'] page.text = page_data['text'] page.images = [] for image_data in page_data['images']: image = Image() image.path = image_data['path'] image.x = image_data['x'] image.y = image_data['y'] image.width = image_data['width'] image.height = image_data['height'] image.h_mirrored = image_data['h_mirrored'] image.v_mirrored = image_data['v_mirrored'] image.angle = image_data['angle'] page.images.append(image) self._pages.append(page)
def __open_on_journal(self, widget, url): '''Ask the journal to display a URL''' jobject = datastore.create() metadata = { 'title': '%s: %s' % (_('URL from Speak'), url), 'title_set_by_user': '******', 'icon-color': profile.get_color().to_string(), 'mime_type': 'text/uri-list', } for k, v in metadata.items(): jobject.metadata[k] = v file_path = os.path.join(get_activity_root(), 'instance', '%i_' % time.time()) open(file_path, 'w').write(url + '\r\n') os.chmod(file_path, 0755) jobject.set_file_path(file_path) datastore.write(jobject) show_object_in_journal(jobject.object_id) jobject.destroy() os.unlink(file_path)
def __handle_link_cb(self, widget, url_object): url = url_object.get_uri() logging.debug('Create journal entry for URL: %s', url) jobject = datastore.create() metadata = { 'title': "%s: %s" % (_('URL from Read'), url), 'title_set_by_user': '******', 'icon-color': profile.get_color().to_string(), 'mime_type': 'text/uri-list', } for k, v in metadata.items(): jobject.metadata[k] = v file_path = os.path.join(get_activity_root(), 'instance', '%i_' % time.time()) open(file_path, 'w').write(url + '\r\n') os.chmod(file_path, 0755) jobject.set_file_path(file_path) datastore.write(jobject) show_object_in_journal(jobject.object_id) jobject.destroy() os.unlink(file_path)
def _get_local_settings(activity): """ return an activity-specific Gio.Settings """ global _settings if _settings is None: # create schemas directory if missing path = os.path.join(get_activity_root(), 'data', 'schemas') if not os.access(path, os.F_OK): os.makedirs(path) # create compiled schema file if missing compiled = os.path.join(path, 'gschemas.compiled') if not os.access(compiled, os.R_OK): src = '%s.gschema.xml' % activity.get_bundle_id() lines = \ [ '<?xml version="1.0" encoding="UTF-8"?>', '<schemalist>', '<schema id="org.laptop.WebActivity" ' 'path="/org/laptop/WebActivity/">', '<key name="home-page" type="s">', "<default>''</default>", '<summary>Home page URL</summary>', '<description>URL to show as default or when home button ' 'is pressed.</description>', '</key>', '</schema>', '</schemalist>', ] open(os.path.join(path, src), 'w').writelines(lines) os.system('glib-compile-schemas %s' % path) os.remove(os.path.join(path, src)) # create a local Gio.Settings based on the compiled schema source = Gio.SettingsSchemaSource.new_from_directory(path, None, True) schema = source.lookup(SETTINGS_SCHEMA_ID, True) _settings = Gio.Settings.new_full(schema, None, None) return _settings
def __init__(self, game_path=None): tmp_root = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance') self.temp_folder = tempfile.mkdtemp(dir=tmp_root) chmod(self.temp_folder, 0777) self.data = {} if game_path is None: game_path = get_activity_root() if isdir(game_path): self.game_path = game_path else: logging.error('Game_path not found in %s' % game_path) return self.data['face'] = '' self.data['align'] = '1' self.data['divided'] = '0' self.data['equal_pairs'] = '0' self.data['font_name1'] = DEFAULT_FONT self.data['font_name2'] = DEFAULT_FONT self.pairs = {} self.grid = [] # used to know if the game should be saved and reloaded self.modified = False logging.debug('Model init is_demo False') self.is_demo = False # used by the leader of the game to keep track of the game state self.players = {} self.player_active = 0 self.selected = 0 self.turn = 0 self.started = 0 self.count = 0
def __init__(self): db_path = os.path.join(activity.get_activity_root(), 'data', 'places.db') self._connection = sqlite3.connect(db_path) cursor = self._connection.cursor() cursor.execute('select * from sqlite_master where name == "places"') if cursor.fetchone() is None: # Create table to store the visited places. Note that # bookmark and gecko_flags fields aren't used anymore in # WebKit port, but are kept for backwards compatibility. cursor.execute("""create table places ( uri text, title text, bookmark boolean, gecko_flags integer, visits integer, last_visit timestamp ); """) else: self._cleanup()
from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Pango from Reproductor import Reproductor from BarradeReproduccion import BarradeReproduccion from Radio import Radio import os import shutil from sugar3.activity import activity from ManejodeBasedeDatos import ManejodeBasedeDatos # Directorio para crear la base de datos directorio_base = os.path.join(activity.get_activity_root(), 'data/') mi_base = os.path.join(directorio_base + "Radios.db") # Si el directorio no existe, crearlo if not os.path.exists(directorio_base): os.mkdir(directorio_base) # Si la base de datos no existe, crearla if not os.path.exists(mi_base): BasedeDatos = ManejodeBasedeDatos(mi_base) BasedeDatos.CrearBasededatos() BasedeDatos.Llenar_Base() os.chmod(os.path.join(directorio_base, 'Radios.db'), 0660)
import telepathy import telepathy.client from sugar3.presence import presenceservice from sugar3.graphics.tray import HTray from sugar3 import profile from sugar3.graphics.alert import Alert from sugar3.graphics.alert import NotifyAlert from sugar3.graphics.icon import Icon from sugar3 import mime from sugar3.graphics.toolbarbox import ToolbarButton PROFILE_VERSION = 2 _profile_version = 0 _profile_path = os.path.join(activity.get_activity_root(), 'data/gecko') _version_file = os.path.join(_profile_path, 'version') _cookies_db_path = os.path.join(_profile_path, 'cookies.sqlite') if os.path.exists(_version_file): f = open(_version_file) _profile_version = int(f.read()) f.close() if _profile_version < PROFILE_VERSION: if not os.path.exists(_profile_path): os.mkdir(_profile_path) if os.path.exists('cert8.db'): shutil.copy('cert8.db', _profile_path) else:
COLOR_BG_BUTTONS = ( (Gtk.StateType.NORMAL, "#027F01"), (Gtk.StateType.ACTIVE, "#CCFF99"), (Gtk.StateType.PRELIGHT, "#016D01"), (Gtk.StateType.SELECTED, "#CCFF99"), (Gtk.StateType.INSENSITIVE, "#027F01"), ) OLD_COLOR_BG_BUTTONS = ( (Gtk.StateType.NORMAL, "#027F01"), (Gtk.StateType.ACTIVE, "#014D01"), (Gtk.StateType.PRELIGHT, "#016D01"), (Gtk.StateType.SELECTED, "#027F01"), (Gtk.StateType.INSENSITIVE, "#027F01"), ) SESSION_PATH = os.path.join(get_activity_root(), 'tmp', '.session') if os.path.isdir(SESSION_PATH): shutil.rmtree(SESSION_PATH) os.mkdir(SESSION_PATH) def path(*args): file = os.path.join(*args) if os.path.isabs(file): return file else: return os.path.join(get_bundle_path(), file) def pixbuf(file, size=None):
def write(self, file_name, page): """ Persitencia: Cuadro_titulo, globos[] Lista de cuadros, imagen de fondo, globos[] por cada globo: tipo, posicion (x,y), ancho, alto, direccion, pos_flecha (x,y), texto,font, tamanio, color """ instance_path = os.path.join(activity.get_activity_root(), 'instance') # Copio los datos de Page en PageData pageData = {} pageData['version'] = '1' pageData['boxs'] = [] for box in page.boxs: boxData = {} boxData['img_x'] = box.img_x boxData['img_y'] = box.img_y boxData['img_w'] = box.img_w boxData['img_h'] = box.img_h boxData['image_name'] = box.image_name boxData['slideshow_duration'] = box.slideshow_duration boxData['globes'] = [] for globo in box.globos: globoData = {} globoData['title_globe'] = (globo == box.title_globe) logging.debug('Saving %s', globo.globe_type) globoData['globe_type'] = globo.globe_type globoData['radio'] = globo.radio globoData['width'], globoData['height'] = \ globo.ancho, globo.alto if (globo.__class__ != globos.Rectangulo): globoData['point_0'] = globo.punto[0] globoData['point_1'] = globo.punto[1] globoData['direction'] = globo.direccion if (globo.__class__ == globos.Globo): globoData['mode'] = globo.modo if (globo.__class__ == globos.Imagen): globoData['image_name'] = globo.image_name globoData['x'], globoData['y'] = globo.x, globo.y if globo.texto is not None: globoData['text_width'] = globo.texto.ancho globoData['text_height'] = globo.texto.alto globoData['text_text'] = globo.texto.text globoData['text_color'] = globo.texto.color globoData['text_font_description'] = \ globo.texto.font_description boxData['globes'].append(globoData) pageData['boxs'].append(boxData) logging.debug('pageData %s', pageData) data_file_name = 'data.json' f = open(os.path.join(instance_path, data_file_name), 'w') try: json.dump(pageData, f) finally: f.close() logging.debug('file_name %s', file_name) z = zipfile.ZipFile(file_name, 'w') z.write(os.path.join(instance_path, data_file_name).encode( 'ascii', 'ignore'), data_file_name.encode('ascii', 'ignore')) for box in page.boxs: if (box.image_name != ''): z.write(os.path.join( instance_path, box.image_name).encode('ascii', 'ignore'), box.image_name.encode('ascii', 'ignore')) z.close()
def __init__(self, handle): ''' Initialize the toolbars and the game board ''' try: super(StoryActivity, self).__init__(handle) except dbus.exceptions.DBusException as e: _logger.error(str(e)) self._path = activity.get_bundle_path() self.datapath = os.path.join(activity.get_activity_root(), 'instance') self._nick = profile.get_nick_name() if profile.get_color() is not None: self._colors = profile.get_color().to_string().split(',') else: self._colors = ['#A0FFA0', '#FF8080'] self._old_cursor = self.get_window().get_cursor() self.tablet_mode = _is_tablet_mode() self.recording = False self.audio_process = None self._arecord = None self._alert = None self._uid = None self._setup_toolbars() self._setup_dispatch_table() self._fixed = Gtk.Fixed() self._fixed.connect('size-allocate', self._fixed_resize_cb) self._fixed.show() self.set_canvas(self._fixed) self._vbox = Gtk.VBox(False, 0) self._vbox.set_size_request(Gdk.Screen.width(), Gdk.Screen.height()) self._fixed.put(self._vbox, 0, 0) self._vbox.show() self._canvas = Gtk.DrawingArea() self._canvas.set_size_request(int(Gdk.Screen.width()), int(Gdk.Screen.height())) self._canvas.show() self._vbox.pack_end(self._canvas, True, True, 0) self._vbox.show() entry_width = Gdk.Screen.width() - 7 * style.GRID_CELL_SIZE - \ 2 * style.DEFAULT_SPACING entry_height = 3 * style.GRID_CELL_SIZE - 2 * style.DEFAULT_SPACING self._entry = Gtk.TextView() self._entry.set_wrap_mode(Gtk.WrapMode.WORD) self._entry.set_pixels_above_lines(0) self._entry.set_size_request(entry_width, entry_height) font_desc = Pango.font_description_from_string('14') self._entry.modify_font(font_desc) self.text_buffer = self._entry.get_buffer() self.text_buffer.set_text(PLACEHOLDER) self._entry.connect('focus-in-event', self._text_focus_in_cb) self._entry.connect('key-press-event', self._text_focus_in_cb) self._entry.connect('focus-out-event', self._text_focus_out_cb) self._entry.get_buffer().connect('changed', self._text_changed_cb) self._entry.show() self._scrolled_window = Gtk.ScrolledWindow() self._scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN) self._scrolled_window.set_size_request( Gdk.Screen.width() - 6 * style.GRID_CELL_SIZE, style.GRID_CELL_SIZE * 3) self._scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) rgba = Gdk.RGBA() rgba.red, rgba.green, rgba.blue, rgba.alpha = 1., 1., 1., 1. self._scrolled_window.override_background_color( Gtk.StateFlags.NORMAL, rgba) self._scrolled_window.add(self._entry) if self.tablet_mode: self._fixed.put(self._scrolled_window, 3 * style.GRID_CELL_SIZE, style.DEFAULT_SPACING) else: self._fixed.put( self._scrolled_window, 3 * style.GRID_CELL_SIZE, Gdk.Screen.height() - style.DEFAULT_SPACING - style.GRID_CELL_SIZE * 4) self._scrolled_window.show() self._fixed.show() self._game = Game(self._canvas, parent=self, path=self._path, root=activity.get_bundle_path(), colors=self._colors) self._setup_presence_service() if 'mode' in self.metadata: self._game.set_mode(self.metadata['mode']) if self.metadata['mode'] == 'array': self.array_button.set_active(True) self.autoplay_button.set_sensitive(False) else: self._linear_button.set_active(True) if 'uid' in self.metadata: self._uid = self.metadata['uid'] else: self._uid = generate_uid() self.metadata['uid'] = self._uid if 'dotlist' in self.metadata: self._restore() self.check_audio_status() self.check_text_status() else: self._game.new_game() Gdk.Screen.get_default().connect('size-changed', self._configure_cb)
from sugar3.graphics.alert import NotifyAlert from sugar3.graphics.icon import Icon from sugar3.graphics.animator import Animator, Animation from sugar3 import mime from sugar3.graphics.toolbarbox import ToolbarButton from sugar3 import profile from collabwrapper.collabwrapper import CollabWrapper from widgets import TitledTray PROFILE_VERSION = 2 THUMB_WIDTH, THUMB_HEIGHT = style.zoom(100), style.zoom(80) _profile_version = 0 _profile_path = os.path.join(activity.get_activity_root(), 'data/gecko') _version_file = os.path.join(_profile_path, 'version') _cookies_db_path = os.path.join(_profile_path, 'cookies.sqlite') if os.path.exists(_version_file): f = open(_version_file) _profile_version = int(f.read()) f.close() if _profile_version < PROFILE_VERSION: if not os.path.exists(_profile_path): os.mkdir(_profile_path) if os.path.exists('cert8.db'): shutil.copy('cert8.db', _profile_path) else:
# -*- coding: utf-8 -*- import os import logging from os.path import join from gi.repository import Gdk try: from sugar3.activity.activity import get_bundle_path, get_activity_root TAM_TAM_ROOT = get_bundle_path() ACTIVITY_ROOT = get_activity_root() except: TAM_TAM_ROOT = os.getcwd() ACTIVITY_ROOT = os.getcwd() #QUICKLOAD = os.path.isfile("QUICKLOAD") # skip loading inessential comenents to speed things up FEATURES_OGG = True FEATURES_MIC = None FEATURES_LAB = None FEATURES_NEWSOUNDS = None FEATURES_GRAB_MOUSE = None if os.path.isfile("DEBUG"): f = open("DEBUG") l = f.read(10) f.close() if len(l): DEBUG = int(l) else: DEBUG = 99
def __init__(self, handle): ''' Initialize the toolbar ''' try: super(ReflectActivity, self).__init__(handle) except dbus.exceptions.DBusException as e: _logger.error(str(e)) logging.error('setting reflection data to []') self.reflection_data = [] self.connect('realize', self.__realize_cb) self.font_size = 8 self.max_participants = 4 self._setup_toolbars() color = profile.get_color() color_stroke = color.get_stroke_color() color_fill = color.get_fill_color() lighter = utils.lighter_color([color_stroke, color_fill]) darker = 1 - lighter if lighter == 0: self.bg_color = style.Color(color_stroke) self.fg_color = style.Color(color_fill) else: self.bg_color = style.Color(color_fill) self.fg_color = style.Color(color_stroke) self.modify_bg(Gtk.StateType.NORMAL, self.bg_color.get_gdk_color()) self.bundle_path = activity.get_bundle_path() self.tmp_path = os.path.join(activity.get_activity_root(), 'instance') self.sharing = False self._copy_entry = None self._paste_entry = None self._webkit = None self._clipboard_text = '' self._fixed = None self.initiating = True if self.shared_activity: # We're joining if not self.get_shared(): self.initiating = False self.busy_cursor() share_icon = Icon(icon_name='zoom-neighborhood') self._joined_alert = Alert() self._joined_alert.props.icon = share_icon self._joined_alert.props.title = _('Please wait') self._joined_alert.props.msg = _('Starting connection...') self.add_alert(self._joined_alert) # Wait for joined signal self.connect("joined", self._joined_cb) self._open_reflect_windows() self._setup_presence_service() # Joiners wait to receive data from sharer # Otherwise, load reflections from local store if not self.shared_activity: self.busy_cursor() GObject.idle_add(self._load_reflections)