Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/WorkPanel.py
blob: 36f6ba432c5857426c6ba9a45959efa0a59d1142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#   WorkPanel.py por:
#       Cristian García     <cristian99garcia@gmail.com>
#       Ignacio Rodriguez   <nachoel01@gmail.com>
#       Flavio Danesse      <fdanesse@gmail.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import mimetypes

import gi
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import GtkSource
from gi.repository import Pango

from Widgets import JAMediaTerminal

PATH = os.path.dirname(__file__)

class WorkPanel(Gtk.Paned):
    """
    Panel, área de trabajo.
        zona superior: Notebook + source view para archivos abiertos
        zona inferior: terminales.
    """
    
    __gtype_name__ = 'WorkPanel'
    
    __gsignals__ = {
     'new_select': (GObject.SIGNAL_RUN_FIRST,
        GObject.TYPE_NONE, (GObject.TYPE_STRING,
        GObject.TYPE_STRING))}

    def __init__(self):

        Gtk.Paned.__init__(self,
            orientation=Gtk.Orientation.VERTICAL)

        self.notebook_sourceview = Notebook_SourceView()
        self.debug_notebook = DebugNotebook()
        
        self.pack1(self.notebook_sourceview, resize = True, shrink = False)
        self.pack2(self.debug_notebook, resize = False, shrink = True)

        self.show_all()
        
        self.debug_notebook.set_size_request(-1, 170)
        
        self.notebook_sourceview.connect('new_select', self.__re_emit_new_select)

    def set_linea(self, texto):
        """
        Recibe la linea seleccionada en instrospeccion y
        y la pasa a notebook_sourceview para seleccionarla.
        """
        
        self.notebook_sourceview.set_linea(texto)
        
    def __re_emit_new_select(self, widget, nombre, texto):
        """
        Recibe nombre y contenido de archivo seleccionado
        en Notebook_SourceView y los envia BasePanel.
        """
        
        self.emit('new_select', nombre, texto)
        
    def abrir_archivo(self, archivo):
        """
        Abre un archivo.
        """
        
        self.notebook_sourceview.abrir_archivo(archivo)

class Notebook_SourceView(Gtk.Notebook):
    """
    Notebook contenedor de sourceview para
    archivos abiertos.
    """

    __gsignals__ = {
     'new_select': (GObject.SIGNAL_RUN_FIRST,
        GObject.TYPE_NONE, (GObject.TYPE_STRING,
        GObject.TYPE_STRING))}

    def __init__(self):

        Gtk.Notebook.__init__(self)

        self.show_all()

        self.abrir_archivo(False)

        self.connect('switch_page', self.__switch_page)
        
    def set_linea(self, texto):
        """
        Recibe la linea seleccionada en instrospeccion y
        y la selecciona en el sourceview activo.
        """

        scrolled = self.get_children()[self.get_current_page()]
        view = scrolled.get_children()[0]
        buffer = view.get_buffer()

        start = buffer.get_start_iter()
        end = buffer.get_end_iter()

        if start.get_offset() == buffer.get_char_count():
            start = buffer.get_start_iter()

        match = start.forward_search(texto, 0, end)

        if match:
            match_start, match_end = match

            buffer.select_range(match_start, match_end)
            view.scroll_to_iter(match_end, 0.1, 1, 1, 1)
            
    def __switch_page(self, widget, widget_child, indice):
        """
        Cuando el usuario selecciona una lengüeta en
        el notebook, se emite la señal 'new_select'.
        """
        
        view = widget_child.get_child()
        buffer = view.get_buffer()
        archivo = view.archivo
        nombre = False
        
        if archivo:
            nombre = os.path.basename(archivo)
        
        inicio, fin = buffer.get_bounds()
        
        self.emit(
            'new_select', nombre,
            buffer.get_text(inicio, fin, 0))
        
    def abrir_archivo(self, archivo):
        """
        Abre un archivo y agrega una página
        para él, con su código.
        """

        paginas = self.get_children()
        
        for pagina in paginas:
            view = pagina.get_child()
            
            if view.archivo == archivo:
                return
        
        sourceview = SourceView()
        hbox = Gtk.HBox()
        label = Gtk.Label("sin título")
        boton = Gtk.ToolButton(Gtk.STOCK_CLOSE)

        hbox.pack_start(label, False, False, 0)
        hbox.pack_start(boton, False, False, 0)

        if archivo:
            if os.path.exists(archivo):
                label.set_text(os.path.basename(archivo))

        sourceview.set_archivo(archivo)

        scroll = Gtk.ScrolledWindow()

        scroll.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC)

        scroll.add(sourceview)

        self.append_page(scroll, hbox)

        label.show()
        boton.show()
        self.show_all()

class SourceView(GtkSource.View):
    """
    Visor de código para archivos abiertos.
    """

    def __init__(self):

        GtkSource.View.__init__(self)

        self.archivo = False

        self.buffer = GtkSource.Buffer()

        self.lenguaje_manager = GtkSource.LanguageManager()
        self.lenguajes = self.lenguaje_manager.get_language_ids()

        self.lenguajes.sort()
        self.lenguajes.remove(self.lenguajes[0])

        self.lenguajes.insert(0, 'Texto Plano')

        self.set_buffer(self.buffer)
        self.set_insert_spaces_instead_of_tabs(True)
        self.set_tab_width(4)

        self.modify_font(Pango.FontDescription('Monospace'))

        completion = self.get_completion()
        completion.add_provider(AutoCompletado(self.buffer))

        self.show_all()

    def set_archivo(self, archivo):
        """
        Setea el archivo cuyo codigo debe mostrarse.
        """

        self.archivo = archivo

        if self.archivo:
            if os.path.exists(self.archivo):
                texto = open(self.archivo, 'r').read()
                nombre = os.path.basename(self.archivo)

                self.__set_lenguaje(archivo)
                self.buffer.set_text(texto)

                self.buffer.begin_not_undoable_action()
                self.buffer.end_not_undoable_action()

    def get_modified(self):
        """
        Obtiene el estado de modificación del buffer y lo devuelve
        """
        
        return self.buffer.get_modified()

    def __set_lenguaje(self, archivo):
        """
        Setea los colores del texto según tipo de archivo.
        """

        encontrado = False
        tipo = mimetypes.guess_type(archivo)[0]

        for id in self.lenguajes:
            lenguaje = self.lenguaje_manager.get_language(id)

            if lenguaje and len(lenguaje.get_mime_types()):
                mime = lenguaje.get_mime_types()[0]

                if tipo == mime:
                    self.buffer.set_highlight_syntax(True)
                    self.buffer.set_language(lenguaje)

                    if id == 'python':
                        self.set_insert_spaces_instead_of_tabs(True)
                        self.set_tab_width(4)

                    else:
                        self.set_insert_spaces_instead_of_tabs(False)
                        self.set_tab_width(8)

                    self.lenguaje = lenguaje
                    encontrado = True
                    break

        if not encontrado:
            self.set_highlight_syntax(False)
            self.buffer.set_language(None)

class AutoCompletado(GObject.Object, GtkSource.CompletionProvider):
    
    __gtype_name__ = 'AutoCompletado'

    def __init__(self, buffer):
        
        GObject.Object.__init__(self)
        
        self.buffer = buffer

    def __set_imports(self, imports):
        """
        Guarda los datos para importaciones previas,
        para calculos de autocompletado.
        """
        
        import shelve

        pathin = os.path.join("/tmp", "shelvein")

        archivo = shelve.open(pathin)
        archivo["Lista"] = imports
        archivo.close()
        
    def __get_auto_completado(self):
        """
        Devuelve la lista de opciones posibles
        para auto completar.
        """
        
        import commands

        pathin = os.path.join("/tmp", "shelvein")
        
        pathout = os.path.join(commands.getoutput(
            'python %s %s' % (
                os.path.join(PATH, "gtkintrospection.py"),
                pathin)))
        
        lista = []
        
        if os.path.exists(pathout):
            ### Obtener lista para autocompletado.
            
            import shelve
            
            archivo = shelve.open(pathout)
            lista = archivo["Lista"]
            archivo.close()
            
        return lista
        
    def do_activate_proposal(self, dato1, dato2):
        """
        Cuando se selecciona y clickea
        una posible solución.
        """
        
        pass
    
    def do_get_name(self, coso=None, coso2=None):
        """
        Devuelve el nombre del último
        módulo al que se auto completó.
        """
        
        pass

    def do_populate(self, context):
        """
        Cuando se producen cambios en el buffer.
        
        Metodología para autocompletado:
            * Importar todos los paquetes y módulos que se están
                importando en el archivo sobre el cual estamos auto completando.
            * Hacer el auto completado propiamente dicho, trabajando sobre
                la línea de código que se está editando.
        """
        
        ### Iterador de texto sobre el código actual.
        textiter = self.buffer.get_iter_at_mark(self.buffer.get_insert())# Gtk.TextIter
        
        ### indice de linea activa.
        indice_de_linea_activa = textiter.get_line()
        
        ### Texto de la linea activa.
        texto_de_linea_en_edicion = textiter.get_slice(
            self.buffer.get_iter_at_line(indice_de_linea_activa))
        
        ### Si hay un punto en la línea.
        if "." in texto_de_linea_en_edicion:
        
            ### Si el punto está en la última palabra.
            if "." in texto_de_linea_en_edicion.split()[-1]:
                
                ### Auto completado se hace sobre "."
                if texto_de_linea_en_edicion.endswith("."):
                    
                    palabras = texto_de_linea_en_edicion.split()
                    
                    if palabras:
                        ### Importar paquetes y modulos previos
                        inicio = self.buffer.get_start_iter()
                        texto = self.buffer.get_text(inicio, textiter, True)
                        lineas = texto.splitlines()
                        
                        imports = []
                        
                        for linea in lineas:
                            # FIXME: Analizar mejor los casos como ''', """, etc.
                            if "import " in linea and not linea.startswith("#") and \
                                not linea.startswith("\"") and not linea.startswith("'"):
                                    imports.append(linea)

                        ### ['import os', 'import sys', 'from os import path']
                        ### Esto es [] si auto completado se hace antes de los imports
                        
                        ### Auto completado se hace sobre la última palabra
                        palabra = palabras[-1]
                        palabra = palabra.split("(")[-1] # Caso:  class Ventana(gtk.
                        
                        pals = palabra.split(".")[:-1]
                        imports.append(pals) # ['import os', 'import sys', 'from os import path', ['gtk', 'gdk', '']]
                        
                        ### Guardar en un archivo.
                        self.__set_imports(imports)
                        
                        ### Obtener lista para autocompletado.
                        lista = self.__get_auto_completado()
                        
                        opciones = []
                        
                        for item in lista:
                            opciones.append(GtkSource.CompletionItem.new(item,
                                item, None, None))
                            
                        context.add_proposals(self, opciones, True)
                        
                else:
                    # FIXME: Se está autocompletando.
                    # Esto debe actualizar la lista de opciones disponibles,
                    # Filtrando en la lista según el texto escrito por el usuario.
                    text = texto_de_linea_en_edicion.split(".")[-1]
                    
            else:
                context.add_proposals(self, [], True)
            
        else:
            context.add_proposals(self, [], True)

class DebugNotebook(Gtk.Notebook):
    """
    Notebook para terminales y debugs.
    """
    
    def __init__(self):

        Gtk.Notebook.__init__(self)
        
        self.terminal = JAMediaTerminal()
        
        self.append_page(self.terminal, Gtk.Label('Terminal'))
        
        self.show_all()