home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / gedit-2 / plugins / externaltools / functions.py < prev    next >
Encoding:
Python Source  |  2006-08-27  |  10.2 KB  |  331 lines

  1. # -*- coding: utf-8 -*-
  2. #    Gedit External Tools plugin
  3. #    Copyright (C) 2005-2006  Steve Fr├⌐cinaux <steve@istique.net>
  4. #
  5. #    This program is free software; you can redistribute it and/or modify
  6. #    it under the terms of the GNU General Public License as published by
  7. #    the Free Software Foundation; either version 2 of the License, or
  8. #    (at your option) any later version.
  9. #
  10. #    This program is distributed in the hope that it will be useful,
  11. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #    GNU General Public License for more details.
  14. #
  15. #    You should have received a copy of the GNU General Public License
  16. #    along with this program; if not, write to the Free Software
  17. #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  18.  
  19. import ElementTree as et
  20. import os
  21. import gtk
  22. from gtk import gdk
  23. import gnomevfs
  24. import gedit, gtksourceview
  25. from outputpanel import OutputPanel
  26. from capture import *
  27.  
  28. # ==== Data storage related functions ====
  29.  
  30. class ToolsTree:
  31.     def __init__(self):
  32.         self.xml_location = os.path.join(os.environ['HOME'], '.gnome2/gedit')
  33.  
  34.         if not os.path.isdir(self.xml_location):
  35.             os.mkdir(self.xml_location)
  36.  
  37.         self.xml_location = os.path.join(self.xml_location, 'gedit-tools.xml')
  38.         
  39.         try:
  40.             if not os.path.isfile(self.xml_location):
  41.                 self.tree = et.parse(self.get_stock_file())
  42.             else:
  43.                 self.tree = et.parse(self.xml_location)
  44.             self.root = self.tree.getroot()
  45.         except:
  46.             self.root = et.Element('tools')
  47.             self.tree = et.ElementTree(self.root)
  48.     
  49.     def __iter__(self):
  50.         return iter(self.root)
  51.     
  52.     def get_stock_file(self):
  53.         dirs = os.getenv('XDG_DATA_DIR')
  54.         if dirs:
  55.             dirs = dirs.split(os.pathsep)
  56.         else:
  57.             dirs = ('/usr/local/share', '/usr/share')
  58.         
  59.         for d in dirs:
  60.             f = os.path.join(d, 'gedit-2/plugins/externaltools/stock-tools.xml')
  61.             if os.path.isfile(f):
  62.                 return f
  63.  
  64.         return None
  65.     
  66.     def save(self):
  67.         self.tree.write(self.xml_location, 'UTF-8')
  68.         
  69.     def get_tool_from_accelerator(self, keyval, mod, ignore = None):
  70.         if not self.root:
  71.             return None
  72.         
  73.         for tool in self.root:
  74.             if tool != ignore:
  75.                 skey, smod = gtk.accelerator_parse(default(tool.get('accelerator'), ''))
  76.                 if skey == keyval and mod == smod:
  77.                     return tool
  78.         return None
  79.  
  80.  
  81. def default(val, d):
  82.     if val is not None:
  83.         return val
  84.     else:
  85.         return d
  86.  
  87. # ==== UI related functions ====
  88. APPLICABILITIES = ('all', 'titled', 'local', 'remote', 'untitled')
  89.  
  90. def insert_tools_menu(window, tools = None):
  91.     window_data = dict()
  92.     window.set_data("ToolsPluginCommandsData", window_data)
  93.  
  94.     if tools is None:
  95.         tools = ToolsTree()
  96.  
  97.     manager = window.get_ui_manager()
  98.  
  99.     window_data['action_groups'] = dict()
  100.     window_data['ui_id'] = manager.new_merge_id()
  101.  
  102.     i = 0;
  103.     for tool in tools:
  104.         menu_id = "ToolCommand%06d" % i
  105.         
  106.         ap = tool.get('applicability')
  107.         if ap not in window_data['action_groups']:
  108.             window_data['action_groups'][ap] = \
  109.                 gtk.ActionGroup("GeditToolsPluginCommandsActions%s" % ap.capitalize())
  110.             window_data['action_groups'][ap].set_translation_domain('gedit')
  111.         
  112.         window_data['action_groups'][ap].add_actions(
  113.             [(menu_id, None, tool.get('label'),
  114.               tool.get('accelerator'), tool.get('description'),
  115.               capture_menu_action)],
  116.             (window, tool))
  117.         manager.add_ui(window_data['ui_id'],
  118.                        '/MenuBar/ToolsMenu/ToolsOps_4',
  119.                        menu_id, 
  120.                        menu_id,
  121.                        gtk.UI_MANAGER_MENUITEM,
  122.                        False)
  123.         i = i + 1
  124.  
  125.     for applic in APPLICABILITIES:
  126.         if applic in window_data['action_groups']:
  127.             manager.insert_action_group(window_data['action_groups'][applic], -1)
  128.  
  129. def remove_tools_menu(window):
  130.     window_data = window.get_data("ToolsPluginCommandsData")
  131.  
  132.     manager = window.get_ui_manager()
  133.     manager.remove_ui(window_data['ui_id'])
  134.     for action_group in window_data['action_groups'].itervalues():
  135.         manager.remove_action_group(action_group)
  136.     window.set_data("ToolsPluginCommandsData", None)
  137.  
  138. def update_tools_menu(tools = None):
  139.     for window in gedit.app_get_default().get_windows():
  140.         remove_tools_menu(window)
  141.         insert_tools_menu(window, tools)
  142.         filter_tools_menu(window)
  143.         window.get_ui_manager().ensure_update()
  144.  
  145. def filter_tools_menu(window):
  146.     action_groups = window.get_data("ToolsPluginCommandsData")['action_groups']
  147.  
  148.     document = window.get_active_document()
  149.     if document is not None:
  150.         active_groups = ['all']
  151.         uri = document.get_uri()
  152.         if uri is not None:
  153.             active_groups.append('titled')
  154.             if gnomevfs.get_uri_scheme(uri) == 'file':
  155.                 active_groups.append('local')
  156.             else:
  157.                 active_groups.append('remote')
  158.         else:
  159.             active_groups.append('untitled')
  160.     else:
  161.         active_groups = []
  162.  
  163.     for name, group in action_groups.iteritems():
  164.         group.set_sensitive(name in active_groups)
  165.  
  166. # ==== Capture related functions ====
  167. def capture_menu_action(action, window, node):
  168.  
  169.     # Get the panel
  170.     panel = window.get_data("ToolsPluginWindowData")["output_buffer"]
  171.     panel.show()
  172.     panel.clear()
  173.  
  174.     # Configure capture environment
  175.     try:
  176.         cwd = os.getcwd()
  177.     except OSError:
  178.         cwd = os.getenv('HOME');
  179.  
  180.      capture = Capture(node.text, cwd)
  181.      capture.env = os.environ.copy()
  182.     capture.set_env(GEDIT_CWD = cwd)
  183.  
  184.     view = window.get_active_view()
  185.     if view is not None:
  186.         # Environment vars relative to current document
  187.         document = view.get_buffer()
  188.         uri = document.get_uri()
  189.         if uri is not None:
  190.             scheme = gnomevfs.get_uri_scheme(uri)
  191.             name = os.path.basename(uri)
  192.             capture.set_env(GEDIT_CURRENT_DOCUMENT_URI    = uri,
  193.                             GEDIT_CURRENT_DOCUMENT_NAME   = name,
  194.                             GEDIT_CURRENT_DOCUMENT_SCHEME = scheme)
  195.             if scheme == 'file':
  196.                  path = gnomevfs.get_local_path_from_uri(uri)
  197.                 cwd = os.path.dirname(path)
  198.                 capture.set_cwd(cwd)
  199.                 capture.set_env(GEDIT_CURRENT_DOCUMENT_PATH = path,
  200.                                 GEDIT_CURRENT_DOCUMENT_DIR  = cwd)
  201.         
  202.         documents_uri = [doc.get_uri()
  203.                                  for doc in window.get_documents()
  204.                                  if doc.get_uri() is not None]
  205.         documents_path = [gnomevfs.get_local_path_from_uri(uri)
  206.                                  for uri in documents_uri
  207.                                  if gnomevfs.get_uri_scheme(uri) == 'file']
  208.         capture.set_env(GEDIT_DOCUMENTS_URI  = ' '.join(documents_uri),
  209.                         GEDIT_DOCUMENTS_PATH = ' '.join(documents_path))
  210.  
  211.      capture.set_flags(capture.CAPTURE_BOTH)
  212.  
  213.     # Assign the error output to the output panel
  214.     panel.process = capture
  215.  
  216.     # Get input text
  217.     input_type = default(node.get('input'), 'nothing')
  218.     output_type = default(node.get('output'), 'output-panel')
  219.  
  220.     if input_type != 'nothing' and view is not None:
  221.         if input_type == 'document':
  222.             start, end = document.get_bounds()
  223.         elif input_type == 'selection':
  224.             try:
  225.                 start, end = document.get_selection_bounds()
  226.             except ValueError:
  227.                 start, end = document.get_bounds()
  228.                 if output_type == 'replace-selection':
  229.                     document.select_range(start, end)
  230.         elif input_type == 'line':
  231.             start = document.get_iter_at_mark(document.get_insert())
  232.             end = start.copy()
  233.             if not start.starts_line():
  234.                 start.backward_line()
  235.             if not end.ends_line():
  236.                 end.forward_to_line_end()
  237.         elif input_type == 'word':
  238.             start = document.get_iter_at_mark(document.get_insert())
  239.             end = start.copy()
  240.             if not start.inside_word():
  241.                 panel.write(_('You must be inside a word to run this command'),
  242.                             panel.command_tag)
  243.                 return
  244.             if not start.starts_word():
  245.                 start.backward_word_start()
  246.             if not end.ends_word():
  247.                 end.forward_word_end()
  248.             
  249.         input_text = document.get_text(start, end)
  250.         capture.set_input(input_text)
  251.     
  252.     # Assign the standard output to the chosen "file"
  253.     if output_type == 'new-document':
  254.         tab = window.create_tab(True)
  255.         view = tab.get_view()
  256.         document = tab.get_document()
  257.         pos = document.get_start_iter()
  258.         capture.connect('stdout-line', capture_stdout_line_document, document, pos)
  259.         document.begin_user_action()
  260.         view.set_editable(False)
  261.         view.set_cursor_visible(False)
  262.     elif output_type != 'output-panel' and view is not None:
  263.         document.begin_user_action()
  264.         view.set_editable(False)
  265.         view.set_cursor_visible(False)
  266.         
  267.         if output_type == 'insert':
  268.             pos = document.get_iter_at_mark(document.get_mark('insert'))
  269.         elif output_type == 'replace-selection':
  270.             document.delete_selection(False, False)
  271.             pos = document.get_iter_at_mark(document.get_mark('insert'))
  272.         elif output_type == 'replace-document':
  273.             document.set_text('')
  274.             pos = document.get_end_iter()
  275.         else:
  276.             pos = document.get_end_iter()
  277.         capture.connect('stdout-line', capture_stdout_line_document, document, pos)
  278.     else:
  279.         capture.connect('stdout-line', capture_stdout_line_panel, panel)
  280.         document.begin_user_action()
  281.  
  282.     capture.connect('stderr-line',   capture_stderr_line_panel,   panel)
  283.     capture.connect('begin-execute', capture_begin_execute_panel, panel, node.get('label'))
  284.     capture.connect('end-execute',   capture_end_execute_panel,   panel, view, 
  285.                     output_type in ('new-document','replace-document'))
  286.     
  287.     # Run the command
  288.     view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gdk.Cursor(gdk.WATCH))
  289.     capture.execute()
  290.     document.end_user_action()
  291.  
  292. def capture_stderr_line_panel(capture, line, panel):
  293.     panel.write(line, panel.error_tag)
  294.  
  295. def capture_begin_execute_panel(capture, panel, label):
  296.     panel['stop'].set_sensitive(True)
  297.     panel.clear()
  298.     panel.write(_("Running tool:"), panel.italic_tag);
  299.     panel.write(" %s\n\n" % label, panel.bold_tag);
  300.  
  301. def capture_end_execute_panel(capture, exit_code, panel, view, update_type):
  302.     panel['stop'].set_sensitive(False)
  303.     
  304.     if update_type:
  305.         doc = view.get_buffer()
  306.         start = doc.get_start_iter()
  307.         end = start.copy()
  308.         end.forward_chars(300)
  309.         
  310.         mtype = gnomevfs.get_mime_type_for_data(doc.get_text(start, end))
  311.         languages_manager = gtksourceview.SourceLanguagesManager()
  312.         language = languages_manager.get_language_from_mime_type(mtype)
  313.         if language is not None:
  314.             doc.set_language(language)
  315.     
  316.     view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gdk.Cursor(gdk.XTERM))
  317.     view.set_cursor_visible(True)
  318.     view.set_editable(True)
  319.  
  320.     if exit_code == 0:
  321.         panel.write("\n" + _("Done.") + "\n", panel.italic_tag)
  322.     else:
  323.         panel.write("\n" + _("Exited") + ":", panel.italic_tag)
  324.         panel.write(" %d\n" % exit_code, panel.bold_tag)
  325.  
  326. def capture_stdout_line_panel(capture, line, panel):
  327.     panel.write(line)
  328.  
  329. def capture_stdout_line_document(capture, line, document, pos):
  330.     document.insert(pos, line)
  331.