Migrated to Python 3, implemented some changes to the Gi

This commit is contained in:
José Carlos Cuevas 2018-09-12 11:19:40 +02:00
parent 9e323703a5
commit 37abc5c09b
3 changed files with 80 additions and 67 deletions

4
.gitignore vendored
View file

@ -53,3 +53,7 @@ lib/
lib64
include/
build/
# Ropeproject ignore
.ropeproject/
.bak

View file

@ -1,10 +1,17 @@
import ez_setup, sys, shutil, os, os.path, subprocess
import ez_setup
import sys
import shutil
import os
import os.path
import subprocess
ez_setup.use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.install import install
from distutils.dir_util import copy_tree
class CustomInstall(install):
"""
We subclass the install command to add some more mojo
@ -14,20 +21,20 @@ class CustomInstall(install):
# Now we do our own magic
if sys.platform != 'win32' and sys.platform != 'darwin':
try:
print "Creating shared directory..."
os.mkdir("/usr/local/share/jsoninspector", 0755)
print("Creating shared directory...")
os.mkdir("/usr/local/share/jsoninspector", 0o755)
except:
if not os.path.exists("/usr/local/share/jsoninspector"):
print "Warning: Couldn't create /usr/local/share/jsoninspector"
print("Warning: Couldn't create /usr/local/share/jsoninspector")
# Copy the translations
try:
print "Installing translations..."
print("Installing translations...")
copy_tree('locale/po/', '/usr/share/locale/')
except:
print "Warning: error copying translation files."
print("Warning: error copying translation files.")
# Generate the icons
try:
@ -37,67 +44,68 @@ class CustomInstall(install):
result = 1
if result != 0:
print "Warning: Error generating icons"
print("Warning: Error generating icons")
# Copy the icons
print "Installing application icons..."
for icon_size in ['{sz}x{sz}'.format(sz = x) for x in ['16', '22','24', '32', '36', '48', '64', '72', '96', '128', '192']]:
print("Installing application icons...")
for icon_size in ['{sz}x{sz}'.format(sz=x) for x in ['16', '22', '24', '32', '36', '48', '64', '72', '96', '128', '192']]:
try:
shutil.copyfile('res/jsoninspector' + icon_size + ".png",
shutil.copyfile('res/jsoninspector' + icon_size + ".png",
'/usr/share/icons/hicolor/' + icon_size + "/apps/jsoninspector.png")
except:
print "Warning: error copying icon {size}.".format(size = icon_size)
print("Warning: error copying icon {size}.".format(size=icon_size))
try:
shutil.copyfile('res/jsoninspector48x48.png', '/usr/share/pixmaps/jsoninspector.png')
except:
print "Warning: error copying icon to pixmaps directory."
print("Warning: error copying icon to pixmaps directory.")
try:
shutil.copyfile('res/jsoninspector.svg' ,'/usr/share/icons/hicolor/scalable/apps/jsoninspector.svg')
shutil.copyfile('res/jsoninspector.svg', '/usr/share/icons/hicolor/scalable/apps/jsoninspector.svg')
except:
print "Warning: error copying svg to scalable."
print("Warning: error copying svg to scalable.")
print "Updating icon cache..."
print("Updating icon cache...")
try:
result = subprocess.call(['/usr/bin/gtk-update-icon-cache /usr/share/icons/hicolor/'])
except:
result = 1
if result != 0:
print "Warning: Error updating hicolor icon cache."
print("Warning: Error updating hicolor icon cache.")
try:
print "Installing glade file..."
print("Installing glade file...")
shutil.copyfile('res/jsoninspector.glade', '/usr/local/share/jsoninspector/jsoninspector.glade')
except:
print "Warning: error copying .glade file."
print("Warning: error copying .glade file.")
try:
print "Installing desktop entry..."
print("Installing desktop entry...")
shutil.copyfile('res/jsoninspector.desktop', '/usr/share/applications/jsoninspector.desktop')
except:
print "Warning: error copying .desktop entry."
print("Warning: error copying .desktop entry.")
setup(
name = "Jsoninspector",
version = "2.0",
packages = find_packages('src', exclude = ['ez_setup']),
entry_points = { 'gui_scripts' : [ 'jsoninspector = jsoninspector:main_start' ] },
package_dir = { '' : 'src' },
name="Jsoninspector",
version="2.0",
packages=find_packages('src', exclude=['ez_setup']),
entry_points={'gui_scripts': ['jsoninspector=jsoninspector:main_start']},
package_dir={'': 'src'},
# metadata for upload to PyPI
author = "Jose Carlos Cuevas",
author_email = "reset.reboot@gmail.com",
description = "JSON Inspector is a simple application to study JSON code",
license = "GPLv3",
keywords = "json inspect gtk gnome",
url = "https://github.com/resetreboot/jsoninspector", # project home page, if any
cmdclass = { 'install' : CustomInstall }
author="Jose Carlos Cuevas",
author_email="reset.reboot@gmail.com",
description="JSON Inspector is a simple application to study JSON code",
license="GPLv3",
keywords="json inspect gtk gnome",
url="https://eonbeta.servegame.com/git/resetreboot/jsoninspector", # project home page, if any
cmdclass={'install': CustomInstall}
)

View file

@ -1,9 +1,13 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
import json, sys, os.path
import json
import sys
import os.path
# Internationalization support
import gettext
@ -11,7 +15,7 @@ import locale
APP = "jsoninspector"
if os.path.exists('../locale/po') and os.path.exists('../../res'):
if os.path.exists('../../locale/po') and os.path.exists('../../res'):
# We're in the development tree
DIR = "../../locale/po/"
RESOURCES = "../../res/"
@ -39,15 +43,15 @@ class MainWindowMethods(Gtk.Application):
Main Application object with the main window signals
"""
def __init__(self, logic):
Gtk.Application.__init__(self, application_id = "apps.gnome.jsoninspector",
flags = Gio.ApplicationFlags.FLAGS_NONE)
Gtk.Application.__init__(self, application_id="apps.gnome.jsoninspector",
flags=Gio.ApplicationFlags.FLAGS_NONE)
# We store the reference to the app logic
self.logicObj = logic
self.connect("activate", self.on_app_start)
def on_app_start(self, data = None):
def on_app_start(self, data=None):
"""
Loads the MainWindow widgets, shows it up and starts the main loop
"""
@ -100,14 +104,14 @@ class MainWindowMethods(Gtk.Application):
# We update the statusbar accordingly to what has happened
if self.logicObj.loadjson(filename):
label.set_text(filename)
treeStore = self.builder.get_object("treestore1")
treeStore.clear()
self.logicObj.loadTree(treeStore)
else:
label.set_text(_("No JSON loaded."))
# We finish the dialog
@ -154,8 +158,8 @@ class MainWindowMethods(Gtk.Application):
treestore.clear()
if self.logicObj.loadJSONText(jsonText):
status_label = self.builder.get_object("StatusLabel")
status_label = self.builder.get_object("StatusLabel")
status_label.set_text(_("Loaded from the clipboard."))
self.logicObj.loadTree(treestore)
@ -186,10 +190,10 @@ class MainWindowMethods(Gtk.Application):
"""
pass
def onAboutDialogClose(self, widget, event = None):
def onAboutDialogClose(self, widget, event=None):
pass
def onAboutDialogDeleteEvent(self, widget, event = None):
def onAboutDialogDeleteEvent(self, widget, event=None):
pass
@ -209,7 +213,7 @@ class LogicObject(object):
try:
self.json = json.loads(f.read())
except ValueError:
print _("Not valid JSON!\n")
print(_("Not valid JSON!\n"))
self.json = None
f.close()
@ -225,9 +229,9 @@ class LogicObject(object):
try:
self.json = json.loads(text)
except ValueError:
print _("Not valid JSON")
print(_("Not valid JSON"))
self.json = None
return False
return True
@ -236,23 +240,22 @@ class LogicObject(object):
"""
Carga el JSON en el tree store para mostrarlo
"""
for key_val in self.json.keys():
for key_val in list(self.json.keys()):
self.process_node(treestore, self.json[key_val], key_val)
def _loadTreeRec(self, treestore, elems, parent_node):
"""
Adición recursiva de elementos al árbol
"""
for key_val in elems.keys():
for key_val in list(elems.keys()):
self.process_node(treestore, elems[key_val], key_val, parent_node)
def process_node(self, treestore, node, node_key, parent_node = None):
def process_node(self, treestore, node, node_key, parent_node=None):
# Si el elemento contiene un diccionario
if type(node) is dict:
# Añadimos el nodo, y obtenemos la referencia
new_node = treestore.append(parent_node, [unicode(node_key), u"", u""])
new_node = treestore.append(parent_node, [str(node_key), "", ""])
# De manera recursiva, entramos en el diccionario y obtenemos
# los nodos, añadidos como hijos de este
self._loadTreeRec(treestore, node, new_node)
@ -260,20 +263,20 @@ class LogicObject(object):
elif type(node) is list:
count = 0
# Añadimos el nodo, y obtenemos la referencia
new_node = treestore.append(parent_node,
[unicode(node_key),
new_node = treestore.append(parent_node,
[str(node_key),
"", ""])
for elem in node:
if type(elem) is dict:
another_node = treestore.append(new_node,
[unicode(node_key) + u"[" + unicode(count) + u"]",
"", unicode(type(elem))])
[str(node_key) + "[" + str(count) + "]",
"", str(type(elem))])
self._loadTreeRec(treestore, elem, another_node)
else:
treestore.append(new_node, [unicode(node_key) + u"[" + unicode(count) + u"]",
unicode(elem),
unicode(type(elem))])
treestore.append(new_node, [str(node_key) + "[" + str(count) + "]",
str(elem),
str(type(elem))])
count += 1
@ -281,16 +284,14 @@ class LogicObject(object):
# Tenemos un nodo hoja, obtenemos el valor y el tipo y lo
# añadimos
treestore.append(parent_node, [unicode(node_key),
unicode(node),
unicode(type(node))])
treestore.append(parent_node, [str(node_key),
str(node),
str(type(node))])
# Main procedure
if __name__ == "__main__":
logicObject = LogicObject()
mainWindow = MainWindowMethods(logicObject)