def load_from_file(uri):
     """Determine the correct subclass to instantiate.
     
     Also time everything and report how long it took. Raises IOError if
     the file extension is unknown, or no track points were found.
     """
     start_time = clock()
     
     try:
         gpx = globals()[uri[-3:].upper() + 'File'](uri)
     except KeyError:
         raise IOError
     
     Widgets.status_message(_('%d points loaded in %.2fs.') %
         (len(gpx.tracks), clock() - start_time), True)
     
     if len(gpx.tracks) < 2:
         return
     
     TrackFile.instances.add(gpx)
     MapView.emit('realize')
     MapView.set_zoom_level(MapView.get_max_zoom_level())
     MapView.ensure_visible(TrackFile.get_bounding_box(), False)
     
     TrackFile.update_range()
     Camera.set_all_found_timezone(gpx.start.geotimezone)
 def load_from_file(uri):
     """Coordinates instantiation of various classes.
     
     Ensures that related Photograph, Camera, CameraView, and Label are all
     instantiated together.
     """
     photo = Photograph(uri)
     photo.read()
     
     Widgets.empty_camera_list.hide()
     
     camera_id, camera_name = Camera.generate_id(photo.camera_info)
     camera = Camera(camera_id)
     camera.add_photo(photo)
     
     CameraView(camera, camera_name)
     Label(photo)
     
     # If the user has selected the lookup method, then the timestamp
     # was probably calculated incorrectly the first time (before the
     # timezone was discovered). So call it again to get the correct value.
     if camera.timezone_method == 'lookup':
         photo.calculate_timestamp(camera.offset)
     
     Widgets.button_sensitivity()
     
     return photo
def animate_in(anim=True):
    """Fade in all the map actors."""
    for i in xrange(Gst.get_int('animation-steps') if anim else 1, 0, -1):
        for actor in (Crosshair, Box, Scale):
            actor.set_opacity(256 - i)
        Widgets.redraw_interface()
        sleep(0.01)
 def search_completed(self, entry, model, itr):
     """Go to the selected location."""
     self.last_search = itr.copy()
     MapView.emit('realize')
     MapView.set_zoom_level(MapView.get_max_zoom_level())
     Widgets.redraw_interface()
     MapView.center_on(*model.get(itr, LATITUDE, LONGITUDE))
     MapView.set_zoom_level(11)
Beispiel #5
0
def startPage():
    main_frame = tk.Frame(master=window, bg='#d93253', height=250, width=250)
    main_frame.grid(row=3, column=0)
    ### buttons
    for i in range(3):
        for j in range(3):
            btn1 = Widgets()
            btn1.new_grid_button(main_frame, f"{i},{j}", 10, 5, '#d93253', i,
                                 j)
    get_player_name(main_frame)
Beispiel #6
0
 def __init__(self, access_token=''):
     self.Account = Account(access_token=access_token)
     self.Apps = Apps(access_token=access_token)
     self.Audio = Audio(access_token=access_token)
     self.Auth = Auth(access_token=access_token)
     self.Board = Board(access_token=access_token)
     self.Database = Database(access_token=access_token)
     self.Docs = Docs(access_token=access_token)
     self.Other = Other(access_token=access_token)
     self.Fave = Fave(access_token=access_token)
     self.Friends = Friends(access_token=access_token)
     self.Gifts = Gifts(access_token=access_token)
     self.Groups = Groups(access_token=access_token)
     self.Likes = Likes(access_token=access_token)
     self.Market = Market(access_token=access_token)
     self.Messages = Messages(access_token=access_token)
     self.Newsfeed = Newsfeed(access_token=access_token)
     self.Notes = Notes(access_token=access_token)
     self.Notifications = Notifications(access_token=access_token)
     self.Pages = Pages(access_token=access_token)
     self.Photos = Photos(access_token=access_token)
     self.Places = Places(access_token=access_token)
     self.Polls = Polls(access_token=access_token)
     self.Search = Search(access_token=access_token)
     self.Stats = Stats(access_token=access_token)
     self.Status = Status(access_token=access_token)
     self.Storage = Storage(access_token=access_token)
     self.Users = Users(access_token=access_token)
     self.Utils = Utils(access_token=access_token)
     self.Video = Video(access_token=access_token)
     self.Wall = Wall(access_token=access_token)
     self.Widgets = Widgets(access_token=access_token)
Beispiel #7
0
    def get(self, par):

        # all blog and static pages are cacheable
        if self._check_get_from_cache():
            return True

        self.widgets = Widgets(self, self._conf)

        # get the groups
        self._obj['groups'] = Group.all()

        routes = [
            # {"r": self._conf.BLOG + "/widget/(.*)",  "f": self._get_widget},
            {"r": "/rssfeed(.*)",                      "f": self._force_rss},
            {"r": self._conf.BLOG + "/search\?q=(.*)", "f": self._get_blog_search},
            {"r": self._conf.BLOG + "/(.*)/(.*)\?",    "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)/(.*)",      "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)\?",         "f": self._get_blog_group},
            {"r": self._conf.BLOG + "/(.*)",           "f": self._get_blog_group},
            {"r": self._conf.BLOG + ".*",              "f": self._get_blog},
            {"r": "/(.*)\?",                           "f": self._get_static},
            {"r": "/(.*)",                             "f": self._get_static}
        ]
            
        if self._req.route(routes):
            # cache the return url        
            self._req.sesh().set_return_url(self._req.spath())
            self._req.sesh().save();
            return True
        
        return False
Beispiel #8
0
    def _init_widgets(self):
        """Initialize widgets"""

        self.widgets = Widgets(self)

        self.entry_line = Entryline(self)
        self.grid = Grid(self)

        self.macro_panel = MacroPanel(self, self.grid.model.code_array)

        self.main_splitter = QSplitter(Qt.Vertical, self)
        self.setCentralWidget(self.main_splitter)

        self.main_splitter.addWidget(self.entry_line)
        self.main_splitter.addWidget(self.grid)
        self.main_splitter.addWidget(self.grid.table_choice)
        self.main_splitter.setSizes(
            [self.entry_line.minimumHeight(), 9999, 20])

        self.macro_dock = QDockWidget("Macros", self)
        self.macro_dock.setObjectName("Macro Panel")
        self.macro_dock.setWidget(self.macro_panel)
        self.addDockWidget(Qt.RightDockWidgetArea, self.macro_dock)

        self.macro_dock.installEventFilter(self)

        self.gui_update.connect(self.on_gui_update)
        self.refresh_timer.timeout.connect(self.on_refresh_timer)
Beispiel #9
0
    def __init__gui(self):
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon(r'.\icons\icon.ico'))
        self.setGeometry(self.left,
                         self.top,
                         self.width,
                         self.height)

        self.__initMenuBar()

        self.generalSettingsWidget = Widgets.generalSettings()
        self.maintenanceWidget = Widgets.Maintenance()
        self.banDetectionWidget = Widgets.BanDetection()
        self.tmrLoggingWidget = Widgets.TMRLogging()

        self.set_api_key()

        self.__initTabs()
Beispiel #10
0
    def _create_window(self):
        window = self.controller.window
        window.title("Optimisation")

        wsize = (1000, 600)
        window.geometry('%dx%d' % wsize)
        window.resizable(width=False, height=False)

        frame = tk.Frame(window, bg="gray94", width=wsize[0], height=wsize[1])
        frame.pack()

        widgets = Widgets(self, frame)
        self._set_default_values()
Beispiel #11
0
    def __init__(self):

        wg = Widgets()
        self.sk = Cliente()

        self.sm = wg.sm

        # Telas
        self.screen_home = wg.screen_home # name = home
        self.screen_terminal = wg.screen_terminal # name = terminal
        self.screen_cadastro = wg.screen_cadastro # name = cadastro
        
        # Home
        self.label = wg.label
        
        self.entry_host = wg.entry_host
        self.entry_port = wg.entry_port
        
        # Terminal
        self.lbterminal = wg.lbterminal

        self.entry_comando = wg.entry_comando

        self.botao = wg.botao
        self.botao.bind(on_release = lambda x: self.conectar())

        self.botao_ins = wg.botao_ins
        self.botao_ins.bind(on_release = lambda x: self.insert())

        self.botao_ping = wg.botao_ping
        self.botao_ping.bind(on_release = lambda x: self.ping())

        self.botao_env = wg.botao_env
        self.botao_env.bind(on_release = lambda x: self.enviar())

        self.botao_desc = wg.botao_desc
        self.botao_desc.bind(on_release = lambda x: self.desconectar())

        # Cadastro

        self.lbcadastro = wg.lbcadastro
        self.entry_nome = wg.entry_nome
        self.entry_sexo = wg.entry_sexo
        self.entry_telefone = wg.entry_telefone
        self.entry_email = wg.entry_email

        self.btsend = wg.bt_send
        self.btsend.bind(on_release = lambda x: self.send())
    def _create_window(self):
        window = self.controller.window

        # Для изменения заголовка окна
        window.title('Quadrocopter')

        # Для изменения размеров окна wsize
        wsize = (1000, 600)

        window.geometry('%dx%d' % wsize)
        window.resizable(width=False, height=False)

        # Для изменения БГ окна
        frame = tk.Frame(window, bg='gray94', width=wsize[0], height=wsize[1])

        self._create_tabs()

        frame.pack()

        widgets = Widgets(self, frame)
        self._set_default_values()
Beispiel #13
0
    def get(self, par):

        # all blog and static pages are cacheable
        if self._check_get_from_cache():
            return True

        self.widgets = Widgets(self, self._conf)

        # TODO filterise this some umbraco url specific tidying
        # if self._req.ext() == 'aspx':
        #     return self._aspx_redirect()

        # self._req.remove_par("c")
        # self._req.remove_par("C")

        # get the groups
        self._obj['groups'] = Group.all()

        routes = [
            # {"r": self._conf.BLOG + "/widget/(.*)",  "f": self._get_widget},
            {"r": "/rssfeed(.*)",                     "f": self._force_rss},
            {"r": self._conf.BLOG + "/(.*)/(.*)\?",    "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)/(.*)",      "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)\?",         "f": self._get_blog_group},
            {"r": self._conf.BLOG + "/(.*)",           "f": self._get_blog_group},
            {"r": self._conf.BLOG + ".*",              "f": self._get_blog},
            {"r": "/(.*)\?",                          "f": self._get_static},
            {"r": "/(.*)",                            "f": self._get_static}
        ]
            
        if self._req.route(routes):
            # cache the return url        
            self._req.sesh().set_return_url(self._req.spath())
            self._req.sesh().save();
            return True
        
        return False
Beispiel #14
0
 def __init__(self, glade, objeto = None, usuario = None):
     """
     Constructor.
     glade es una cadena con el nombre del fichero .glade a cargar.
     objeto es el objeto principal de la ventana.
     Si usuario se recibe, se guarda en un atributo privado de la 
     clase que servirá únicamente para crear un menú superior en 
     la ventana con las opciones de menú disponibles para el usuario.
     Si el usuario es None, no se crea ningún menú.
     """
     if isinstance(usuario, int):
         usuario = pclases.Usuario.get(usuario)
     self.__usuario = usuario
     self._is_fullscreen = False
     import logging
     self.logger = logging.getLogger('GINN')
     # El fichero de log lo voy a plantar en el raíz del proyecto.
     rutalogger = os.path.join(os.path.dirname(__file__), "..", 'ginn.log')
     hdlr = logging.FileHandler(rutalogger)
     formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
     hdlr.setFormatter(formatter)
     self.logger.addHandler(hdlr)
     # self.logger.setLevel(logging.INFO)
     try:
         self.wids = Widgets(glade)  # Puede que venga la ruta ya y no 
                                     # haga falta combinar con os.path.join.
     except RuntimeError:
         try:
             self.wids = Widgets(os.path.join("formularios","glades",glade))
         except RuntimeError:
             try:
                 self.wids = Widgets(os.path.join("glades", glade))
             except RuntimeError:
                 try:
                     self.wids = Widgets(os.path.join(
                                     "..", "formularios", "glades", glade))
                 except RuntimeError:
                     if pclases.DEBUG and pclases.VERBOSE:
                         print "ventana.py::Ventana.__init__ -> "\
                               "No encuentro el glade. Estoy en %s. "\
                               "Intento cargar de nuevo desde donde "\
                               "se supone que debería estar." % (
                                 os.path.abspath(os.path.curdir))
                     self.wids = Widgets(glade)
     self.refocus_enter()
     try:
         self.wids['ventana'].set_border_width(5)
         # TODO:Cambiar por uno correspondiente al logo de la configuración. 
         ruta_logo = os.path.join("imagenes", 'logo.xpm')
         logo_xpm = gtk.gdk.pixbuf_new_from_file(ruta_logo) 
         self.wids['ventana'].set_icon(logo_xpm)
         self.wids['barra_estado'] = gtk.Statusbar()
         label_statusbar = self.wids['barra_estado'].get_children()[0].child
         font = pango.FontDescription("Monospace oblique 7")
         label_statusbar.modify_font(font)
         label_statusbar.modify_fg(gtk.STATE_NORMAL, 
             label_statusbar.get_colormap().alloc_color("darkgray"))
         contenido_anterior = self.wids['ventana'].get_child()
         self.wids['ventana'].remove(contenido_anterior)
         self.wids['contenedor_exterior'] = gtk.VBox()
         self.wids['ventana'].add(self.wids['contenedor_exterior'])
         self.wids['menu_superior'] = self.build_menu_superior()
         self.wids['contenedor_exterior'].pack_start(
             self.wids['menu_superior'], False)
         self.wids['contenedor_exterior'].add(contenido_anterior)
         self.wids['contenedor_exterior'].pack_end(
             self.wids['barra_estado'], False)
         self.wids['contenedor_exterior'].show()
         self.wids['barra_estado'].show()
         config = ConfigConexion()
         info_conexion = "%s://%s:xxxxxxxx@%s:%s/%s" % (config.get_tipobd(), 
                                                        config.get_user(), 
                                                        config.get_host(), 
                                                        config.get_puerto(), 
                                                        config.get_dbname())
         info_usuario = ""
         if hasattr(self, "usuario") and self.__usuario != None:
             info_usuario = " usuario: %s." % (self.__usuario.usuario)
         if self.__usuario != None:
             info_usuario = " __usuario: %s." % (self.__usuario.usuario)
         ui.escribir_barra_estado(self.wids['barra_estado'], 
                                  "Conectado a %s.%s" % (info_conexion, 
                                                         info_usuario))
     except Exception, msg:
         txt = "ventana.py::__init__ -> No se pudo establecer ancho "\
               "de borde, icono de ventana o barra de estado. "\
               "Excepción: %s." % (msg)
         self.logger.warning(txt)
Beispiel #15
0
class RouteBlog():

    def __init__(self, req, conf):
        self._req = req
        self._conf = conf
        self._obj = {}

        if self._req.ext() == 'xml':
            self._PAGESIZE = self._conf.RSS_PAGE
        else:
            self._PAGESIZE = self._conf.BLOG_PAGE

        
    def get(self, par):

        # all blog and static pages are cacheable
        if self._check_get_from_cache():
            return True

        self.widgets = Widgets(self, self._conf)

        # get the groups
        self._obj['groups'] = Group.all()

        routes = [
            # {"r": self._conf.BLOG + "/widget/(.*)",  "f": self._get_widget},
            {"r": "/rssfeed(.*)",                      "f": self._force_rss},
            {"r": self._conf.BLOG + "/search\?q=(.*)", "f": self._get_blog_search},
            {"r": self._conf.BLOG + "/(.*)/(.*)\?",    "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)/(.*)",      "f": self._get_blog_single},
            {"r": self._conf.BLOG + "/(.*)\?",         "f": self._get_blog_group},
            {"r": self._conf.BLOG + "/(.*)",           "f": self._get_blog_group},
            {"r": self._conf.BLOG + ".*",              "f": self._get_blog},
            {"r": "/(.*)\?",                           "f": self._get_static},
            {"r": "/(.*)",                             "f": self._get_static}
        ]
            
        if self._req.route(routes):
            # cache the return url        
            self._req.sesh().set_return_url(self._req.spath())
            self._req.sesh().save();
            return True
        
        return False


    def post(self, par):
        routes = [            
            {"r": "/contact-form(.*)",             "f": self._contact_email}
        ]
        if self._req.route(routes):
            return True
        return False
        

    def _contact_email(self, par):
        emails = Emails(self._req)
        emails.contact()
        # now return the static reply page
        self.get(par)


    # def _aspx_redirect(self):
    #     """ check the last part of the path for any stored redirects """
    #     ppart = self._req.pathel(self._req.length()-1, encode=True)
    #     logging.debug(ppart)

    #     q = Redirect.all().filter("fromurl = ", ppart)
    #     np = q.get()
    #     if np:
    #         newp = self._req.path()[:-1]
    #         newp.append(np.tourl)
    #         self._req.redirect(str("/" + "/".join(newp)))
    #     else:
    #         self._req.redirect(self._req.spath())        # some specific redirects        


    def _check_cache_exception(self):
        if re.search("/search\?q=", self._req.spath(), re.IGNORECASE):
            return True
        
        return False


    def _check_get_from_cache(self):
        
        if self._check_cache_exception():
            return False

        if not self._conf.CACHE:
            return False
            
        # only get fom cache if not editng
        if self._req.sesh().can_edit():
            return False

        logging.debug("lookin in cache: " + self._req.get_cache_key())
        data = memcache.get(self._req.get_cache_key())
        if data is None:
            logging.debug("cache miss")
            return False
        
        logging.debug("cache hit")
        self._req.blast(data)

        if self._req.ext() == 'xml':
            self._req.set_header('Content-Type', 'application/rss+xml')

        return True     # got it form cache


    def get_image(self, par):
        """ called directly from main get router """
        try:
            iid = int(par[0]);
            img = Image.get_by_id(iid)
            if img:
                self._req.redirect(str(img.serving_url))
            else:
                self._req.notfound()
        except:
            self._req.notfound()


    def _force_rss(self, par):
        """ if some urls without a .xml extension are requesting rss """
        self._PAGESIZE = self._conf.RSS_PAGE
        self._get_blog([], xml=True)


    def _get_blog_single(self, par):

        ut = Utils()
        self._build_widgets_single()

        o = self._obj
        # if it is the single blog view and the user is an editor then load up the images for the image select box
        if self._req.sesh().can_edit():
            o['images'] = Image.all().order("-date").fetch(self._conf.IMAGES_VIEWER_COUNT)

        content = Content.get_by_key_name(par[1])
        if content:
            o['data'] = self.copy_bits(content)
        
            # versions for admin - perhaps optimise this out with a isAdmin clause
            o['data'].otherversions = content.contentversion_set
            ov = []
            for c in content.contentversion_set:
                c.nicetime = c.createtime.strftime('%e %b %Y - %H:%M:%S')
                ov.append(c)
            o['data'].otherversions = ov
            
            # what to put in the meta description - needed for singe blog post only
            if content.current.summary:
                o['data'].metadesc = ut.strip_tags(content.current.summary)
            else:
                o['data'].metadesc = o['data'].title
     
            # no paging controls - for a single blog
            o['page'] = {}
            
        else:
            return self._req.notfound()

        self._respond(path='blog-single', obj=self._obj)


    def _get_blog_group(self, par):
        """ all blog articles in the group """

        group = Group.get_by_key_name(par[0])
        if group:
            q = group.content_set
            self._obj['title'] = group.title
            self._get_blog_list(q)
        else:
            return self._req.notfound()


    def _get_blog(self, par, xml=False):
        """ all blog articles """

        q = Content.all();
        self._obj['title'] = self._conf.BLOG_TITLE
        self._get_blog_list(q, xml)


    def _get_blog_search(self, par, xml=False):
        """ all blog articles matching search result """
        self._curpage = int(self._req.par('p', default_value = 1))

        self._obj['title'] = "Search"

        search = BlogSearch()
        result = search.get(par[0])
        
        newest = datetime.datetime.fromtimestamp(0)
        self._obj['data'] = []

        count = 0
        for r in result:
            count = count + 1

            logging.debug(r.doc_id)

            c = Content.get_by_key_name(r.doc_id)
            d = self.copy_bits(c)

            self._obj['data'].append(d)
            
            if c.sortdate > newest:
                newest = c.sortdate

        # fill in all our widgets        
        self._build_widgets_list(count, None)


        self._respond(path='blog-search', obj=self._obj, xml=xml, search={"term":par[0], "count": count})


    def _get_blog_list(self, q, xml=False):

        self._curpage = int(self._req.par('p', default_value = 1))

        self._obj['data'] = []

        q.filter('ctype =', 'blog').order("-sortdate");

        if not self._req.sesh().can_edit():
            q.filter('status =', 'published')
        
        # fill in all our widgets        
        self._build_widgets_list(q.count(), q)

        # to stick in the rss
        newest = datetime.datetime.fromtimestamp(0)
        
        for c in q.fetch(self._PAGESIZE, offset=(self._curpage-1) * self._PAGESIZE):
            d = self.copy_bits(c)

            d.rssdate = emailutils.formatdate(time.mktime(c.sortdate.timetuple()), usegmt=True)
            
            self._obj['data'].append(d)

            if c.sortdate > newest:
                newest = c.sortdate

        # format in the rss standard format
        self._obj['rssrecentdate'] = emailutils.formatdate(time.mktime(newest.timetuple()), usegmt=True)
           
        self._respond(path='blog', obj=self._obj, xml=xml)


    def _build_widgets_single(self):
        # create the widgets container
        self._obj['widge'] = {}
        self._obj['widge']['popular'] = self.widgets.popular()


    def _build_widgets_list(self, count, q):

        self._build_widgets_single()
        self._obj['page'] = self.widgets.pagination(count)
        if q:
            self._obj['slider'] = self.widgets.slider(q)

    
    def _get_static(self, par):
        """ all other none blog pages """
        try:
            self._respond(path="pages/" + par[0])
        except:
            return False    # this will triger the not found

        return True
        

    # def _get_widget(self, par):
        
    #     # simply return widget content
    #     content = Content.get_by_key_name(par[0])
    #     if content:
    #         return self.response.write(content.current.content)
    #     else:
    #         return self.redirect('/404')  # respond with a 404 not ging to the 404 page


    def copy_bits(self, c):
        """ used bt the slider widget and the blog list to copy content bits to the contentver for display"""

        if self._req.sesh().can_edit():
            d = c.editing
        else:
            d = c.current

        d.keyname = c.key().name()
        d.group = c.group
        d.author = c.author.displayname

        d.ctype = c.ctype
        d.status = c.status

        d.nicedate = c.sortdate.strftime('%e %b %Y')
        
        # use hard coded imagepath, or the mainimage's url
        if not d.imagepath:
            if d.mainimage:
                d.imagepath = d.mainimage.serving_url
        return d


    def _respond(self, path, obj={}, xml=False, search={}):
        """ draw the html and add it to the response then decide to add to or flush the cashe if admin"""
        
        opt = {
            "appname": self._conf.APP_NAME,
            "blog_name": self._conf.BLOG,
            "fb_app_id": self._conf.FB_APP_ID,
            "can_edit": self._req.sesh().can_edit(),
            "authed": self._req.sesh().authorised(),
            "authfor": self._req.sesh().user_name(),
            "url": self._req.spath(query=False),
            "search": search 
        }

        if self._req.ext() == 'xml' or xml:
            path = "rss"
            self._req.set_header('Content-Type', 'application/rss+xml')

        html = self._req.draw(path=path, obj=obj, opt=opt)

        # if an admin hits the page then clear this out of the cache
        if self._conf.CACHE:
            # if an admin hits the page then clear this out of the cache
            if self._req.sesh().can_edit():
                memcache.delete(self._req.get_cache_key())
            else:
                if not memcache.add(self._req.get_cache_key(), html, 3600):   #3600 = 1 hour 
                    logging.error("MEMCACHE MISTAKE")
Beispiel #16
0
 def __init__(self, glade, objeto = None, usuario = None):
     """
     Constructor.
     glade es una cadena con el nombre del fichero .glade a cargar.
     objeto es el objeto principal de la ventana.
     Si usuario se recibe, se guarda en un atributo privado de la 
     clase que servirá únicamente para crear un menú superior en 
     la ventana con las opciones de menú disponibles para el usuario.
     Si el usuario es None, no se crea ningún menú.
     """
     if isinstance(usuario, int):
         usuario = pclases.Usuario.get(usuario)
     self.__usuario = usuario
     self._is_fullscreen = False
     import logging
     self.logger = logging.getLogger('GINN')
     hdlr = logging.FileHandler('ginn.log')
     formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
     hdlr.setFormatter(formatter)
     self.logger.addHandler(hdlr)
     # self.logger.setLevel(logging.INFO)
     self.wids = Widgets(glade)
     self.handlers_id = dict([(w, {}) for w in self.wids.keys()])
     for w in self.wids.keys():
         if isinstance(self.wids[w], gtk.Entry):
             h_id = self.wids[w].connect("activate", self.refocus_entry)
             try:
                 self.handlers_id[w]["activate"].append(h_id)
             except KeyError:
                 self.handlers_id[w]["activate"] = [h_id]
     config = ConfigConexion()
     try:
         self.wids['ventana'].set_border_width(5)
         # TODO:Cambiar por uno correspondiente al logo de la configuración. 
         logo_xpm = gtk.gdk.pixbuf_new_from_file('logo_w.xpm')
         self.wids['ventana'].set_icon(logo_xpm)
         self.wids['barra_estado'] = gtk.Statusbar()
         label_statusbar = self.wids['barra_estado'].get_children()[0].child
         font = pango.FontDescription("Monospace oblique 7")
         label_statusbar.modify_font(font)
         label_statusbar.modify_fg(gtk.STATE_NORMAL, 
             label_statusbar.get_colormap().alloc_color("darkgray"))
         contenido_anterior = self.wids['ventana'].get_child()
         self.wids['ventana'].remove(contenido_anterior)
         self.wids['contenedor_exterior'] = gtk.VBox()
         self.wids['ventana'].add(self.wids['contenedor_exterior'])
         self.wids['menu_superior'] = self.build_menu_superior()
         self.wids['contenedor_exterior'].pack_start(
             self.wids['menu_superior'], False)
         self.wids['contenedor_exterior'].add(contenido_anterior)
         self.wids['contenedor_exterior'].pack_end(
             self.wids['barra_estado'], False)
         self.wids['contenedor_exterior'].show()
         self.wids['barra_estado'].show()
         info_conexion = "%s://%s:xxxxxxxx@%s:%s/%s" % (config.get_tipobd(), 
                                                        config.get_user(), 
                                                        config.get_host(), 
                                                        config.get_puerto(), 
                                                        config.get_dbname())
         info_usuario = ""
         if hasattr(self, "usuario") and self.usuario != None:
             info_usuario = " usuario: %s." % (self.usuario.usuario)
         if self.__usuario != None:
             info_usuario = " __usuario: %s." % (self.__usuario.usuario)
         utils.escribir_barra_estado(self.wids['barra_estado'], "Conectado a %s.%s" % (info_conexion, info_usuario))
     except Exception, msg:
         txt = "ventana.py::__init__ -> No se pudo establecer ancho de borde, icono de ventana o barra de estado. Excepción: %s." % (msg)
         self.logger.warning(txt)
Beispiel #17
0
class Ventana:
    def __init__(self, glade, objeto = None, usuario = None):
        """
        Constructor.
        glade es una cadena con el nombre del fichero .glade a cargar.
        objeto es el objeto principal de la ventana.
        Si usuario se recibe, se guarda en un atributo privado de la 
        clase que servirá únicamente para crear un menú superior en 
        la ventana con las opciones de menú disponibles para el usuario.
        Si el usuario es None, no se crea ningún menú.
        """
        if isinstance(usuario, int):
            usuario = pclases.Usuario.get(usuario)
        self.__usuario = usuario
        self._is_fullscreen = False
        import logging
        self.logger = logging.getLogger('GINN')
        hdlr = logging.FileHandler('ginn.log')
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        # self.logger.setLevel(logging.INFO)
        self.wids = Widgets(glade)
        self.handlers_id = dict([(w, {}) for w in self.wids.keys()])
        for w in self.wids.keys():
            if isinstance(self.wids[w], gtk.Entry):
                h_id = self.wids[w].connect("activate", self.refocus_entry)
                try:
                    self.handlers_id[w]["activate"].append(h_id)
                except KeyError:
                    self.handlers_id[w]["activate"] = [h_id]
        config = ConfigConexion()
        try:
            self.wids['ventana'].set_border_width(5)
            # TODO:Cambiar por uno correspondiente al logo de la configuración. 
            logo_xpm = gtk.gdk.pixbuf_new_from_file('logo_w.xpm')
            self.wids['ventana'].set_icon(logo_xpm)
            self.wids['barra_estado'] = gtk.Statusbar()
            label_statusbar = self.wids['barra_estado'].get_children()[0].child
            font = pango.FontDescription("Monospace oblique 7")
            label_statusbar.modify_font(font)
            label_statusbar.modify_fg(gtk.STATE_NORMAL, 
                label_statusbar.get_colormap().alloc_color("darkgray"))
            contenido_anterior = self.wids['ventana'].get_child()
            self.wids['ventana'].remove(contenido_anterior)
            self.wids['contenedor_exterior'] = gtk.VBox()
            self.wids['ventana'].add(self.wids['contenedor_exterior'])
            self.wids['menu_superior'] = self.build_menu_superior()
            self.wids['contenedor_exterior'].pack_start(
                self.wids['menu_superior'], False)
            self.wids['contenedor_exterior'].add(contenido_anterior)
            self.wids['contenedor_exterior'].pack_end(
                self.wids['barra_estado'], False)
            self.wids['contenedor_exterior'].show()
            self.wids['barra_estado'].show()
            info_conexion = "%s://%s:xxxxxxxx@%s:%s/%s" % (config.get_tipobd(), 
                                                           config.get_user(), 
                                                           config.get_host(), 
                                                           config.get_puerto(), 
                                                           config.get_dbname())
            info_usuario = ""
            if hasattr(self, "usuario") and self.usuario != None:
                info_usuario = " usuario: %s." % (self.usuario.usuario)
            if self.__usuario != None:
                info_usuario = " __usuario: %s." % (self.__usuario.usuario)
            utils.escribir_barra_estado(self.wids['barra_estado'], "Conectado a %s.%s" % (info_conexion, info_usuario))
        except Exception, msg:
            txt = "ventana.py::__init__ -> No se pudo establecer ancho de borde, icono de ventana o barra de estado. Excepción: %s." % (msg)
            self.logger.warning(txt)
        self.objeto = objeto
        self.make_connections()
        self.make_funciones_ociosas()
        try:
            if "tpv.glade" in glade:
                tecla_fullscreen = "F10"
                # Es la de abrir el cajón en el TPV, grrrr...
                # Lo suyo sería mirar en los accelerators si ya está pillado
                # el F11, pero no sé cómo hacerlo si lo ha hecho libglade por 
                # mí y no manualmente con add_accelerator*
            else:
                tecla_fullscreen = "F11"
            def view_key_press(widget, event):
                if event.keyval == gtk.gdk.keyval_from_name("F5"):
                    if event.state == gtk.gdk.SHIFT_MASK:
                        refrescar_cache_sqlobject()
                    # print "Shift+F5"
                    self.actualizar_objeto_y_enlaces()
                    try:
                        self.actualizar_ventana()
                    except AttributeError:
                        # No tiene actualizar_ventana
                        pass
                elif event.keyval == gtk.gdk.keyval_from_name('q') \
                        and event.state & gtk.gdk.CONTROL_MASK \
                        and event.state & gtk.gdk.MOD1_MASK:
                    # print "CONTROL+ALT+q"
                    import trazabilidad
                    t = trazabilidad.Trazabilidad(self.objeto, ventana_padre = self)
                elif event.keyval == gtk.gdk.keyval_from_name(tecla_fullscreen):
                    self._full_unfull()
                else:
                    # DONE: Aquí debería hacer algo para propagar el evento, 
                    #       porque si no la barra de menú superior no 
                    #       es capaz de interceptar el Ctrl+Q que lanzaría 
                    #       el "Cerrar ventana".
                    #       Ya se propaga, el motivo de por qué no funciona 
                    #       el Ctrl+Q no es no propagar el evento.
                    #widget.propagate_key_event(event)
                    #print event.keyval, event.state, event.string
                    pass
            h_id=self.wids['ventana'].connect("key_press_event",view_key_press)
            try:
                self.handlers_id['ventana']["key_press_event"].append(h_id)
            except KeyError:
                self.handlers_id['ventana']["key_press_event"] = [h_id]
        except Exception, msg:
            txtexcp = "ventana.py::__init__ -> Mnemonics no añadidos. %s"%msg
            print txtexcp
            self.logger.warning(txtexcp)
Beispiel #18
0
obj_rules = Rules()
dgroups_app_rules = obj_rules.init_rules()
dgroups_key_binder = None

# Layouts
obj_layouts = Layouts()
layouts = obj_layouts.init_layouts(my_gaps)
floating_layout = layout.Floating()

# Widgets
whichPrimary = {
    'bifrost': [True, False, False],
    'walhall': [False, True, False]
}
my_widgets1 = Widgets(hostname, primaryMonitor = whichPrimary[hostname][0])
my_widgets2 = Widgets(hostname, primaryMonitor = whichPrimary[hostname][1])
#my_widgets3 = Widgets(hostname, primaryMonitor = whichPrimary[hostname][2])

# Screens with Widgets
screens = [
    Screen(top=bar.Bar(widgets = my_widgets1.init_widgets(),
                       opacity = 0.95, size = 22)), 
    Screen(top=bar.Bar(widgets = my_widgets2.init_widgets(),
                       opacity = 0.95, size = 22)),
    # Screen(top=bar.Bar(widgets = init_widgets_screen3(),
    #                    opacity = 0.95, size = 22)),
]

# Autostart hook
@hook.subscribe.startup_once
 def offset_handler(self, *ignore):
     """When the offset is changed, update the loaded photos."""
     for i, photo in enumerate(self.photos):
         if not i % 10:
             Widgets.redraw_interface()
         photo.calculate_timestamp(self.offset)
Beispiel #20
0
class Ventana(object):

    def refocus_enter(self):
        self.handlers_id = dict([(w, {}) for w in self.wids.keys()])
        for w in self.wids.keys():
            widget = self.wids[w]
            if isinstance(widget, gtk.ComboBoxEntry):
                widget = widget.child
            if isinstance(widget, gtk.Entry):
                h_id = widget.connect("activate", self.refocus_entry)
                try:
                    self.handlers_id[w]["activate"].append(h_id)
                except KeyError:
                    self.handlers_id[w]["activate"] = [h_id]

    def __init__(self, glade, objeto = None, usuario = None):
        """
        Constructor.
        glade es una cadena con el nombre del fichero .glade a cargar.
        objeto es el objeto principal de la ventana.
        Si usuario se recibe, se guarda en un atributo privado de la 
        clase que servirá únicamente para crear un menú superior en 
        la ventana con las opciones de menú disponibles para el usuario.
        Si el usuario es None, no se crea ningún menú.
        """
        if isinstance(usuario, int):
            usuario = pclases.Usuario.get(usuario)
        self.__usuario = usuario
        self._is_fullscreen = False
        import logging
        self.logger = logging.getLogger('GINN')
        # El fichero de log lo voy a plantar en el raíz del proyecto.
        rutalogger = os.path.join(os.path.dirname(__file__), "..", 'ginn.log')
        hdlr = logging.FileHandler(rutalogger)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        # self.logger.setLevel(logging.INFO)
        try:
            self.wids = Widgets(glade)  # Puede que venga la ruta ya y no 
                                        # haga falta combinar con os.path.join.
        except RuntimeError:
            try:
                self.wids = Widgets(os.path.join("formularios","glades",glade))
            except RuntimeError:
                try:
                    self.wids = Widgets(os.path.join("glades", glade))
                except RuntimeError:
                    try:
                        self.wids = Widgets(os.path.join(
                                        "..", "formularios", "glades", glade))
                    except RuntimeError:
                        if pclases.DEBUG and pclases.VERBOSE:
                            print "ventana.py::Ventana.__init__ -> "\
                                  "No encuentro el glade. Estoy en %s. "\
                                  "Intento cargar de nuevo desde donde "\
                                  "se supone que debería estar." % (
                                    os.path.abspath(os.path.curdir))
                        self.wids = Widgets(glade)
        self.refocus_enter()
        try:
            self.wids['ventana'].set_border_width(5)
            # TODO:Cambiar por uno correspondiente al logo de la configuración. 
            ruta_logo = os.path.join("imagenes", 'logo.xpm')
            logo_xpm = gtk.gdk.pixbuf_new_from_file(ruta_logo) 
            self.wids['ventana'].set_icon(logo_xpm)
            self.wids['barra_estado'] = gtk.Statusbar()
            label_statusbar = self.wids['barra_estado'].get_children()[0].child
            font = pango.FontDescription("Monospace oblique 7")
            label_statusbar.modify_font(font)
            label_statusbar.modify_fg(gtk.STATE_NORMAL, 
                label_statusbar.get_colormap().alloc_color("darkgray"))
            contenido_anterior = self.wids['ventana'].get_child()
            self.wids['ventana'].remove(contenido_anterior)
            self.wids['contenedor_exterior'] = gtk.VBox()
            self.wids['ventana'].add(self.wids['contenedor_exterior'])
            self.wids['menu_superior'] = self.build_menu_superior()
            self.wids['contenedor_exterior'].pack_start(
                self.wids['menu_superior'], False)
            self.wids['contenedor_exterior'].add(contenido_anterior)
            self.wids['contenedor_exterior'].pack_end(
                self.wids['barra_estado'], False)
            self.wids['contenedor_exterior'].show()
            self.wids['barra_estado'].show()
            config = ConfigConexion()
            info_conexion = "%s://%s:xxxxxxxx@%s:%s/%s" % (config.get_tipobd(), 
                                                           config.get_user(), 
                                                           config.get_host(), 
                                                           config.get_puerto(), 
                                                           config.get_dbname())
            info_usuario = ""
            if hasattr(self, "usuario") and self.__usuario != None:
                info_usuario = " usuario: %s." % (self.__usuario.usuario)
            if self.__usuario != None:
                info_usuario = " __usuario: %s." % (self.__usuario.usuario)
            ui.escribir_barra_estado(self.wids['barra_estado'], 
                                     "Conectado a %s.%s" % (info_conexion, 
                                                            info_usuario))
        except Exception, msg:
            txt = "ventana.py::__init__ -> No se pudo establecer ancho "\
                  "de borde, icono de ventana o barra de estado. "\
                  "Excepción: %s." % (msg)
            self.logger.warning(txt)
        self.objeto = objeto
        self.make_connections()
        try:
            tecla_fullscreen = "F11"
            def view_key_press(widget, event):
                if event.keyval == gtk.gdk.keyval_from_name("F5"):
                    if event.state == gtk.gdk.SHIFT_MASK:
                        refrescar_cache_sqlobject()
                    # print "Shift+F5"
                    self.actualizar_objeto_y_enlaces()
                    try:
                        self.actualizar_ventana()
                    except AttributeError:
                        # No tiene actualizar_ventana
                        pass
                elif event.keyval == gtk.gdk.keyval_from_name('q') \
                        and event.state & gtk.gdk.CONTROL_MASK \
                        and event.state & gtk.gdk.MOD1_MASK:
                    # print "CONTROL+ALT+q"
                    import trazabilidad
                    trazabilidad.Trazabilidad(self.objeto, ventana_padre = self)
                elif event.keyval == gtk.gdk.keyval_from_name(tecla_fullscreen):
                    self._full_unfull()
                elif event.keyval == gtk.gdk.keyval_from_name("Escape"):
                    widget_focusado = self.wids['ventana'].get_focus()
                    # Si estoy editando una celda no le cierro la ventana sin 
                    # avisar para que no pierda los cambios.
                    mostrar_salir = (widget_focusado 
                        and isinstance(widget_focusado, gtk.Entry)
                        and widget_focusado.parent 
                        and isinstance(widget_focusado.parent, gtk.TreeView))
                    self.salir(None, mostrar_ventana = mostrar_salir)    
                        # NAV plagiarism one more time!
                elif event.keyval == gtk.gdk.keyval_from_name('z') \
                        and event.state & gtk.gdk.CONTROL_MASK:
                    # Deshacer en todos los botones de la ventana.
                    for wname in self.wids.keys():
                        w = self.wids[wname]
                        if w.name.startswith("b_undo"):
                            w.clicked()
                else:
                    # DONE: Aquí debería hacer algo para propagar el evento, 
                    #       porque si no la barra de menú superior no 
                    #       es capaz de interceptar el Ctrl+Q que lanzaría 
                    #       el "Cerrar ventana".
                    #       Ya se propaga, el motivo de por qué no funciona 
                    #       el Ctrl+Q no es no propagar el evento.
                    #widget.propagate_key_event(event)
                    #print event.keyval, event.state, event.string
                    pass
            h_id=self.wids['ventana'].connect("key_press_event",view_key_press)
            try:
                self.handlers_id['ventana']["key_press_event"].append(h_id)
            except KeyError:
                self.handlers_id['ventana']["key_press_event"] = [h_id]
        except Exception, msg:
            txtexcp = "ventana.py::__init__ -> Mnemonics no añadidos. %s"%msg
            print txtexcp
            self.logger.warning(txtexcp)