Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Making ninja python3 compatible.

Adding docstring to highlighter
  • Loading branch information...
commit cc69778fbc5e15f45efd36c7b15c8c3d867f4a0e 1 parent 5d40e09
@diegosarmentero diegosarmentero authored
Showing with 478 additions and 375 deletions.
  1. +0 −10 ninja-ide.py
  2. +13 −0 ninja_ide/__init__.py
  3. +5 −5 ninja_ide/core/cliparser.py
  4. +4 −4 ninja_ide/core/file_manager.py
  5. +15 −12 ninja_ide/core/filesystem_notifications/__init__.py
  6. +1 −1  ninja_ide/core/filesystem_notifications/darwin.py
  7. +25 −17 ninja_ide/core/plugin_manager.py
  8. +1 −1  ninja_ide/core/plugin_services.py
  9. +59 −71 ninja_ide/core/settings.py
  10. +2 −2 ninja_ide/dependencies/pep8mod.py
  11. +23 −18 ninja_ide/dependencies/pyflakes_mod/checker.py
  12. +2 −2 ninja_ide/dependencies/pyflakes_mod/scripts/pyflakes.py
  13. +8 −9 ninja_ide/gui/actions.py
  14. +6 −8 ninja_ide/gui/central_widget.py
  15. +2 −2 ninja_ide/gui/dialogs/about_ninja.py
  16. +12 −7 ninja_ide/gui/dialogs/language_manager.py
  17. +12 −11 ninja_ide/gui/dialogs/plugins_manager.py
  18. +7 −7 ninja_ide/gui/dialogs/preferences.py
  19. +12 −7 ninja_ide/gui/dialogs/themes_manager.py
  20. +10 −5 ninja_ide/gui/editor/editor.py
  21. +11 −3 ninja_ide/gui/editor/errors_checker.py
  22. +42 −2 ninja_ide/gui/editor/highlighter.py
  23. +4 −2 ninja_ide/gui/editor/pep8_checker.py
  24. +2 −2 ninja_ide/gui/explorer/errors_lists.py
  25. +7 −7 ninja_ide/gui/explorer/explorer_container.py
  26. +12 −12 ninja_ide/gui/explorer/tree_projects_widget.py
  27. +37 −22 ninja_ide/gui/ide.py
  28. +7 −6 ninja_ide/gui/main_panel/browser_widget.py
  29. +17 −18 ninja_ide/gui/main_panel/main_container.py
  30. +12 −11 ninja_ide/gui/main_panel/recent_project_item.py
  31. +6 −6 ninja_ide/gui/main_panel/tab_widget.py
  32. +1 −1  ninja_ide/gui/menus/lib/tetrismodel.py
  33. +6 −5 ninja_ide/gui/misc/console_widget.py
  34. +10 −6 ninja_ide/gui/misc/find_in_files.py
  35. +3 −3 ninja_ide/gui/misc/plugin_preferences.py
  36. +3 −2 ninja_ide/gui/misc/run_widget.py
  37. +2 −2 ninja_ide/gui/misc/shortcut_manager.py
  38. +2 −2 ninja_ide/gui/status_bar.py
  39. +1 −2  ninja_ide/gui/updates.py
  40. +1 −1  ninja_ide/resources.py
  41. +2 −2 ninja_ide/tools/completion/analyzer.py
  42. +8 −3 ninja_ide/tools/completion/code_completion.py
  43. +7 −4 ninja_ide/tools/completion/completer.py
  44. +2 −1  ninja_ide/tools/completion/completer_widget.py
  45. +4 −3 ninja_ide/tools/completion/completion_daemon.py
  46. +5 −5 ninja_ide/tools/completion/model.py
  47. +5 −5 ninja_ide/tools/json_manager.py
  48. +36 −34 ninja_ide/tools/locator.py
  49. +3 −3 ninja_ide/tools/ui_tools.py
  50. +1 −1  setup.py
View
10 ninja-ide.py
@@ -23,16 +23,6 @@
from __future__ import absolute_import
-###############################################################################
-# SET PYQT API 2
-###############################################################################
-
-import sip
-API_NAMES = ["QDate", "QDateTime", "QString", "QTime", "QUrl", "QTextStream"]
-API_VERSION = 2
-for name in API_NAMES:
- sip.setapi(name, API_VERSION)
-
import ninja_ide
View
13 ninja_ide/__init__.py
@@ -40,6 +40,19 @@
and more enjoyable.
"""
+
+###############################################################################
+# SET PYQT API 2
+###############################################################################
+
+import sip
+API_NAMES = ["QDate", "QDateTime", "QString", "QTime", "QUrl", "QTextStream",
+ "QVariant"]
+API_VERSION = 2
+for name in API_NAMES:
+ sip.setapi(name, API_VERSION)
+
+
###############################################################################
# START
###############################################################################
View
10 ninja_ide/core/cliparser.py
@@ -39,16 +39,16 @@ def _get_parser():
parser = argparse.ArgumentParser(description=usage, epilog=epilog)
- parser.add_argument('file', metavar='file', type=unicode,
+ parser.add_argument('file', metavar='file', type=str,
nargs='*', help='A file/s to edit', default=[])
- parser.add_argument('-f', '--files', metavar='file', type=unicode,
+ parser.add_argument('-f', '--files', metavar='file', type=str,
nargs='+', help='A file/s to edit', default=[])
parser.add_argument('-l', '--lineno', metavar='lineno', type=int,
nargs='+', help='Line number for the files to open', default=[])
- parser.add_argument('-p', '--project', metavar='project', type=unicode,
+ parser.add_argument('-p', '--project', metavar='project', type=str,
nargs='+', help='A project/s to edit', default=[])
parser.add_argument('--plugin',
- metavar='plugin', type=unicode,
+ metavar='plugin', type=str,
nargs='+', help='A plugin to load', default=[])
parser.add_argument('--loglevel', help="Level to use for logging, "
"one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'",
@@ -154,7 +154,7 @@ def parse():
log_level = opts.loglevel
log_file = opts.logfile
- except Exception, reason:
+ except Exception as reason:
print("Args couldn't be parsed.")
print(reason)
return (filenames, projects_path, extra_plugins, linenos, log_level,
View
8 ninja_ide/core/file_manager.py
@@ -116,8 +116,8 @@ def _search_coding_line(txt):
"""Search a pattern like this: # -*- coding: utf-8 -*-."""
coding_pattern = "coding[:=]\s*([-\w.]+)"
pat_coding = re.search(coding_pattern, txt)
- if pat_coding and unicode(pat_coding.groups()[0]) != 'None':
- return unicode(pat_coding.groups()[0])
+ if pat_coding and pat_coding.groups()[0] != 'None':
+ return pat_coding.groups()[0]
return None
@@ -147,8 +147,8 @@ def read_file_content(fileName):
content = f.read()
encoding = get_file_encoding(content)
content.decode(encoding)
- except IOError, reason:
- raise NinjaIOException(unicode(reason))
+ except IOError as reason:
+ raise NinjaIOException(reason)
return content
View
27 ninja_ide/core/filesystem_notifications/__init__.py
@@ -19,18 +19,21 @@
import sys
-
-if sys.platform == 'win32':
- from ninja_ide.core.filesystem_notifications import windows
- source = windows
-elif sys.platform == 'darwin':
- from ninja_ide.core.filesystem_notifications import darwin
- source = darwin
-elif sys.platform.startswith("linux"):
- from ninja_ide.core.filesystem_notifications import linux
- source = linux
-else:
- #Aything we do not have a clue how to handle
+try:
+ if sys.platform == 'win32':
+ from ninja_ide.core.filesystem_notifications import windows
+ source = windows
+ elif sys.platform == 'darwin':
+ from ninja_ide.core.filesystem_notifications import darwin
+ source = darwin
+ elif sys.platform.startswith("linux"):
+ from ninja_ide.core.filesystem_notifications import linux
+ source = linux
+ else:
+ #Aything we do not have a clue how to handle
+ from ninja_ide.core.filesystem_notifications import openbsd
+ source = openbsd
+except:
from ninja_ide.core.filesystem_notifications import openbsd
source = openbsd
View
2  ninja_ide/core/filesystem_notifications/darwin.py
@@ -69,7 +69,7 @@ def add_watch(self, path):
#self.watching_paths[path] = stream
#if not self.observer.is_alive():
#self.observer.start()
- #except Exception, reason:
+ #except Exception as reason:
#print reason
#logger.debug("Path could not be added: %r" % path)
View
42 ninja_ide/core/plugin_manager.py
@@ -15,19 +15,21 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
-from __future__ import absolute_import
+from __future__ import unicode_literals
import os
import sys
import copy
-import urllib2
+import json
import zipfile
import traceback
#lint:disable
try:
- import json
+ from urllib.request import urlopen
+ from urllib.error import URLError
except ImportError:
- import simplejson as json
+ from urllib2 import urlopen
+ from urllib2 import URLError
#lint:enable
from ninja_ide import resources
@@ -36,6 +38,12 @@
logger = NinjaLogger('ninja_ide.core.plugin_manager')
REQUIREMENTS = 'requirements.txt'
COMMAND_FOR_PIP_INSTALL = 'pip install -r %s'
+try:
+ # For Python2
+ str = unicode # lint:ok
+except NameError:
+ # We are in Python3
+ pass
class ServiceLocator(object):
@@ -51,7 +59,7 @@ def get_service(self, name):
return self.__services.get(name)
def get_availables_services(self):
- return self.__services.keys()
+ return list(self.__services.keys())
'''
@@ -135,7 +143,7 @@ def __init__(self, plugins_dir, service_locator):
def __create_list(self, obj):
if isinstance(obj, (list, tuple)):
return obj
- elif isinstance(obj, basestring):
+ elif isinstance(obj, str):
return [obj]
def add_plugin_dir(self, plugin_dir):
@@ -156,7 +164,7 @@ def get_active_plugins(self):
'''
Return a list the instances
'''
- return [plugin[0] for plugin in self._active_plugins.values()]
+ return [plugin[0] for plugin in list(self._active_plugins.values())]
def __getitem__(self, plugin_name):
'''
@@ -213,7 +221,7 @@ def __len__(self):
'''
return len(self._found_plugins)
- def __nonzero__(self):
+ def __bool__(self):
'''
Magic method to indicate that any
instance must pass the if conditional
@@ -273,7 +281,7 @@ def _load_module(self, module, klassname, metadata, dir_name):
plugin_instance = klass(self._service_locator, metadata=metadata)
#return the plugin instance
return plugin_instance
- except(ImportError, AttributeError), reason:
+ except(ImportError, AttributeError) as reason:
raise PluginManagerException('Error loading "%s": %s' %
(module, reason))
finally:
@@ -284,7 +292,7 @@ def load(self, plugin_name, dir_name):
global PLUGIN_EXTENSION
if plugin_name in self._active_plugins:
return
- for dir_name, plugin_list in self._plugins_by_dir.iteritems():
+ for dir_name, plugin_list in self._plugins_by_dir.items():
if plugin_name in plugin_list:
ext = PLUGIN_EXTENSION
plugin_filename = os.path.join(dir_name, plugin_name)
@@ -307,7 +315,7 @@ def load(self, plugin_name, dir_name):
#tuple (instance, metadata)
plugin_metadata = (plugin_instance, plugin_structure)
self._active_plugins[plugin_name] = plugin_metadata
- except (PluginManagerException, Exception), reason:
+ except (PluginManagerException, Exception) as reason:
logger.error("Not instanciated (%s): %s", plugin_name,
reason)
#remove the plugin because has errors
@@ -321,7 +329,7 @@ def load(self, plugin_name, dir_name):
plugin_name)
def load_all(self):
- for dir, pl in self._plugins_by_dir.iteritems():
+ for dir, pl in self._plugins_by_dir.items():
#Copy the list because may be we REMOVE item while iterate!
found_plugins_aux = copy.copy(pl)
for plugin_name in found_plugins_aux:
@@ -339,7 +347,7 @@ def unload(self, plugin_name):
#call a special method *finish* in the plugin!
plugin_object.finish()
del self._active_plugins[plugin_name]
- except Exception, reason:
+ except Exception as reason:
logger.error("Finishing plugin (%s): %s", plugin_name, reason)
else:
logger.info("Successfuly finished (%s)", plugin_name)
@@ -375,10 +383,10 @@ def _availables_plugins(url):
Return the availables plugins from an url in NINJA-IDE web page
"""
try:
- descriptor = urllib2.urlopen(url)
+ descriptor = urlopen(url)
plugins = json.load(descriptor)
return plugins
- except urllib2.URLError:
+ except URLError:
return {}
@@ -426,7 +434,7 @@ def download_plugin(file_):
plugins_installed_before = set(__get_all_plugin_descriptors())
#download the plugin
fileName = os.path.join(resources.PLUGINS, os.path.basename(file_))
- content = urllib2.urlopen(file_)
+ content = urlopen(file_)
f = open(fileName, 'wb')
f.write(content.read())
f.close()
@@ -527,7 +535,7 @@ def uninstall_plugin(plug):
for root, dirs, files in os.walk(pluginDir):
pluginFiles = [os.path.join(root, f) for f in files]
#remove all files
- map(os.remove, pluginFiles)
+ list(map(os.remove, pluginFiles))
#collect subfolders
folders += [os.path.join(root, d) for d in dirs]
folders.reverse()
View
2  ninja_ide/core/plugin_services.py
@@ -257,7 +257,7 @@ def _fileSaved(self, fileName):
"""
Signal emitted after save a file
"""
- fileName = unicode(fileName.split(":")[-1]).strip()
+ fileName = fileName.split(":")[-1].strip()
self.fileSaved.emit(fileName)
def _currentTabChanged(self, fileName):
View
130 ninja_ide/core/settings.py
@@ -307,148 +307,136 @@ def load_settings():
global MINIMAP_MIN_OPACITY
global SIZE_PROPORTION
#General
- HIDE_TOOLBAR = qsettings.value("window/hide_toolbar", False).toBool()
- TOOLBAR_AREA = qsettings.value(
- 'preferences/general/toolbarArea', 1).toInt()[0]
- LANGUAGE = qsettings.value(
- 'preferences/interface/language', '').toString()
+ HIDE_TOOLBAR = qsettings.value("window/hide_toolbar", 'false') == 'true'
+ TOOLBAR_AREA = int(qsettings.value('preferences/general/toolbarArea', 1))
+ LANGUAGE = qsettings.value('preferences/interface/language', '')
SHOW_START_PAGE = qsettings.value(
- 'preferences/general/showStartPage', True).toBool()
+ 'preferences/general/showStartPage', 'true') == 'true'
CONFIRM_EXIT = qsettings.value('preferences/general/confirmExit',
- True).toBool()
- UI_LAYOUT = qsettings.value('preferences/interface/uiLayout',
- 0).toInt()[0]
+ 'true') == 'true'
+ UI_LAYOUT = int(qsettings.value('preferences/interface/uiLayout', 0))
NOTIFY_UPDATES = qsettings.value(
- 'preferences/general/notifyUpdates', True).toBool()
+ 'preferences/general/notifyUpdates', 'true') == 'true'
PYTHON_PATH = qsettings.value('preferences/execution/pythonPath',
- 'python').toString()
+ 'python')
NINJA_SKIN = qsettings.value('preferences/theme/skin',
- 'Default').toString()
- profileDict = qsettings.value('ide/profiles', {}).toMap()
+ 'Default')
+ profileDict = dict(qsettings.value('ide/profiles', {}))
for key in profileDict:
- profile_list = list(profileDict[key].toList())
+ profile_list = list(profileDict[key])
files = []
if profile_list:
files = [item
- for item in profile_list[0].toList()]
+ for item in list(profile_list[0])]
tempFiles = []
for file_ in files:
- fileData = file_.toList()
+ fileData = list(file_)
if len(fileData) > 0:
- tempFiles.append([fileData[0].toString(),
- fileData[1].toInt()[0]])
+ tempFiles.append([fileData[0], int(fileData[1])])
files = tempFiles
projects = []
if len(profile_list) > 1:
- projects = [item.toString() for item in profile_list[1].toList()]
+ projects = [item for item in list(profile_list[1])]
PROFILES[key] = [files, projects]
- toolbar_items = [str(item.toString()) for item in qsettings.value(
- 'preferences/interface/toolbar', []).toList()]
+ toolbar_items = [item for item in list(qsettings.value(
+ 'preferences/interface/toolbar', []))]
if toolbar_items:
TOOLBAR_ITEMS = toolbar_items
#EXECUTION OPTIONS
EXECUTION_OPTIONS = qsettings.value(
- 'preferences/execution/executionOptions', '').toString()
- extensions = [item.toString() for item in qsettings.value(
- 'preferences/general/supportedExtensions', []).toList()]
+ 'preferences/execution/executionOptions', '')
+ extensions = [item for item in list(qsettings.value(
+ 'preferences/general/supportedExtensions', []))]
if extensions:
SUPPORTED_EXTENSIONS = extensions
WORKSPACE = qsettings.value(
- 'preferences/general/workspace', "").toString()
+ 'preferences/general/workspace', "")
#Editor
SHOW_MINIMAP = qsettings.value(
- 'preferences/editor/minimapShow', False).toBool()
- MINIMAP_MAX_OPACITY = qsettings.value(
- 'preferences/editor/minimapMaxOpacity', 0.8).toFloat()[0]
- MINIMAP_MIN_OPACITY = qsettings.value(
- 'preferences/editor/minimapMinOpacity', 0.1).toFloat()[0]
- SIZE_PROPORTION = qsettings.value(
- 'preferences/editor/minimapSizeProportion', 0.17).toFloat()[0]
- INDENT = qsettings.value('preferences/editor/indent',
- 4).toInt()[0]
- MARGIN_LINE = qsettings.value('preferences/editor/marginLine',
- 80).toInt()[0]
+ 'preferences/editor/minimapShow', 'false') == 'true'
+ MINIMAP_MAX_OPACITY = float(qsettings.value(
+ 'preferences/editor/minimapMaxOpacity', 0.8))
+ MINIMAP_MIN_OPACITY = float(qsettings.value(
+ 'preferences/editor/minimapMinOpacity', 0.1))
+ SIZE_PROPORTION = float(qsettings.value(
+ 'preferences/editor/minimapSizeProportion', 0.17))
+ INDENT = int(qsettings.value('preferences/editor/indent', 4))
+ MARGIN_LINE = int(qsettings.value('preferences/editor/marginLine', 80))
pep8mod.MAX_LINE_LENGTH = MARGIN_LINE
REMOVE_TRAILING_SPACES = qsettings.value(
- 'preferences/editor/removeTrailingSpaces', True).toBool()
+ 'preferences/editor/removeTrailingSpaces', 'true') == 'true'
SHOW_TABS_AND_SPACES = qsettings.value(
- 'preferences/editor/showTabsAndSpaces', True).toBool()
- USE_TABS = qsettings.value(
- 'preferences/editor/useTabs', False).toBool()
+ 'preferences/editor/showTabsAndSpaces', 'true') == 'true'
+ USE_TABS = qsettings.value('preferences/editor/useTabs', 'false') == 'true'
if USE_TABS:
pep8mod.options.ignore.append("W191")
pep8mod.refresh_checks()
ALLOW_WORD_WRAP = qsettings.value(
- 'preferences/editor/allowWordWrap', False).toBool()
+ 'preferences/editor/allowWordWrap', 'false') == 'true'
COMPLETE_DECLARATIONS = qsettings.value(
- 'preferences/editor/completeDeclarations', True).toBool()
+ 'preferences/editor/completeDeclarations', 'true') == 'true'
HIGHLIGHT_WHOLE_LINE = qsettings.value(
- 'preferences/editor/highlightWholeLine', True).toBool()
+ 'preferences/editor/highlightWholeLine', 'true') == 'true'
font_family = qsettings.value(
- 'preferences/editor/fontFamily', "").toString()
+ 'preferences/editor/fontFamily', "")
if font_family:
FONT_FAMILY = font_family
- font_size = qsettings.value('preferences/editor/fontSize',
- 0).toInt()[0]
+ font_size = int(qsettings.value('preferences/editor/fontSize', 0))
if font_size != 0:
FONT_SIZE = font_size
SHOW_MARGIN_LINE = qsettings.value(
- 'preferences/editor/showMarginLine', True).toBool()
+ 'preferences/editor/showMarginLine', 'true') == 'true'
FIND_ERRORS = qsettings.value('preferences/editor/errors',
- True).toBool()
+ 'true') == 'true'
ERRORS_HIGHLIGHT_LINE = qsettings.value(
- 'preferences/editor/errorsInLine', True).toBool()
+ 'preferences/editor/errorsInLine', 'true') == 'true'
CHECK_STYLE = qsettings.value('preferences/editor/checkStyle',
- True).toBool()
+ 'true') == 'true'
CHECK_HIGHLIGHT_LINE = qsettings.value(
- 'preferences/editor/checkStyleInline', True).toBool()
+ 'preferences/editor/checkStyleInline', 'true') == 'true'
CODE_COMPLETION = qsettings.value(
- 'preferences/editor/codeCompletion', True).toBool()
+ 'preferences/editor/codeCompletion', 'true') == 'true'
CENTER_ON_SCROLL = qsettings.value(
- 'preferences/editor/centerOnScroll', True).toBool()
+ 'preferences/editor/centerOnScroll', 'true') == 'true'
parentheses = qsettings.value('preferences/editor/parentheses',
- True).toBool()
+ 'true') == 'true'
if not parentheses:
del BRACES['(']
- brackets = qsettings.value('preferences/editor/brackets',
- True).toBool()
+ brackets = qsettings.value('preferences/editor/brackets', 'true') == 'true'
if not brackets:
del BRACES['[']
- keys = qsettings.value('preferences/editor/keys',
- True).toBool()
+ keys = qsettings.value('preferences/editor/keys', 'true') == 'true'
if not keys:
del BRACES['{']
simpleQuotes = qsettings.value('preferences/editor/simpleQuotes',
- True).toBool()
+ 'true') == 'true'
if not simpleQuotes:
del QUOTES["'"]
doubleQuotes = qsettings.value('preferences/editor/doubleQuotes',
- True).toBool()
+ 'true') == 'true'
if not doubleQuotes:
del QUOTES['"']
#Projects
SHOW_PROJECT_EXPLORER = qsettings.value(
- 'preferences/interface/showProjectExplorer', True).toBool()
+ 'preferences/interface/showProjectExplorer', 'true') == 'true'
SHOW_SYMBOLS_LIST = qsettings.value(
- 'preferences/interface/showSymbolsList', True).toBool()
+ 'preferences/interface/showSymbolsList', 'true') == 'true'
SHOW_WEB_INSPECTOR = qsettings.value(
- 'preferences/interface/showWebInspector', False).toBool()
+ 'preferences/interface/showWebInspector', 'false') == 'true'
SHOW_ERRORS_LIST = qsettings.value(
- 'preferences/interface/showErrorsList', False).toBool()
+ 'preferences/interface/showErrorsList', 'false') == 'true'
#Bookmarks and Breakpoints
- bookmarks = qsettings.value('preferences/editor/bookmarks', {}).toMap()
+ bookmarks = dict(qsettings.value('preferences/editor/bookmarks', {}))
for key in bookmarks:
if key:
- BOOKMARKS[key] = [
- i.toInt()[0] for i in bookmarks[key].toList()]
- breakpoints = qsettings.value('preferences/editor/breakpoints', {}).toMap()
+ BOOKMARKS[key] = [int(i) for i in list(bookmarks[key])]
+ breakpoints = dict(qsettings.value('preferences/editor/breakpoints', {}))
for key in breakpoints:
if key:
- BREAKPOINTS[key] = [
- i.toInt()[0] for i in breakpoints[key].toList()]
+ BREAKPOINTS[key] = [int(i) for i in list(breakpoints[key])]
# Checkers
CHECK_FOR_DOCSTRINGS = qsettings.value(
- 'preferences/editor/checkForDocstrings', False).toBool()
+ 'preferences/editor/checkForDocstrings', 'false') == 'true'
# Import introspection here, it not needed in the namespace of
# the rest of the file.
from ninja_ide.tools import introspection
View
4 ninja_ide/dependencies/pep8mod.py
@@ -1330,8 +1330,8 @@ def run_check(fileName, source):
try:
lines = [line + '\n' for line in source.splitlines()]
return Checker(fileName, lines).check_all()
- except Exception, reason:
+ except Exception as reason:
print('pep8mod couldn\'t parse file: {0}'.format(fileName))
- print reason
+ print(reason)
raise
return []
View
41 ninja_ide/dependencies/pyflakes_mod/checker.py
@@ -2,15 +2,20 @@
# (c) 2005-2008 Divmod, Inc.
# See LICENSE file for details
-import __builtin__
import os.path
from compiler import ast
+#lint:disable
+try:
+ import builtins
+except ImportError:
+ import __builtin__ as builtins
+#lint:enable
from ninja_ide.core import settings
from ninja_ide.dependencies.pyflakes_mod import messages
-PYTHON_BUILTINS = dir(__builtin__)
+PYTHON_BUILTINS = dir(builtins)
class Binding(object):
@@ -34,10 +39,11 @@ def __str__(self):
return self.name
def __repr__(self):
- return '<%s object %r from line %r at 0x%x>' % (self.__class__.__name__,
- self.name,
- self.source.lineno,
- id(self))
+ return '<%s object %r from line %r at 0x%x>' % (
+ self.__class__.__name__,
+ self.name,
+ self.source.lineno,
+ id(self))
class UnBinding(Binding):
@@ -134,7 +140,7 @@ class ModuleScope(Scope):
pass
-# Globally defined names which are not attributes of the __builtin__ module.
+# Globally defined names which are not attributes of the builtins module.
_MAGIC_GLOBALS = ['__file__', '__builtins__']
@@ -216,22 +222,22 @@ def check_dead_scopes(self):
for scope in self.dead_scopes:
export = isinstance(scope.get('__all__'), ExportBinding)
if export:
- all = scope['__all__'].names()
+ alls = scope['__all__'].names()
if os.path.split(self.filename)[1] != '__init__.py':
# Look for possible mistakes in the export list
- undefined = set(all) - set(scope)
+ undefined = set(alls) - set(scope)
for name in undefined:
self.report(
messages.UndefinedExport,
scope['__all__'].source.lineno,
name)
else:
- all = []
+ alls = []
# Look for imported names that aren't used.
for importation in scope.itervalues():
if isinstance(importation, Importation):
- if not importation.used and importation.name not in all:
+ if not importation.used and importation.name not in alls:
self.report(
messages.UnusedImport,
importation.source.lineno,
@@ -299,7 +305,7 @@ def addBinding(self, lineno, value, reportRedef=True):
existing = scope.get(value.name)
if (isinstance(existing, Importation)
and not existing.used
- and (not isinstance(value, Importation) or \
+ and (not isinstance(value, Importation) or
value.fullName == existing.fullName)
and reportRedef):
@@ -315,7 +321,7 @@ def addBinding(self, lineno, value, reportRedef=True):
self.scope[value.name] = value
if settings.CHECK_FOR_DOCSTRINGS and \
- ((value.__class__ is FunctionDefinition) or \
+ ((value.__class__ is FunctionDefinition) or
(value.source.__class__.__name__.upper() == "CLASS")):
doc = value.source.doc
if doc is None:
@@ -358,17 +364,17 @@ def FOR(self, node):
"""
Process bindings for loop variables.
"""
- vars = []
+ variables = []
def collectLoopVars(n):
if hasattr(n, 'name'):
- vars.append(n.name)
+ variables.append(n.name)
else:
for c in n.getChildNodes():
collectLoopVars(c)
collectLoopVars(node.assign)
- for varn in vars:
+ for varn in variables:
if (isinstance(self.scope.get(varn), Importation)
# unused ones will get an unused import warning
and self.scope[varn].used):
@@ -409,7 +415,7 @@ def NAME(self, node):
try:
self.scopeStack[0][node.name].used = (self.scope, node.lineno)
except KeyError:
- if ((not hasattr(__builtin__, node.name))
+ if ((not hasattr(builtins, node.name))
and node.name not in _MAGIC_GLOBALS
and not importStarred):
if (os.path.basename(self.filename) == '__init__.py' and
@@ -543,7 +549,6 @@ def FROM(self, node):
for name, alias in node.names:
if name == '*':
self.scope.importStarred = True
- #self.report(messages.ImportStarUsed, node.lineno, node.modname)
continue
name = alias or name
importation = Importation(name, node)
View
4 ninja_ide/dependencies/pyflakes_mod/scripts/pyflakes.py
@@ -35,7 +35,7 @@ def check(codeString, filename):
if sys.version_info[:2] == (2, 4):
raise SyntaxError(None)
raise
- except (SyntaxError, IndentationError), value:
+ except (SyntaxError, IndentationError) as value:
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
@@ -75,7 +75,7 @@ def checkPath(filename):
"""
try:
return check(file(filename, 'U').read() + '\n', filename)
- except IOError, msg:
+ except IOError as msg:
return 1
View
17 ninja_ide/gui/actions.py
@@ -272,7 +272,7 @@ def install_shortcuts(self, ide):
self.ide.mainContainer.change_tabs_visibility)
key = Qt.Key_1
- for i in xrange(10):
+ for i in range(10):
if sys.platform == "darwin":
short = TabShortcuts(
QKeySequence(Qt.CTRL + Qt.ALT + key), self.ide, i)
@@ -455,7 +455,7 @@ def _add_file_to_project(self, path):
self.ide.mainContainer.actualTab.setTabText(
self.ide.mainContainer.actualTab.currentIndex(), name)
editorWidget._file_saved()
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
@@ -534,13 +534,13 @@ def close_files_from_project(self, project):
"""Close the files related to this project."""
if project:
tabMain = self.ide.mainContainer._tabMain
- for tabIndex in reversed(xrange(tabMain.count())):
+ for tabIndex in reversed(range(tabMain.count())):
if file_manager.belongs_to_folder(
project, tabMain.widget(tabIndex).ID):
tabMain.removeTab(tabIndex)
tabSecondary = self.ide.mainContainer._tabSecondary
- for tabIndex in reversed(xrange(tabSecondary.count())):
+ for tabIndex in reversed(range(tabSecondary.count())):
if file_manager.belongs_to_folder(
project, tabSecondary.widget(tabIndex).ID):
tabSecondary.removeTab(tabIndex)
@@ -626,7 +626,6 @@ def editor_indent_less(self):
def editor_indent_more(self):
"""Indent 1 position to the right for the current line or selection."""
- print 'yes'
editorWidget = self.ide.mainContainer.get_actual_editor()
if editorWidget and editorWidget.hasFocus():
editorWidget.indent_more()
@@ -810,8 +809,8 @@ def locate_function(self, function, filePath, isVariable):
self.__codeBack.append((editorWidget.ID,
editorWidget.textCursor().position()))
self.__codeForward = []
- self._locator.navigate_to(unicode(function),
- unicode(filePath), isVariable)
+ self._locator.navigate_to(function,
+ filePath, isVariable)
def update_explorer(self):
"""Update the symbols in the Symbol Explorer when a file is saved."""
@@ -956,7 +955,7 @@ def group_tabs_together(self):
if not projectName:
projectName = file_manager.get_basename(project)
tabGroup = tab_group.TabGroup(project, projectName, self)
- for index in reversed(xrange(
+ for index in reversed(range(
self.ide.mainContainer._tabMain.count())):
widget = self.ide.mainContainer._tabMain.widget(index)
if type(widget) is editor.Editor and \
@@ -968,7 +967,7 @@ def group_tabs_together(self):
def deactivate_tabs_groups(self):
"""Deactivate tab grouping based in the project they belong."""
- for index in reversed(xrange(
+ for index in reversed(range(
self.ide.mainContainer._tabMain.count())):
widget = self.ide.mainContainer._tabMain.widget(index)
if type(widget) is tab_group.TabGroup:
View
14 ninja_ide/gui/central_widget.py
@@ -106,14 +106,12 @@ def showEvent(self, event):
self._splitterArea.insertWidget(0, self._splitterMain)
qsettings = QSettings()
#Lists of sizes as list of QVariant- heightList = [QVariant, QVariant]
- heightList = qsettings.value("window/central/mainSize",
- [(self.height() / 3) * 2, self.height() / 3]).toList()
- widthList = qsettings.value("window/central/areaSize",
- [(self.width() / 6) * 5, self.width() / 6]).toList()
- self._splitterMainSizes = [
- heightList[0].toInt()[0], heightList[1].toInt()[0]]
- self._splitterAreaSizes = [
- widthList[0].toInt()[0], widthList[1].toInt()[0]]
+ heightList = list(qsettings.value("window/central/mainSize",
+ [(self.height() / 3) * 2, self.height() / 3]))
+ widthList = list(qsettings.value("window/central/areaSize",
+ [(self.width() / 6) * 5, self.width() / 6]))
+ self._splitterMainSizes = [int(heightList[0]), int(heightList[1])]
+ self._splitterAreaSizes = [int(widthList[0]), int(widthList[1])]
if not event.spontaneous():
self.change_misc_visibility()
if bin(settings.UI_LAYOUT)[-1] == '1':
View
4 ninja_ide/gui/dialogs/about_ninja.py
@@ -67,10 +67,10 @@ def __init__(self, parent=None):
and handles all kinds of situations thanks to its rich extensibility.""")))
vbox.addWidget(QLabel(self.tr("Version: %s" % ninja_ide.__version__)))
link_ninja = QLabel(
- self.tr("Website: <a href='%1'>%s</a>" % ninja_ide.__url__))
+ self.tr("Website: <a href='%s'>%s</a>" % ninja_ide.__url__))
vbox.addWidget(link_ninja)
link_source = QLabel(
- self.tr("Source Code: <a href='%s'>%s</a>" % \
+ self.tr("Source Code: <a href='%s'>%s</a>" %
(ninja_ide.__source__, ninja_ide.__source__)))
vbox.addWidget(link_source)
View
19 ninja_ide/gui/dialogs/language_manager.py
@@ -15,10 +15,15 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
-from __future__ import absolute_import
-
import os
-import urllib2
+#lint:disable
+try:
+ from urllib.request import urlopen
+ from urllib.error import URLError
+except ImportError:
+ from urllib2 import urlopen
+ from urllib2 import URLError
+#lint:enable
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QVBoxLayout
@@ -98,14 +103,14 @@ def resizeEvent(self, event):
def execute_thread(self):
try:
- descriptor_languages = urllib2.urlopen(resources.LANGUAGES_URL)
+ descriptor_languages = urlopen(resources.LANGUAGES_URL)
languages = json_manager.parse(descriptor_languages)
languages = [[name, languages[name]] for name in languages]
local_languages = self.get_local_languages()
languages = [languages[i] for i in range(len(languages)) if
os.path.basename(languages[i][1]) not in local_languages]
self._languages = languages
- except urllib2.URLError:
+ except URLError:
self._languages = []
def get_local_languages(self):
@@ -123,11 +128,11 @@ def _download_language_thread(self):
def download(self, url, folder):
fileName = os.path.join(folder, os.path.basename(url))
try:
- content = urllib2.urlopen(url)
+ content = urlopen(url)
f = open(fileName, 'wb')
f.write(content.read())
f.close()
- except urllib2.URLError:
+ except URLError:
return
View
23 ninja_ide/gui/dialogs/plugins_manager.py
@@ -16,6 +16,7 @@
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
import webbrowser
from copy import copy
@@ -63,7 +64,7 @@
def _get_plugin(plugin_name, plugin_list):
plugin = None
for plug in plugin_list:
- if unicode(plug["name"]) == unicode(plugin_name):
+ if plug["name"] == plugin_name:
plugin = plug
break
return plugin
@@ -246,7 +247,7 @@ def __init__(self, parent, updates):
def _show_item_description(self):
item = self._table.currentItem()
if item is not None:
- data = item.data(Qt.UserRole).toList()
+ data = list(item.data(Qt.UserRole))
self._parent.show_plugin_info(data)
def _update_plugins(self):
@@ -256,7 +257,7 @@ def _update_plugins(self):
for p_row in plugins:
#search the plugin
for p_dict in self._updates:
- if unicode(p_dict["name"]) == unicode(p_row[0]):
+ if p_dict["name"] == p_row[0]:
p_data = p_dict
break
#append the downlod link
@@ -293,7 +294,7 @@ def __init__(self, parent, available):
def _show_item_description(self):
item = self._table.currentItem()
if item is not None:
- data = item.data(Qt.UserRole).toList()
+ data = list(item.data(Qt.UserRole))
self._parent.show_plugin_info(data)
def _install_plugins(self):
@@ -303,7 +304,7 @@ def _install_plugins(self):
for p_row in plugins:
#search the plugin
for p_dict in self._available:
- if unicode(p_dict["name"]) == unicode(p_row[0]):
+ if p_dict["name"] == p_row[0]:
p_data = p_dict
break
#append the downlod link
@@ -363,7 +364,7 @@ def __init__(self, parent, installed):
def _show_item_description(self):
item = self._table.currentItem()
if item is not None:
- data = item.data(Qt.UserRole).toList()
+ data = list(item.data(Qt.UserRole))
self._parent.show_plugin_info(data)
def remove_item(self, plugin_name):
@@ -424,11 +425,11 @@ def collect_data_thread(self):
if plug_oficial:
ava = plug_oficial
oficial_available = [p for p in oficial_available
- if unicode(p["name"]) != unicode(local_data["name"])]
+ if p["name"] != local_data["name"]]
elif plug_community:
ava = plug_community
community_available = [p for p in community_available
- if unicode(p["name"]) != unicode(local_data["name"])]
+ if p["name"] != local_data["name"]]
#check versions
if ava:
available_version = version.LooseVersion(str(ava["version"]))
@@ -457,7 +458,7 @@ def download_plugins_thread(self):
if req_command[0]:
self._manager._requirements[p[0]] = req_command[1]
self.emit(SIGNAL("plugin_downloaded(PyQt_PyObject)"), p)
- except Exception, e:
+ except Exception as e:
logger.warning("Impossible to install (%s): %s", p[0], e)
def uninstall_plugins_thread(self):
@@ -465,7 +466,7 @@ def uninstall_plugins_thread(self):
try:
plugin_manager.uninstall_plugin(p)
self.emit(SIGNAL("plugin_uninstalled(PyQt_PyObject)"), p)
- except Exception, e:
+ except Exception as e:
logger.warning("Impossible to uninstall (%s): %s", p[0], e)
def update_plugin_thread(self):
@@ -479,7 +480,7 @@ def update_plugin_thread(self):
p.append(name)
plugin_manager.update_local_plugin_descriptor([p])
self._manager.reset_installed_plugins()
- except Exception, e:
+ except Exception as e:
logger.warning("Impossible to update (%s): %s", p[0], e)
View
14 ninja_ide/gui/dialogs/preferences.py
@@ -120,7 +120,7 @@ def _cancel(self):
self.close()
def _save(self):
- for i in xrange(self._tabs.count()):
+ for i in range(self._tabs.count()):
self._tabs.widget(i).save()
self.close()
@@ -146,7 +146,7 @@ def __init__(self, parent):
vbox.addWidget(self._tabs)
def save(self):
- for i in xrange(self._tabs.count()):
+ for i in range(self._tabs.count()):
self._tabs.widget(i).save()
@@ -206,9 +206,9 @@ def __init__(self, dialog):
qsettings.beginGroup('preferences')
qsettings.beginGroup('general')
self._checkLastSession.setChecked(
- qsettings.value('loadFiles', True).toBool())
+ qsettings.value('loadFiles', 'true') == 'true')
self._checkActivatePlugins.setChecked(
- qsettings.value('activatePlugins', True).toBool())
+ qsettings.value('activatePlugins', 'true') == 'true')
self._checkNotifyUpdates.setChecked(settings.NOTIFY_UPDATES)
self._checkShowStartPage.setChecked(settings.SHOW_START_PAGE)
self._checkConfirmExit.setChecked(settings.CONFIRM_EXIT)
@@ -745,7 +745,7 @@ def __init__(self):
vbox.addWidget(self._tabs)
def save(self):
- for i in xrange(self._tabs.count()):
+ for i in range(self._tabs.count()):
self._tabs.widget(i).save()
@@ -1473,7 +1473,7 @@ def __init__(self, parent):
btnSidebarForeground))
# Connect Buttons
- for i in xrange(0, 26):
+ for i in range(0, 26):
item = grid.itemAtPosition(i, 1).widget()
btn = grid.itemAtPosition(i, 2).widget()
self.connect(item, SIGNAL("returnPressed()"),
@@ -1801,7 +1801,7 @@ def save_stylesheet(self):
QMessageBox.information(self, self.tr("Style Sheet Saved"),
self.tr("Theme saved at: '%s'." % file_name))
self.edit_qss.document().setModified(False)
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid File Name: the file '%s' already exists." %
ex.filename))
View
19 ninja_ide/gui/dialogs/themes_manager.py
@@ -15,10 +15,15 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
-from __future__ import absolute_import
-
import os
-import urllib2
+#lint:disable
+try:
+ from urllib.request import urlopen
+ from urllib.error import URLError
+except ImportError:
+ from urllib2 import urlopen
+ from urllib2 import URLError
+#lint:enable
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QVBoxLayout
@@ -96,14 +101,14 @@ def resizeEvent(self, event):
def execute_thread(self):
try:
- descriptor_schemes = urllib2.urlopen(resources.SCHEMES_URL)
+ descriptor_schemes = urlopen(resources.SCHEMES_URL)
schemes = json_manager.parse(descriptor_schemes)
schemes = [(d['name'], d['download']) for d in schemes]
local_schemes = self.get_local_schemes()
schemes = [schemes[i] for i in range(len(schemes)) if
os.path.basename(schemes[i][1]) not in local_schemes]
self._schemes = schemes
- except urllib2.URLError:
+ except URLError:
self._schemes = []
def get_local_schemes(self):
@@ -120,11 +125,11 @@ def _download_scheme_thread(self):
def download(self, url, folder):
fileName = os.path.join(folder, os.path.basename(url))
try:
- content = urllib2.urlopen(url)
+ content = urlopen(url)
f = open(fileName, 'w')
f.write(content.read())
f.close()
- except urllib2.URLError:
+ except URLError:
return
View
15 ninja_ide/gui/editor/editor.py
@@ -15,11 +15,17 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+
import re
from tokenize import generate_tokens, TokenError
import token as tkn
-from StringIO import StringIO
+#lint:disable
+try:
+ from StringIO import StringIO
+except:
+ from io import StringIO
+#lint:enable
from PyQt4.QtGui import QPlainTextEdit
from PyQt4.QtGui import QFontMetricsF
@@ -42,7 +48,6 @@
from ninja_ide import resources
from ninja_ide.core import settings
from ninja_ide.core import file_manager
-from ninja_ide.tools import json_manager
from ninja_ide.tools.completion import completer_widget
from ninja_ide.gui.main_panel import itab_item
from ninja_ide.gui.editor import highlighter
@@ -701,7 +706,7 @@ def __quot_completion(self, event):
simmetrical symbol, is a little more cumbersome guessing the completion
table.
"""
- text = unicode(event.text())
+ text = event.text()
PENTA_Q = 5 * text
TETRA_Q = 4 * text
TRIPLE_Q = 3 * text
@@ -729,7 +734,7 @@ def __brace_completion(self, event):
"""Indicate if this symbol is part of a given pair and needs to be
completed.
"""
- text = unicode(event.text())
+ text = event.text()
if text in settings.BRACES.values():
portion = self.__reverse_select_text_portion_from_offset(1, 1)
brace_open = portion[0]
@@ -740,7 +745,7 @@ def __brace_completion(self, event):
return True
def __auto_indent(self, event):
- text = unicode(self.textCursor().block().previous().text())
+ text = self.textCursor().block().previous().text()
spaces = helpers.get_indentation(text, self.indent, self.useTabs)
self.textCursor().insertText(spaces)
if text != '' and text == ' ' * len(text):
View
14 ninja_ide/gui/editor/errors_checker.py
@@ -17,13 +17,19 @@
from __future__ import absolute_import
import re
-import compiler
+try:
+ import compiler
+except ImportError:
+ print('Errors checker not working in Python3')
from PyQt4.QtCore import QThread
from ninja_ide.core import file_manager
from ninja_ide.core import settings
-from ninja_ide.dependencies.pyflakes_mod import checker
+try:
+ from ninja_ide.dependencies.pyflakes_mod import checker
+except ImportError:
+ print('Errors checker not working in Python3')
class ErrorsChecker(QThread):
@@ -68,7 +74,9 @@ def run(self):
message = self.errorsSummary[lineno]
message += [m.message % m.message_args]
self.errorsSummary[lineno] = message
- except Exception, reason:
+ except Exception as reason:
+ print(repr(reason))
+ raise
message = ''
if hasattr(reason, 'msg'):
message = reason.msg
View
44 ninja_ide/gui/editor/highlighter.py
@@ -52,6 +52,7 @@ def format(color, style=''):
def restyle(scheme):
+ """Reset the style for each highlighting item when the scheme change."""
STYLES['keyword'] = format(scheme.get('keyword',
resources.COLOR_SCHEME['keyword']), 'bold')
STYLES['operator'] = format(scheme.get('operator',
@@ -79,6 +80,7 @@ def restyle(scheme):
class SyntaxUserData(QTextBlockUserData):
+ """Store the information of the errors, str and comments for each block."""
def __init__(self, error=False):
super(SyntaxUserData, self).__init__()
@@ -87,18 +89,22 @@ def __init__(self, error=False):
self.comment_start = -1
def clear_data(self):
+ """Clear the data stored for the current block."""
self.error = False
self.str_groups = []
self.comment_start = -1
def add_str_group(self, start, end):
+ """Add a pair of values setting the beggining and end of a string."""
self.str_groups.append((start + 1, end))
def comment_start_at(self, pos):
+ """Set the position in the line where the comment starts."""
self.comment_start = pos
class Highlighter(QSyntaxHighlighter):
+ """Syntax Highlighter for NINJA-IDE."""
# braces
braces = ['\\(', '\\)', '\\{', '\\}', '\\[', '\\]']
@@ -116,9 +122,11 @@ def __init__(self, document, lang=None, scheme=None,
self.apply_highlight(lang, scheme)
def sanitize(self, word):
+ """Sanitize the string to avoid problems with the regex."""
return word.replace('\\', '\\\\')
def apply_highlight(self, lang, scheme=None, syntax=None):
+ """Set the rules that will decide what to highlight and how."""
if syntax is None:
langSyntax = settings.SYNTAX.get(lang, {})
else:
@@ -151,6 +159,7 @@ def apply_highlight(self, lang, scheme=None, syntax=None):
rules.append((r'__\w+__', 0, STYLES['properObject']))
+ # Classes and functions
definition = langSyntax.get('definition', [])
for de in definition:
expr = r'\b%s\b\s*(\w+)' % de
@@ -164,6 +173,7 @@ def apply_highlight(self, lang, scheme=None, syntax=None):
STYLES['numbers']),
]
+ # Regular expressions
regex = langSyntax.get('regex', [])
for reg in regex:
expr = reg[0]
@@ -178,12 +188,14 @@ def apply_highlight(self, lang, scheme=None, syntax=None):
style = reg[2]
rules.append((expr, 0, format(color, style)))
+ # Strings
stringChar = langSyntax.get('string', [])
for sc in stringChar:
expr = r'"[^"\\]*(\\.[^"\\]*)*"' if sc == '"' \
else r"'[^'\\]*(\\.[^'\\]*)*'"
rules.append((expr, 0, STYLES['string']))
+ # Comments
comments = langSyntax.get('comment', [])
for co in comments:
expr = co + '[^\\n]*'
@@ -218,7 +230,7 @@ def set_selected_word(self, word):
self.selected_word_pattern = None
def __highlight_pep8(self, char_format, user_data):
- """Highlight the lines with errors."""
+ """Highlight the lines with pep8 errors."""
user_data.error = True
char_format = char_format.toCharFormat()
char_format.setUnderlineColor(QColor(
@@ -229,7 +241,7 @@ def __highlight_pep8(self, char_format, user_data):
return char_format
def __highlight_lint(self, char_format, user_data):
- """Highlight the lines with errors."""
+ """Highlight the lines with lint errors."""
user_data.error = True
char_format = char_format.toCharFormat()
char_format.setUnderlineColor(QColor(
@@ -244,10 +256,12 @@ def highlightBlock(self, text):
self.highlight_function(text)
def set_open_visible_area(self, is_line, position):
+ """Set the range of lines that should be highlighted on open."""
if is_line:
self.visible_limits = (position - 50, position + 50)
def open_highlight(self, text):
+ """Only highlight the lines inside the accepted range."""
if self.visible_limits[0] <= self.currentBlock().blockNumber() <= \
self.visible_limits[1]:
self.realtime_highlight(text)
@@ -255,6 +269,11 @@ def open_highlight(self, text):
self.setCurrentBlockState(0)
def async_highlight(self):
+ """Execute a thread to collect the info of the things to highlight.
+
+ The thread will collect the data from where to where to highlight,
+ and which kind of highlight to use for those sections, and return
+ that info to the main thread after it process all the file."""
self.thread_highlight = HighlightParserThread(self)
self.connect(self.thread_highlight,
SIGNAL("highlightingDetected(PyQt_PyObject)"),
@@ -262,17 +281,25 @@ def async_highlight(self):
self.thread_highlight.start()
def _execute_threaded_highlight(self, styles=None):
+ """Function called with the info collected when the thread ends."""
self.highlight_function = self.threaded_highlight
if styles:
self._styles = styles
lines = list(set(styles.keys()) -
set(range(self.visible_limits[0], self.visible_limits[1])))
+ # Highlight the rest of the lines that weren't highlighted on open
self.rehighlight_lines(lines, False)
else:
self._styles = {}
self.highlight_function = self.realtime_highlight
def threaded_highlight(self, text):
+ """Highlight each line using the info collected by the thread.
+
+ This function doesn't need to execute the regular expressions to see
+ where the highlighting starts and end for each rule, it just take
+ the start and end point, and the proper highlighting style from the
+ info returned from the thread and applied that to the document."""
hls = []
block = self.currentBlock()
user_data = block.userData()
@@ -318,6 +345,12 @@ def threaded_highlight(self, text):
block.setUserData(user_data)
def realtime_highlight(self, text):
+ """Highlight each line while it is being edited.
+
+ This function apply the proper highlight to the line being edited
+ by the user, this is a really fast process for each line once you
+ already have the document highlighted, but slow to do it the first
+ time to highlight all the lines together."""
hls = []
block = self.currentBlock()
user_data = block.userData()
@@ -398,6 +431,7 @@ def realtime_highlight(self, text):
block.setUserData(user_data)
def _rehighlight_lines(self, lines):
+ """If the document is valid, highlight the list of lines received."""
if self.document() is None:
return
for line in lines:
@@ -405,6 +439,7 @@ def _rehighlight_lines(self, lines):
self.rehighlightBlock(block)
def _get_errors_lines(self):
+ """Return the number of lines that contains errors to highlight."""
errors_lines = []
block = self.document().begin()
while block.isValid():
@@ -415,6 +450,7 @@ def _get_errors_lines(self):
return errors_lines
def rehighlight_lines(self, lines, errors=True):
+ """Rehighlight the lines for errors or selected words."""
if errors:
errors_lines = self._get_errors_lines()
refresh_lines = set(lines + errors_lines)
@@ -477,6 +513,7 @@ def match_multiline(self, text, delimiter, in_state, style,
return False
def comment_multiline(self, text, delimiter_end, delimiter_start, style):
+ """Process the beggining and end of a multiline comment."""
startIndex = 0
if self.previousBlockState() != 1:
startIndex = delimiter_start.indexIn(text)
@@ -496,12 +533,14 @@ def comment_multiline(self, text, delimiter_end, delimiter_start, style):
class HighlightParserThread(QThread):
+ """Thread that collect the highlighting info to the current file."""
def __init__(self, highlighter):
super(HighlightParserThread, self).__init__()
self._highlighter = highlighter
def run(self):
+ """Execute this rules in another thread to avoid blocking the ui."""
styles = {}
self.msleep(300)
block = self._highlighter.document().begin()
@@ -535,6 +574,7 @@ def run(self):
class EmpyHighlighter(QSyntaxHighlighter):
+ """Dummy highlighter to be used when the current file is not recognized."""
def __init__(self, document):
super(EmpyHighlighter, self).__init__(document)
View
6 ninja_ide/gui/editor/pep8_checker.py
@@ -15,6 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
from PyQt4.QtCore import QThread
@@ -61,9 +62,10 @@ def run(self):
lineno = int(tempData[i][startPos:endPos]) - 1
error = tempData[i][tempData[i].find(
':', endPos + 1) + 2:]
- line = u'\n'.join(
+ line = '\n'.join(
[error, tempData[i + 1], tempData[i + 2]])
- except:
+ except Exception as e:
+ print(repr(e))
line = ''
finally:
i += 3
View
4 ninja_ide/gui/explorer/errors_lists.py
@@ -110,14 +110,14 @@ def _turn_on_off_pep8(self):
def errors_selected(self):
editorWidget = main_container.MainContainer().get_actual_editor()
if editorWidget and self._outRefresh:
- lineno = self.listErrors.currentItem().data(Qt.UserRole).toInt()[0]
+ lineno = int(self.listErrors.currentItem().data(Qt.UserRole))
editorWidget.jump_to_line(lineno)
editorWidget.setFocus()
def pep8_selected(self):
editorWidget = main_container.MainContainer().get_actual_editor()
if editorWidget and self._outRefresh:
- lineno = self.listPep8.currentItem().data(Qt.UserRole).toInt()[0]
+ lineno = int(self.listPep8.currentItem().data(Qt.UserRole))
editorWidget.jump_to_line(lineno)
editorWidget.setFocus()
View
14 ninja_ide/gui/explorer/explorer_container.py
@@ -15,6 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
import os
@@ -266,7 +267,7 @@ def open_project_folder(self, folderName='', notIDEStart=True):
thread.open_folder(folderName)
else:
self._treeProjects._set_current_project(folderName)
- except Exception, reason:
+ except Exception as reason:
logger.error('open_project_folder: %s', reason)
if not notIDEStart:
QMessageBox.information(self, self.tr("Incorrect Project"),
@@ -344,7 +345,7 @@ def close_opened_projects(self):
self._treeProjects._close_open_projects()
def save_recent_projects(self, folder):
- recent_project_list = QSettings().value('recentProjects', {}).toMap()
+ recent_project_list = QSettings().value('recentProjects', {})
#if already exist on the list update the date time
projectProperties = json_manager.read_ninja_project(folder)
name = projectProperties.get('name', '')
@@ -357,7 +358,7 @@ def save_recent_projects(self, folder):
description = self.tr('no description available')
if folder in recent_project_list:
- properties = recent_project_list[folder].toMap()
+ properties = recent_project_list[folder]
properties["lastopen"] = QDateTime.currentDateTime()
properties["name"] = name
properties["description"] = description
@@ -375,12 +376,11 @@ def save_recent_projects(self, folder):
QSettings().setValue('recentProjects', recent_project_list)
def find_most_old_open(self):
- recent_project_list = QSettings().value('recentProjects', {}).toMap()
+ recent_project_list = QSettings().value('recentProjects', {})
listFounder = []
- for recent_project_path, content in recent_project_list.iteritems():
+ for recent_project_path, content in recent_project_list.items():
listFounder.append((recent_project_path, int(
- content.toMap()[u"lastopen"].toDateTime().toString(
- "yyyyMMddHHmmzzz"))))
+ content["lastopen"].toString("yyyyMMddHHmmzzz"))))
listFounder = sorted(listFounder, key=lambda date: listFounder[1],
reverse=True) # sort by date last used
return listFounder[0][0]
View
24 ninja_ide/gui/explorer/tree_projects_widget.py
@@ -16,6 +16,7 @@
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
import os
@@ -336,10 +337,9 @@ def _timeout(self):
def _refresh_project_by_path(self, event, folder):
if event not in (DELETED, ADDED, REMOVE, RENAME):
return
- folder = unicode(folder)
oprojects = self.get_open_projects()
for each_project in oprojects:
- p_path = unicode(each_project.path)
+ p_path = each_project.path
if file_manager.belongs_to_folder(p_path, folder) and \
file_manager.is_supported_extension(folder,
each_project.extensions) and folder[:1] != '.':
@@ -359,7 +359,7 @@ def _refresh_project(self, item=None):
if item.parent() is None:
path = item.path
else:
- path = file_manager.create_path(item.path, unicode(item.text(0)))
+ path = file_manager.create_path(item.path, item.text(0))
thread = ui_tools.ThreadProjectExplore()
self._thread_execution[path] = thread
@@ -409,7 +409,7 @@ def _create_init(self):
pathFolder = os.path.join(item.path, str(item.text(0)))
try:
file_manager.create_init_file_complete(pathFolder)
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("Create INIT fail"),
ex.message)
self._refresh_project(item)
@@ -419,10 +419,10 @@ def _add_new_file(self):
if item.parent() is None:
pathForFile = item.path
else:
- pathForFile = os.path.join(item.path, unicode(item.text(0)))
+ pathForFile = os.path.join(item.path, item.text(0))
result = QInputDialog.getText(self, self.tr("New File"),
self.tr("Enter the File Name:"))
- fileName = unicode(result[0])
+ fileName = result[0]
if result[1] and fileName.strip() != '':
try:
@@ -438,7 +438,7 @@ def _add_new_file(self):
editorWidget = mainContainer.get_actual_editor()
editorWidget.textCursor().insertText("# -*- coding: utf-8 *-*")
main_container.MainContainer().save_file()
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
@@ -449,7 +449,7 @@ def add_existing_file(self, path):
paths = relative.split(os.sep)[:-1]
itemParent = self._actualProject
for p in paths:
- for i in xrange(itemParent.childCount()):
+ for i in range(itemParent.childCount()):
item = itemParent.child(i)
if item.text(0) == p:
itemParent = item
@@ -533,7 +533,7 @@ def _rename_file(self):
subitem.setIcon(0, self._get_file_icon(name))
index = item.parent().indexOfChild(item)
subitem.parent().takeChild(index)
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
@@ -562,7 +562,7 @@ def _copy_file(self):
content = file_manager.read_file_content(pathForFile)
path = file_manager.store_file_content(path, content, newFile=True)
self.add_existing_file(path)
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
@@ -588,7 +588,7 @@ def _move_file(self):
index = item.parent().indexOfChild(item)
item.parent().takeChild(index)
self.add_existing_file(path)
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
@@ -721,7 +721,7 @@ def _set_current_project(self, path):
def _close_open_projects(self):
self.__enableCloseNotification = False
- for i in xrange(self.topLevelItemCount()):
+ for i in range(self.topLevelItemCount()):
self.setCurrentItem(self.topLevelItem(0))
self._close_project()
self.__enableCloseNotification = True
View
59 ninja_ide/gui/ide.py
@@ -15,6 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
import sys
@@ -317,7 +318,7 @@ def load_session_files_projects(self, filesTab1, filesTab2, projects,
def open_file(self, filename):
if filename:
- self.mainContainer.open_file(unicode(filename))
+ self.mainContainer.open_file(filename)
def open_project(self, project):
if project:
@@ -369,7 +370,7 @@ def save_settings(self):
current_file = ''
if editor_widget is not None:
current_file = editor_widget.ID
- if qsettings.value('preferences/general/loadFiles', True).toBool():
+ if qsettings.value('preferences/general/loadFiles', 'true') == 'true':
openedFiles = self.mainContainer.get_opened_documents()
projects_obj = self.explorer.get_opened_projects()
projects = [p.path for p in projects_obj]
@@ -401,8 +402,7 @@ def save_settings(self):
qsettings.setValue("window/central/mainSize",
self.central.get_main_sizes())
#Save the toolbar visibility
- qsettings.setValue("window/hide_toolbar",
- not self.toolbar.isVisible() and self.menuBar().isVisible())
+ qsettings.setValue("window/hide_toolbar", not self.toolbar.isVisible())
#Save Profiles
if self.profile is not None:
self.actions.save_profile(self.profile)
@@ -412,7 +412,7 @@ def save_settings(self):
def load_window_geometry(self):
"""Load from QSettings the window size of de Ninja IDE"""
qsettings = QSettings()
- if qsettings.value("window/maximized", True).toBool():
+ if qsettings.value("window/maximized", 'true') == 'true':
self.setWindowState(Qt.WindowMaximized)
else:
self.resize(qsettings.value("window/size",
@@ -495,8 +495,7 @@ def start(filenames=None, projects_path=None,
#Translator
qsettings = QSettings()
language = QLocale.system().language()
- lang = qsettings.value(
- 'preferences/interface/language', language).toString() + '.qm'
+ lang = qsettings.value('preferences/interface/language', language) + '.qm'
lang_path = file_manager.create_path(resources.LANGS, lang)
if file_manager.file_exists(lang_path):
settings.LANGUAGE = lang_path
@@ -541,8 +540,7 @@ def start(filenames=None, projects_path=None,
#Loading Schemes
splash.showMessage("Loading Schemes",
Qt.AlignRight | Qt.AlignTop, Qt.black)
- scheme = qsettings.value('preferences/editor/scheme',
- "default").toString()
+ scheme = qsettings.value('preferences/editor/scheme', "default")
if scheme != 'default':
scheme = file_manager.create_path(resources.EDITOR_SKINS,
scheme + '.color')
@@ -562,30 +560,47 @@ def start(filenames=None, projects_path=None,
splash.showMessage("Loading Files and Projects",
Qt.AlignRight | Qt.AlignTop, Qt.black)
#Files in Main Tab
- mainFiles = qsettings.value('openFiles/mainTab', []).toList()
+ main_files = qsettings.value('openFiles/mainTab', [])
+ if main_files is not None:
+ mainFiles = list(main_files)
+ else:
+ mainFiles = list()
tempFiles = []
for file_ in mainFiles:
- fileData = file_.toList()
- tempFiles.append((fileData[0].toString(), fileData[1].toInt()[0]))
+ fileData = list(file_)
+ tempFiles.append((fileData[0], int(fileData[1])))
mainFiles = tempFiles
#Files in Secondary Tab
- secondaryFiles = qsettings.value('openFiles/secondaryTab', []).toList()
+ sec_files = qsettings.value('openFiles/secondaryTab', [])
+ if sec_files is not None:
+ secondaryFiles = list(sec_files)
+ else:
+ secondaryFiles = list()
tempFiles = []
for file_ in secondaryFiles:
- fileData = file_.toList()
- tempFiles.append((fileData[0].toString(), fileData[1].toInt()[0]))
+ fileData = list(file_)
+ tempFiles.append((fileData[0], int(fileData[1])))
secondaryFiles = tempFiles
# Recent Files
- recent_files = qsettings.value('openFiles/recentFiles', []).toList()
- recent_files = [file_.toString() for file_ in recent_files]
+ recent = qsettings.value('openFiles/recentFiles', [])
+ if recent is not None:
+ recent_files = list(recent)
+ else:
+ recent_files = list()
+ recent_files = [file_ for file_ in recent_files]
#Current File
- current_file = qsettings.value('openFiles/currentFile', '').toString()
+ current_file = qsettings.value('openFiles/currentFile', '')
#Projects
- projects = qsettings.value('openFiles/projects', []).toList()
- projects = [project.toString() for project in projects]
+ projects_list = qsettings.value('openFiles/projects', [])
+ if projects_list is not None:
+ projects = list(projects_list)
+ else:
+ projects = list()
+ projects = [project for project in projects]
#Include files received from console args
- file_with_nro = map(lambda f: (f[0], f[1] - 1), zip(filenames, linenos))
- file_without_nro = map(lambda f: (f, 0), filenames[len(linenos):])
+ file_with_nro = list(map(lambda f: (f[0], f[1] - 1),
+ zip(filenames, linenos)))
+ file_without_nro = list(map(lambda f: (f, 0), filenames[len(linenos):]))
mainFiles += file_with_nro + file_without_nro
#Include projects received from console args
if projects_path:
View
13 ninja_ide/gui/main_panel/browser_widget.py
@@ -15,10 +15,12 @@
# You should have received a copy of the GNU General Public License
# along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+from __future__ import unicode_literals
import sys
import os
import time
+import datetime
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QVBoxLayout
@@ -127,16 +129,15 @@ def load_items(self):
settings = QSettings()
listByFavorites = []
listNoneFavorites = []
- recent_projects_dict = settings.value(
- 'recentProjects', {}).toMap()
+ recent_projects_dict = dict(settings.value('recentProjects', {}))
#Filter for favorites
- for recent_project_path, content in recent_projects_dict.iteritems():
- if content.toMap()[u"isFavorite"].toBool():
+ for recent_project_path, content in recent_projects_dict.items():
+ if bool(dict(content)["isFavorite"]):
listByFavorites.append((recent_project_path,
- content.toMap()[u"lastopen"].toDateTime()))
+ content["lastopen"]))
else:
listNoneFavorites.append((recent_project_path,
- content.toMap()[u"lastopen"].toDateTime()))
+ content["lastopen"]))
if len(listByFavorites) > 1:
# sort by date favorites
listByFavorites = sorted(listByFavorites,
View
35 ninja_ide/gui/main_panel/main_container.py
@@ -217,7 +217,7 @@ def show_split(self, orientation):
orientation == self.orientation():
self._tabSecondary.hide()
self.splitted = False
- for i in xrange(self._tabSecondary.count()):
+ for i in range(self._tabSecondary.count()):
widget = self._tabSecondary.widget(0)
name = self._tabSecondary.tabText(0)
self._tabMain.add_tab(widget, name)
@@ -424,7 +424,7 @@ def open_image(self, fileName):
viewer.id = fileName
else:
self.move_to_open(fileName)
- except Exception, reason:
+ except Exception as reason:
logger.error('open_image: %s', reason)
QMessageBox.information(self, self.tr("Incorrect File"),
self.tr("The image couldn\'t be open"))
@@ -500,12 +500,11 @@ def __open_file(self, fileName='', cursorPosition=-1,
else:
editorWidget.set_cursor_position(cursorPosition)
self.emit(SIGNAL("currentTabChanged(QString)"), fileName)
- except file_manager.NinjaIOException, reason:
+ except file_manager.NinjaIOException as reason:
if not notStart:
QMessageBox.information(self,
- self.tr("The file couldn't be open"),
- unicode(reason))
- except Exception, reason:
+ self.tr("The file couldn't be open"), reason)
+ except Exception as reason:
logger.error('open_file: %s', reason)
self.actualTab.notOpening = True
@@ -605,8 +604,8 @@ def save_file(self, editorWidget=None):
self.tr("File Saved: %s" % fileName))
editorWidget._file_saved()
return True
- except Exception, reason:
- print reason
+ except Exception as reason:
+ print(reason)
raise
editorWidget.just_saved = False
logger.error('save_file: %s', reason)
@@ -651,12 +650,12 @@ def save_file_as(self):
self.add_standalone_watcher(fileName)
self._file_watcher.allow_kill = True
return True
- except file_manager.NinjaFileExistsException, ex:
+ except file_manager.NinjaFileExistsException as ex:
editorWidget.just_saved = False
QMessageBox.information(self, self.tr("File Already Exists"),
self.tr("Invalid Path: the file '%s' already exists." %
ex.filename))
- except Exception, reason:
+ except Exception as reason:
editorWidget.just_saved = False
logger.error('save_file_as: %s', reason)
QMessageBox.information(self, self.tr("Save Error"),
@@ -675,7 +674,7 @@ def _get_save_folder(self, fileName):
return os.path.expanduser("~")
def save_project(self, projectFolder):
- for i in xrange(self._tabMain.count()):
+ for i in range(self._tabMain.count()):
editorWidget = self._tabMain.widget(i)
if type(editorWidget) is editor.Editor and \
file_manager.belongs_to_folder(projectFolder, editorWidget.ID):
@@ -683,7 +682,7 @@ def save_project(self, projectFolder):
editorWidget)
if not reloaded:
self.save_file(editorWidget)
- for i in xrange(self._tabSecondary.count()):
+ for i in range(self._tabSecondary.count()):
editorWidget = self._tabSecondary.widget(i)
if type(editorWidget) is editor.Editor and \
file_manager.belongs_to_folder(projectFolder, editorWidget.ID):
@@ -693,14 +692,14 @@ def save_project(self, projectFolder):
self.save_file(editorWidget)
def save_all(self):
- for i in xrange(self._tabMain.count()):
+ for i in range(self._tabMain.count()):
editorWidget = self._tabMain.widget(i)
if type(editorWidget) is editor.Editor:
reloaded