Commits

Henning Schröder  committed 4ff2d7e

cleanup and refactorings

  • Participants
  • Parent commits 729a0ad

Comments (0)

Files changed (193)

File codeaide/fileio.py

     i18n = lambda s:s
 
 
-def confirm_close(doc):
+def confirm_close(doc, parent=None):
     if doc.isModified():
         ret = QMessageBox.warning(
-            self.parent.widget, i18n("Closing file"),
+            parent, i18n("Closing file"),
             i18n("This document has been modified.\n"
                  "Do you want to save your changes?"),
             QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,

File codeaide/ide/__init__.py

Empty file removed.

File codeaide/ide/api.py

-from codeaide.interface import Interface, classproperty, Signal
-
-
-
-class Settings(Interface):
-
-    
-    keys = property()
-
-
-    
-    def set(self, key, value):
-        """
-        """
-        
-        
-    def get(self, key, default=None):
-        """
-        """
-        
-
-
-
-class Application(Interface):
-
-
-    active_window = property()
-    settings = property()
-
-        
-    def i18n(self, s):
-        """
-        """
-        
-        
-    def find_icon(self, name):
-        """
-        """
-
-        
-    def run(self):
-        """
-        """
-
-
-    def create_main_window(self):
-        """
-        """
-
-
-
-    def quit(self, force=False):
-        """
-        """
-
-
-
-
-class MainWindow(Interface):
-
-
-    def setup(self):
-        """
-        """
-
-
-class View(Interface):
-
-    active_document = property()
-    active_editor = property()
-
-
-
-class Editor(Interface):
-    """
-    """
-
-    def set_text(self, text):
-        """
-        """
-
-
-class Dock(Interface):
-    """
-    """
-
-
-class Document(Interface):
-
-
-    def load(self, filename):
-        """
-        """
-
-
-    def save(self, filename):
-        """
-        """
-
-
-
-
-
-class Command(Interface):
-
-    shortcut = property()
-    icon = property()
-    menu = property()
-
-
-    def execute(self):
-        """
-        """
-
-
-        
-class Hook(Interface):
-    
-    def execute(self, *args, **kwargs):
-        """
-        """
-
-
-        
-class OnStart(Hook):
-    """
-    """
-
-
-class OnReady(Hook):
-    """
-    """
-
-
-
-class OnQuit(Hook):
-    """
-    """
-
-
-    
-class SimpleSession(Interface):
-    session_properties = property()
-    object_uid = property()
-
-
-    
-class Session(Interface):
-    
-    def save_session(self):
-        """
-        """
-        
-        
-    def restore_session(self):
-        """
-        """
-
-
-
-class Preference(Interface):
-
-    key = property()
-    default = property()
-    value_type = property()
-    section = property()
-    on_change = Signal()
-
-
-
-
-class Buffer(Interface):
-    """
-    """
-
-
-class Window(Interface):
-    """
-    """
-    
-    def switch_buffer(self, name):
-        pass
-    
-
-class Frame(Interface):
-    """
-    """
-    
-    def new_window(self):
-        pass
-
-
-
-    
-    
-class Project(Interface):
-    
-    root_path = property()
-    python_path = property()
-

File codeaide/ide/base.py

-# -*- coding: utf-8 -*-
-import sys
-import os
-import atexit
-import gettext
-from PyQt4.QtCore import (
-    Qt, SIGNAL, QObject, QCoreApplication, QEvent, QPoint, QSize,
-    QVariant, QTimer)
-from PyQt4.QtGui import (
-    QTabWidget, QTabBar, QDockWidget, QMenu, QToolBar, QAction, QToolButton,
-    QKeySequence, QLabel, QFileDialog, QMouseEvent,
-    QStylePainter, QStyleOptionDockWidget, QStyle)
-
-from codeaide.interface import implements, classproperty
-from codeaide.utils import load_icon
-
-
-def i18n(s):
-    return gettext.lgettext(s).decode("utf-8")
-
-
-
-def call_on_idle(func, *args, **kwargs):
-    QTimer.singleShot(0, lambda :func(*args, **kwargs))
-
-
-
-
-def sorted_by_priority(l):
-    return sorted(l,
-                  cmp=lambda a, b: cmp(b.priority, a.priority))
-
-
-
-class ToolbarManager(object):
-
-
-    def __init__(self, mainwin):
-        self.mainwin = mainwin
-        self.toolbars = {}
-        self.menu = QMenu(mainwin)
-
-
-    def get_toolbar(self, title):
-        tb = self.toolbars.get(title)
-        return tb
-
-
-    def add_toolbar(self, title):
-        tb = QToolBar(title, self.mainwin)
-        tb.setObjectName(title)
-        group = self.mainwin.addToolBar(tb)
-        self.toolbars[title] = tb
-        self.menu.addAction(tb.toggleViewAction())
-        return tb
-
-
-    def get_or_create_toolbar(self, title):
-        tb = self.get_toolbar(title)
-        if not tb:
-            tb = self.add_toolbar(title)
-        return tb
-
-
-    def add_toolbar_action(self, tb_title, action):
-        tb = self.get_or_create_toolbar(tb_title)
-        tb.addAction(action)
-
-
-
-class MenuManager(object):
-
-
-    def __init__(self, menubar):
-        self.menubar = menubar
-        self.menus = {}
-
-
-    def get_menu(self, title):
-        menu = self.menus.get(title)
-        return menu
-
-
-    def add_menu(self, title):
-        menu = QMenu(title, self.menubar)
-        self.menubar.addMenu(menu)
-        self.menus[title] = menu
-        return menu
-
-
-    def get_or_create_menu(self, title):
-        menu = self.get_menu(title)
-        if not menu:
-            menu = self.add_menu(title)
-        return menu
-
-
-    def add_menu_action(self, menu_title, item_action):
-        menu = self.get_or_create_menu(menu_title)
-        menu.addAction(item_action)
-
-
-
-
-
-class CommandBase(object):
-
-    title = None
-    menu = None
-    shortcut = None
-    icon = None
-    toolbar = None
-    status_tip = None
-    whats_this = None
-    statusbar = False
-    priority = 0
-
-
-    def __init__(self, parent):
-        self.action = QAction(parent)
-        if self.title:
-            self.action.setText(self.title)
-        if self.icon:
-            self.action.setIcon(load_icon(self.icon))
-        if self.shortcut:
-            self.action.setShortcut(QKeySequence(self.shortcut))
-        if self.status_tip:
-            self.action.setStatusTip(self.status_tip)
-        if self.whats_this:
-            self.action.setWhatsThis(self.whats_this)
-        if self.menu:
-            parent.menu_manager.add_menu_action(self.menu, self.action)
-        if self.toolbar:
-            parent.toolbar_manager.add_toolbar_action(self.toolbar, self.action)
-        if self.statusbar:
-            parent.statusbar_manager.add_action(self.action)
-        if not self.toolbar and not self.menu:
-            parent.addAction(self.action)
-        self.parent = parent
-        self.action.connect(self.action, SIGNAL("triggered()"), self.execute)
-        self.init()
-
-
-    def init(self):
-        pass
-
-    def execute(self):
-        raise NotImplementedError, self.execute
-
-
-
-class DocumentCommandBase(CommandBase):
-
-
-    def __init__(self, parent):
-        CommandBase.__init__(self, parent)
-        self.doc = None
-        parent.connect(parent.window(), SIGNAL("active_document_changed(PyQt_PyObject)"), self.on_active_document_changed)
-
-
-    def check_enabled(self):
-        return True
-
-
-    def on_active_document_changed(self, doc):
-        self.doc = doc
-        if doc is None:
-            is_enabled = False
-        else:
-            is_enabled = self.check_enabled()
-        self.action.setEnabled(is_enabled)
-
-
-
-
-
-class CheckCommandBase(CommandBase):
-
-    checked = False
-
-    def __init__(self, parent):
-        CommandBase.__init__(self, parent)
-        self.action.setCheckable(True)
-        self.action.setChecked(self.checked)
-
-
-
-_installed_filters = []
-
-
-class TitleBar(QLabel):
-
-    def __init__(self, *args):
-        QLabel.__init__(self, *args)
-        self.setFixedHeight(2)
-
-
-    def sizeHint(self):
-        return QSize(2,2)
-
-
-    def minimumSizeHint(self):
-        return QSize(2,2)
-
-
-
-class DockWidget(QDockWidget):
-
-    def __init__(self, *args):
-        QDockWidget.__init__(self, *args)
-        self._titlebar = TitleBar(self)
-        self.setTitleBarWidget(self._titlebar)
-        self.visibilityChanged.connect(self.on_visibility_changed)
-        self.setStyleSheet("""
-         QDockWidget {
-             border: 1px solid darkgrey;
-         }
-
-         QDockWidget::title {
-             text-align: left;
-             background: lightgrey;
-             padding-left: 35px;
-         }
-
-        """)
-
-
-    def restore_titlebar(self):
-        self.setTitleBarWidget(None)
-
-
-    def hide_titlebar(self):
-        self.setTitleBarWidget(self._titlebar)
-
-
-    def style_tabbar(self, tab):
-        tab.setStyleSheet("""
-        /* Style the tab using the tab sub-control. Note that it reads QTabBar _not_ QTabWidget */
-        QTabBar {
-            background-color: lightgrey;
-        }
-        QTabBar::tab {
-            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
-            stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
-            stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
-            border: 1px solid #C4C4C3;
-            border-bottom-color: #C2C7CB; /* same as the pane color */
-            border-top-left-radius: 4px;
-            border-top-right-radius: 4px;
-            min-width: 8ex;
-            padding: 2px;
-        }
-
-        QTabBar::tab:selected, QTabBar::tab:hover {
-            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
-            stop: 0 #fafafa, stop: 0.4 #f4f4f4,
-            stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);
-        }
-
-        QTabBar::tab:selected {
-            border-color: #9B9B9B;
-            border-bottom-color: #C2C7CB; /* same as pane color */
-        }
-
-        QTabBar::tab:!selected {
-            margin-top: 2px; /* make non-selected tabs look smaller */
-        }
-        """)
-
-
-    def on_visibility_changed(self, is_visible):
-        tab = self.dock_tab(self)
-        if tab:
-            if not tab in _installed_filters:
-                tab.installEventFilter(self)
-                tab.setTabsClosable(True)
-                tab.tabCloseRequested.connect(self.on_tab_close_request)
-                _installed_filters.append(tab)
-                self.style_tabbar(tab)
-            if not self.titleBarWidget():
-                QTimer.singleShot(0, self.hide_titlebar)
-        else:
-            if self.titleBarWidget():
-                QTimer.singleShot(0, self.restore_titlebar)
-
-
-                
-    def on_tab_close_request(self, index):
-        tab = self.sender()
-        title = tab.tabText(index)
-        for child in self.parent().children():
-            if isinstance(child, QDockWidget):
-                if child.windowTitle() == title:
-                    child.close()
-                    return
-                    
-        
-
-    def dock_tab(self, dock):
-        title = dock.windowTitle()
-        for child in self.parent().children():
-            if isinstance(child, QTabBar):
-                for i in range(child.count()):
-                    if child.tabText(i) == title:
-                        return child
-
-
-    def tab_dock(self, tab):
-        title = tab.tabText(tab.currentIndex())
-        for child in self.parent().children():
-            if isinstance(child, QDockWidget):
-                if child.windowTitle() == title:
-                    return child
-
-
-    def eventFilter(self, obj, event):
-        if isinstance(obj, QTabBar) and isinstance(event, QMouseEvent):
-            ev_type = event.type()
-            if ev_type == QEvent.MouseButtonPress:
-                pos = event.pos()
-                self._pos = pos
-                if obj.tabRect(obj.currentIndex()).contains(pos):
-                    mev = QMouseEvent(ev_type, QPoint(1, 1),
-                                      event.button(), event.buttons(), event.modifiers())
-                    dock = self.tab_dock(obj)
-                    QCoreApplication.sendEvent(dock, mev)
-
-            elif ev_type == QEvent.MouseMove:
-                if (event.pos() - self._pos).manhattanLength() > 2:
-                    dock = self.tab_dock(obj)
-                    QCoreApplication.sendEvent(dock, event)
-
-        return QDockWidget.eventFilter(self, obj, event)
-
-
-
-
-class DockBase(QObject):
-
-    title = None
-    area = Qt.BottomDockWidgetArea
-    toggle_menu = None
-    toggle_shortcut = None
-    icon = None
-    toolbar = None
-    statusbar = False
-    priority = 0
-    switch_shortcut = None
-
-
-    def __init__(self, parent):
-        QObject.__init__(self, parent)
-
-
-    def create_widget(self, parent):
-        raise NotImplementedError, self.create_widget
-
-
-    def switch_to(self):
-        self.widget.show()
-        self.widget.widget().setFocus()
-
-
-    def set_focus(self, flag):
-        if flag:
-            self.widget.widget().setFocus()
-
-
-
-class DockManager(object):
-
-
-    dockwidget_factory = DockWidget
-
-
-    def __init__(self, mainwin):
-        self.mainwin = mainwin
-        mainwin.setTabPosition(Qt.AllDockWidgetAreas, QTabWidget.North)
-        mainwin.setDockNestingEnabled(True)
-        mainwin.setCorner(Qt.TopLeftCorner, Qt.LeftDockWidgetArea)
-        mainwin.setCorner(Qt.TopRightCorner, Qt.RightDockWidgetArea)
-        mainwin.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea)
-        mainwin.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea)
-        self.menu = QMenu(mainwin)
-        self.docks = []
-        self.widgets = []
-
-
-    def create_widget(self, dock):
-        child_widget = dock.create_widget(dock.widget)
-        if dock.switch_shortcut:
-            dock.switch_action = sa = QAction(self.mainwin)
-            sa.setText(i18n("Switch to %s") % dock.title)
-            sa.setShortcut(QKeySequence(dock.switch_shortcut))
-            sa.connect(sa, SIGNAL("triggered()"), dock.switch_to)
-            self.mainwin.addAction(sa)
-        dock.widget.setWidget(child_widget)
-        self.widgets.append(child_widget)
-
-
-    def add_dockwidget(self, dock):
-        dock.widget = self.dockwidget_factory(self.mainwin)
-        cls_name = dock.__class__.__name__
-        dock.widget.setObjectName(cls_name)
-        dock.widget.setWindowTitle(dock.title or cls_name)
-        call_on_idle(self.create_widget, dock)
-        #self.create_widget(dock)
-        if dock.statusbar:
-            self.mainwin.statusbar_manager.add_action(dock.widget.toggleViewAction())
-
-        self.mainwin.addDockWidget(dock.area, dock.widget)
-
-        action = dock.widget.toggleViewAction()
-        if dock.icon:
-            action.setIcon(load_icon(dock.icon))
-        if dock.toggle_shortcut:
-            action.setShortcut(QKeySequence(dock.toggle_shortcut))
-        if dock.toggle_menu:
-            self.mainwin.menu_manager.add_menu_action(dock.toggle_menu, action)
-        if dock.toolbar:
-            self.mainwin.toolbar_manager.add_toolbar_action(dock.toolbar, action)
-
-        self.docks.append(dock)
-        self.menu.addAction(dock.widget.toggleViewAction())
-        action.connect(action, SIGNAL("triggered(bool)"), dock.set_focus)
-
-
-class StatusbarManager(object):
-
-
-    def __init__(self, mainwin):
-        self.mainwin = mainwin
-        self.bar = mainwin.statusBar()
-        self.labels = []
-        self.widgets = {}
-
-
-    def __setitem__(self, name, value):
-        if name not in self.widgets:
-            self.add_label(name)
-        self.widgets[name].setText(value)
-
-
-    def show_message(self, msg):
-        self.bar.showMessage(msg)
-
-
-    def add_label(self, name, stretch=0):
-        l = QLabel(self.bar)
-        self.labels.append(name)
-        self.add_widget(name, l, stretch)
-
-
-    def add_widget(self, name, widget, stretch=0):
-        self.widgets[name] = widget
-        self.bar.addWidget(widget, stretch)
-        #self.reformat()
-
-
-    def add_action(self, action, name=None):
-        widget = QToolButton(self.bar)
-        widget.setDefaultAction(action)
-        name = name or widget.objectName()
-        self.add_widget(name, widget)

File codeaide/ide/simple/__init__.py

-# -*- coding: utf-8 -*-
-from codeaide.ide.simple.base import Application
-
-# discover classes via Interface
-import codeaide.ide.simple.commands
-import codeaide.ide.simple.python
-import codeaide.ide.simple.help

File codeaide/ide/simple/base.py

-# -*- coding: utf-8 -*-
-import sys
-import os
-
-from PyQt4.QtCore import (
-   QSettings, QSignalMapper, SIGNAL, QTimer, QVariant)
-from PyQt4.QtGui import (
-   QApplication, QSplashScreen, qApp, QMainWindow, QTabWidget, QColor, QImage, QPixmap)
-
-   
-from codeaide import icon_path
-from codeaide.interface import implements, on_hook
-from codeaide.ide import api
-from codeaide.ide.base import (
-   sorted_by_priority, MenuManager, ToolbarManager, StatusbarManager, DockManager)
-from codeaide.ide.simple.utils import call_on_idle
-
-
-
-class Settings(QSettings):
-    implements(api.Settings)
-
-    
-    def __init__(self, parent):
-        QSettings.__init__(self, parent)
-
-        
-    @property
-    def keys(self):
-        return [unicode(k) for k in self.allKeys()]
-
-
-    def set(self, key, value):
-        self.setValue(key, QVariant(repr(value)))
-        self.sync()
-
-    
-    def get(self, key, default=None):
-        val = self.value(key).toPyObject()
-        if not val:
-            return default
-        try:
-            return eval(str(val))
-        except Exception, e:
-            print key, e, val
-            
-
-
-def app():
-    return api.Application.instance
-
-
-def win():
-    return app().active_window
-
-
-def view():
-    return win().active_view
-
-
-def doc():
-    return view().active_document
-
-
-
-
-class Application(QApplication):
-    implements(api.Application)
-
-    organisation_name = "cosmos-tools"
-    application_name = "codeaide"
-
-
-    def __init__(self):
-        QApplication.__init__(self, sys.argv)
-        self.setApplicationName("CodeAide")
-        self.setOrganizationName(self.organisation_name)
-        self.setApplicationName(self.application_name)
-        self.setStyleSheet("QMainWindow::separator { height:2px; width:2px;}")
-        #self.connect(self, SIGNAL("lastWindowClosed()"), self._force_quit)
-        self.settings = api.Settings(self)
-        self._main_window = None
-        self._project = api.Project()
-        
-        
-    @property
-    def active_project(self):
-        return self._project
-
-
-    @property
-    def active_window(self):
-        return self._main_window
-
-    
-    def quit(self, force=False):
-        if on_hook(api.OnQuit) and not force:
-            return
-        self._main_window.close()
-
-
-    def setup(self):
-        self._main_window = self.create_main_window()
-
-
-    def start(self):
-        if on_hook(api.OnStart):
-            return False
-        if not self._main_window:
-            self.setup()
-        self._main_window.show()
-        if on_hook(api.OnReady):
-            return False
-        return True
-
-
-    def run(self):
-        if not self._main_window:
-            if not self.start():
-                return
-        if self._main_window:
-            return self.exec_()
-
-
-    def _create_splash(self, show=True):
-        splash = QSplashScreen()
-        if show:
-            img = QImage(os.path.join(icon_path, "splash.png"))
-            pm = QPixmap.fromImage(img)
-            if not pm.mask():
-                if img.hasAlphaBuffer():
-                    bm = img.createAlphaMask()
-                else:
-                    bm = img.createHeuristicMask()
-                pm.setMask(bm)
-            if pm.mask():
-                splash.setMask(pm.mask())
-            splash.setPixmap(pm)
-            splash.show()
-        return splash
-
-
-    def create_main_window(self):
-        self.splash = self._create_splash()
-        win = api.MainWindow()
-        #self.splash.finish(win)
-        QTimer.singleShot(1000, self.splash.close)
-        win.setup()
-        return win
-
-
-
-class MainWindow(QMainWindow):
-    implements(api.MainWindow)
-
-
-    def __init__(self):
-        QMainWindow.__init__(self)
-
-
-    def setup(self):
-        self._setup_ui()
-        self._restore_settings()
-
-
-    def _restore_settings(self):
-        self.settings = app().settings
-        sb = self.settings.get("statusbar", True)
-        self.statusBar().setVisible(sb)
-        state = self.settings.get("state", None)
-        if state:
-            self.restoreState(state)
-        geom = self.settings.get("geometry", None)
-        if geom:
-            self.restoreGeometry(geom)
-        
-            
-    def closeEvent(self, event):
-        self._view._save_settings()
-        self._save_settings()
-
-
-    def _save_settings(self):
-        geom = (self.x(), self.y(), self.width(), self.height())
-        self.settings.set("geometry", str(self.saveGeometry()))
-        self.settings.set("state", str(self.saveState()))
-        self.settings.set("statusbar", self.statusBar().isVisible())
-
-
-    def _setup_ui(self):
-        self.setWindowTitle("[*] %s" % qApp.applicationName())
-        self.setDocumentMode(True)
-        self.mapper = QSignalMapper(self)
-        self.connect(self.mapper, SIGNAL("mappend(QWidget*)"), self.set_active_view)
-        self.menu_manager = MenuManager(self.menuBar())
-        self.toolbar_manager = ToolbarManager(self)
-        self.dock_manager = DockManager(self)
-        self.statusbar_manager = StatusbarManager(self)
-        self._view = self.create_view()
-        self.setCentralWidget(self._view)
-        self._setup_commands()
-        self._setup_dockwidgets()
-        rect = qApp.desktop().availableGeometry(self)
-        self.setGeometry(rect)
-
-
-    def _setup_commands(self):
-        self._commands = [
-             cmd(self) for cmd in sorted_by_priority(api.Command.implementations)
-             ]
-
-
-    def _setup_dockwidgets(self):
-        self._docks = []
-        for dock_class in api.Dock.implementations:
-            dock = dock_class(self)
-            self.dock_manager.add_dockwidget(dock)
-            self._docks.append(doc)
-
-
-    def create_view(self):
-        view = api.View(self)
-        #call_on_idle(view.open_filename, __file__.rstrip("co"))
-        return view
-
-
-    @property
-    def active_view(self):
-        return self._view
-
-
-    
-    def set_active_view(self, doc):
-        self._view.set_active(doc)
-
-
-
-
-        
-class View(QTabWidget):
-    implements(api.View)
-
-    def __init__(self, parent):
-        QTabWidget.__init__(self)
-        call_on_idle(self.setup_ui)
-      
-
-    def setup_ui(self):
-        self.setDocumentMode(True)
-        self.setMovable(True)
-        self.setTabsClosable(True)
-        self.connect(self, SIGNAL("currentChanged(int)"), self.on_current_changed)
-        self.connect(self, SIGNAL("tabCloseRequested(int)"), self.on_close_request)
-        self._tabs = []
-        self._restore_settings()
-        for filename in sys.argv[1:]:
-            call_on_idle(self.open_filename, filename)
-
-        
-    def _save_settings(self):
-        editors = []
-        for edit in self._tabs:
-            doc = edit.document()
-            editors.append(dict(filename=doc.filename, pos=edit.textCursor().position()))
-        self.settings.set("editors", editors)
-        self.settings.set("active-editor", self.currentIndex())
-
-
-    def _restore_settings(self):
-        self.settings = app().settings
-        editors = self.settings.get("editors", [])
-        for edit in editors:
-            try:
-                call_on_idle(self.open_filename, edit["filename"], edit["pos"])
-            except Exception, e:
-                print e, edit
-        if editors:
-            try:
-                active = self.settings.get("active-editor", 0)
-                call_on_idle(self._set_active, active)
-            except Exception, e:
-                print e, editors
-    
-
-    def _set_active(self, i):
-        self.setCurrentIndex(i)
-        editor = self.currentWidget()
-        if editor:
-            QTimer.singleShot(500, editor.setFocus)
-
-                
-    def on_current_changed(self, i):
-        edit = self.currentWidget()
-        self.window().setWindowTitle("")
-        if edit:
-            doc = edit.document()
-            self.connect(doc, SIGNAL("modificationChanged(bool)"), self.on_modification_change)
-            self.window().setWindowModified(doc.isModified())
-            self.window().setWindowFilePath(self.tabText(i))
-        self.window().emit(SIGNAL("active_document_changed(PyQt_PyObject)"), edit)
-
-
-    def on_modification_change(self, flag):
-        i = self.currentIndex()
-        if flag:
-            self.tabBar().setTabTextColor(i, QColor("blue"))
-        else:
-            self.tabBar().setTabTextColor(i, QColor("black"))
-
-        
-    @property
-    def active_document(self):
-        edit = self.currentWidget()
-        if edit:
-            return edit.document()
-
-
-    def set_active(self, doc):
-        self.setCurrentWidget(doc)
-
-    
-    def _new(self, title="unnamed"):
-        editor = self._create_editor()
-        self._tabs.append(editor)
-        self.addTab(editor, title)
-        self.setCurrentWidget(editor)
-        editor.setFocus()
-        editor.new_buffer()
-        editor.connect(editor, SIGNAL("cursorPositionChanged()"), self.on_cursor_position_changed)
-        return editor
-
-
-    def _create_editor(self):
-        return api.Editor(self)
-
-
-    def new_filename(self, filename="unnamed.py"):
-        editor = self._new(os.path.basename(filename))
-        return editor
-
-
-    def open_filename(self, filename, pos=0):
-        if not filename:
-            return 
-        if not os.path.exists(filename) or os.path.isdir(filename):
-            self.statusbar_manager.show_message(i18n("%s does not exist") % filename)
-            return
-        editor = self._new(os.path.basename(filename))
-        editor.load_buffer(filename)
-        editor.set_position(pos)
-        qApp.processEvents()
-        return editor
-
-
-    def save_filename(self, filename=None):
-        filename = filename or self.active_document.filename
-        textedit = self.currentWidget()
-
-    
-    def on_close_request(self, num):
-        edit = self.widget(num)
-        #edit.document().close()
-        self.removeTab(num)
-        del self._tabs[num]
-
-
-    def on_cursor_position_changed(self):
-        textedit = self.currentWidget()
-        self.window().statusbar_manager["pos"] = "R%s C%s" % (textedit.row+1, textedit.column+1)
-
-
-    def close_active(self):
-        self.on_close_request(self.currentIndex())
-
-    
-
-
-        
-from codeaide.editors import CodeEditor
-
-class Editor(CodeEditor):
-    implements(api.Editor)
-
-
-    def __init__(self, parent):
-        CodeEditor.__init__(self)
-
-
-
-        
-class Project(object):
-    implements(api.Project)
-
-    @property
-    def root_path(self):
-        return os.getcwd()
-
-    

File codeaide/ide/simple/commands.py

-# -*- coding: utf-8 -*-
-import os
-import re
-
-from PyQt4.QtCore import SIGNAL, Qt
-from PyQt4.QtGui import QInputDialog
-
-from codeaide.interface import implements
-from codeaide.ide import api
-from codeaide.ide.base import i18n, CommandBase, CheckCommandBase, DocumentCommandBase
-from codeaide.ide.simple.utils import open_filename, save_filename, confirm_close
-
-
-def app():
-    return api.Application.instance
-
-
-def win():
-    return app().active_window
-
-
-def view():
-    return win().active_view
-
-
-def doc():
-    return view().active_document
-
-
-
-
-
-    
-class SessionRestore(object):
-    implements(api.OnReady)
-    
-    def execute(self):
-        for obj in api.Session.objects:
-            obj.restore_session()
-        for obj in api.SimpleSession.objects:
-            session_properties = getattr(obj, "session_properties", [])
-
-    
-class SessionSaver(object):
-    implements(api.OnQuit)
-    
-    def execute(self):
-        for obj in api.Session.objects:
-            obj.save_session()
-        for obj in api.SimpleSession.objects:
-            session_properties = getattr(obj, "session_properties", [])
-    
-
-    
-class SaveBeforeClose(object):
-    implements(api.OnQuit)
-    
-    def execute(self):
-        # for doc in ...
-        pass
-
-
-
-class FileNewCommand(CommandBase):
-    implements(api.Command)
-
-    title = i18n("&New")
-    menu = i18n("&File")
-    shortcut = i18n("Ctrl+N")
-    icon = "document-new"
-    toolbar = i18n("Main")
-
-
-    def execute(self):
-        view().new_filename()
-
-
-
-
-class FileOpenCommand(CommandBase):
-    implements(api.Command)
-
-    title = i18n("&Open")
-    menu = i18n("&File")
-    shortcut = i18n("Ctrl+O")
-    icon = "document-open"
-    toolbar = i18n("Main")
-
-    def execute(self):
-        filename = open_filename()
-        if filename:
-            view().open_filename(filename)
-
-            
-
-class FileSaveCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Save")
-    menu = i18n("&File")
-    shortcut = i18n("Ctrl+S")
-    icon = "document-save"
-    toolbar = i18n("Main")
-    
-    
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("modificationChanged(bool)"), self.action.setEnabled)
-        return self.doc.document().isModified()
-
-
-    def execute(self):
-        filename = self.doc.document().filename
-        print "saving", repr(filename)
-        self.doc.save_buffer(filename)
-
-
-
-class FileSaveAsCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("Save &as...")
-    menu = i18n("&File")
-    icon = "document-save-as"
-
-    
-    def execute(self):
-        filename = save_filename()
-        if filename:
-            if not filename:
-                return False
-            filename = unicode(filename)
-            self.doc.rename(self.doc.document().filename, filename)
-            self.doc.save_buffer(filename)
-
-
-class FileCloseCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Close")
-    menu = i18n("&File")
-    shortcut = i18n("Ctrl+W")
-    icon = "document-close"
-
-    
-    def execute(self):
-        view().close_active()
-
-
-
-
-class FileQuitCommand(CommandBase):
-    implements(api.Command)
-
-    title = i18n("&Quit")
-    menu = i18n("&File")
-    shortcut = i18n("Ctrl+Q")
-    toolbar = i18n("Main")
-    icon = "application-exit"
-
-
-    def execute(self):
-        app().quit()
-
-
-
-class EditUndoCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Undo")
-    menu = i18n("&Edit")
-    shortcut = i18n("Ctrl+Z")
-    icon = "edit-undo"
-    toolbar = i18n("Edit")
-
-
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("undoAvailable(bool)"), self.action.setEnabled)
-        return self.doc.document().isUndoAvailable()
-
-    def execute(self):
-        self.doc.undo()
-
-        
-class EditRedoCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Redo")
-    menu = i18n("&Edit")
-    shortcut = i18n("Ctrl+Shift+Z")
-    icon = "edit-redo"
-    toolbar = i18n("Edit")
-
-    
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("redoAvailable(bool)"), self.action.setEnabled)
-        return self.doc.document().isRedoAvailable()
-
-    def execute(self):
-        self.doc.redo()
-
-
-
-class EditCutCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("C&ut")
-    menu = i18n("&Edit")
-    shortcut = i18n("Ctrl+X")
-    icon = "edit-cut"
-    toolbar = i18n("Edit")
-
-    
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("copyAvailable(bool)"), self.action.setEnabled)
-        return self.doc.textCursor().hasSelection()
-
-    
-    def execute(self):
-        return self.doc.cut()
-    
-
-    
-class EditCopyCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Copy")
-    menu = i18n("&Edit")
-    shortcut = i18n("Ctrl+C")
-    icon = "edit-copy"
-    toolbar = i18n("Edit")
-
-
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("copyAvailable(bool)"), self.action.setEnabled)
-        return self.doc.textCursor().hasSelection()
-
-    
-    def execute(self):
-        self.doc.copy()
-        
-
-class EditPasteCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Paste")
-    menu = i18n("&Edit")
-    shortcut = i18n("Ctrl+V")
-    icon = "edit-paste"
-    toolbar = i18n("Edit")
-
-    
-    def check_enabled(self):
-        self.doc.connect(self.doc, SIGNAL("pasteAvailable"), self.action.setEnabled)
-        return self.doc.canPaste()
-
-    
-    def execute(self):
-        self.doc.paste()
-        
-    
-
-
-
-class FullscreenCommand(CheckCommandBase):
-    implements(api.Command)
-    implements(api.Session)
-
-    title = i18n("Toggle &fullscreen")
-    menu = i18n("&View")
-    shortcut = i18n("Ctrl+Shift+F")
-    icon = "view-fullscreen"
-    toolbar = i18n("Views")
-
-
-    def restore_session(self):
-        flag = app().settings.get("fullscreen", False)
-        if not flag:
-            self.parent.setWindowState(self.parent.windowState() & Qt.WindowFullScreen)
-        else:
-            self.parent.setWindowState(self.parent.windowState() | Qt.WindowFullScreen)
-        self.action.setChecked(flag)
-    
-
-    def save_session(self):
-        flag = self.parent.windowState() & Qt.WindowFullScreen == Qt.WindowFullScreen
-        app().settings.set("fullscreen", flag)
-
-
-    def execute(self):
-        self.parent.setWindowState(self.parent.windowState() ^ Qt.WindowFullScreen)
-
-        
-        
-        
-        
-class StatusBarCommand(CheckCommandBase):
-    implements(api.Command)
-    implements(api.Session)
-
-    title = i18n("Toggle &status bar")
-    menu = i18n("&View")
-    #toolbar = i18n("Views")
-    checked = True
-
-
-    def restore_session(self):
-        checked = not self.parent.statusBar().isHidden()
-        flag = app().settings.get("statusbar", checked)
-        if not flag:
-            self.parent.statusBar().setVisible(True)
-        else:
-            self.parent.statusBar().setVisible(False)
-        self.action.setChecked(flag)
-    
-
-    def save_session(self):
-        flag = self.parent.statusBar().isHidden()
-        app().settings.set("statusbar", flag)
-
-
-    def execute(self):
-        sb = self.parent.statusBar()
-        sb.setVisible(sb.isHidden())
-
-
-
-class ToolbarsCommand(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("&Toolbars")
-    menu = i18n("&View")
-
-    
-    def init(self):
-        self.action.setMenu(self.parent.toolbar_manager.menu)
-
-
-        
-class DocksCommand(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("&Panels")
-    menu = i18n("&View")
-    
-    def init(self):
-        self.action.setMenu(self.parent.dock_manager.menu)
-
-
-
-        
-class NextBuffer(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("&Next buffer")
-    shortcut = i18n("Ctrl+PgDown")
-    #menu = i18n("&View")
-    
-    def execute(self):
-        i = view().currentIndex() 
-        if i + 1 == view().count():
-            i = -1
-        view().setCurrentIndex(i + 1)
-        view().currentWidget().setFocus()
-
-        
-        
-class PreviousBuffer(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("&Previous buffer")
-    shortcut = i18n("Ctrl+PgUp")
-    #menu = i18n("&View")
-
-
-    def execute(self):
-        i = view().currentIndex() 
-        if i == 0:
-            i =  view().count()
-        view().setCurrentIndex(i - 1)
-        view().currentWidget().setFocus()
-
-
-        
-
-class HelpAboutCommand(CommandBase):
-    implements(api.Command)
-
-    title = i18n("&About")
-    menu = i18n("&Help")
-    shortcut = i18n("F1")
-    icon = "help-about"
-    # keep menu right
-    priority = -1000 
-    
-    def execute(self):
-        app().splash.show()
-
-
-        
-        
-class SourceGotoLine(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("Goto line...")
-    menu = i18n("&Source")
-    shortcut = i18n("Esc,g")
-
-
-    def execute(self):
-        edit = view().currentWidget()
-        (row, ok) = QInputDialog.getInteger(
-           self.parent,
-          "Goto line", "Row number:", 1, 1, edit.blockCount())
-        if ok:
-            edit.set_row_start(row-1)
-
-            
-            
-class SwitchEditor(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("Switch to editor")
-    shortcut = i18n("Ctrl+0")
-
-    
-    def execute(self):
-        view().currentWidget().setFocus() #XXX currenWidget() not part of API
-        
-        
-
-class ToggleEditor(CommandBase):
-    implements(api.Command)
-    
-    title = i18n("Toggle editor")
-    shortcut = i18n("Alt+0")
-    
-    
-    def execute(self):
-        edit = view()
-        visible = not edit.isVisible()
-        edit.setVisible(visible)
-        if visible:
-            edit.currentWidget().setFocus()

File codeaide/ide/simple/help.py

-# -*- coding: utf-8 -*-
-from PyQt4.QtCore import Qt, QUrl
-
-from codeaide.interface import implements
-from codeaide.ide import api
-from codeaide.ide.base import i18n, DockBase
-from codeaide.ide.simple.utils import call_on_idle
-
-
-        
-class HelpDock(DockBase):
-    implements(api.Dock)
-
-    title = i18n("Help")
-    toggle_shortcut = "Alt+1"
-    switch_shortcut = "Ctrl+1"
-    icon = "help-browser"
-    statusbar = True
-    #toggle_menu = i18n("&View")
-    #toolbar = i18n("Views")
-    area = Qt.RightDockWidgetArea    
-
-
-    def create_widget(self, parent):
-        from PyQt4.QtWebKit import QWebView
-
-        class HelpBrowser(QWebView):
-            
-            def __init__(self, parent):
-                QWebView.__init__(self, parent)
-                call_on_idle(self.load, QUrl("http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html"))
-    
-
-        browser = HelpBrowser(parent)
-        browser.resize(300, 300)
-        return browser

File codeaide/ide/simple/python.py

-# -*- coding: utf-8 -*-
-import os
-
-from PyQt4.QtCore import Qt, SIGNAL, QUrl, QDir
-from PyQt4.QtGui import QColor, QTreeWidget, QTreeWidgetItem, QTreeView, QFileSystemModel, QDirModel, QFrame
-
-from codeaide.interface import implements
-from codeaide.ide.base import (
-  i18n, load_icon, DockBase, DocumentCommandBase)
-from codeaide.ide import api
-from codeaide.ide.simple.base import view, doc
-from codeaide.ide.simple.utils import call_on_idle
-
-
-
-class RunCommand(DocumentCommandBase):
-    implements(api.Command)
-
-    title = i18n("&Run in console")
-    menu = i18n("&Run")
-    shortcut = i18n("F5")
-    icon = "run-build"
-    toolbar = i18n("Run")
-
-
-    def execute(self):
-        lines = unicode(doc().toPlainText()).splitlines()
-        for i, l in enumerate(lines):
-            if not l.strip().startswith("#"):
-                break
-            if "-*-coding:" in "".join(l.split()):
-                lines[i] = "# disabled coding"
-        src = "\n".join(lines)
-        ns = {
-             "__file__": (doc().filename or "unnamed.py"),
-             "__name__":"__main__"
-             }
-        # Output goes to console which redirects sys.stdout
-        print "Starting script..."
-        try:
-            exec src in ns
-        except Exception, e:
-            print "Script failed:", e
-            if isinstance(e, SyntaxError):
-                self.doc.set_row_start(e.lineno-1)
-                return
-            import sys, traceback
-            traceback.print_exc()
-            try:
-                etype, value, tb = sys.exc_info()
-                tb = tb.tb_next
-                self.doc.set_row_start(tb.tb_lineno-1)
-            except Exception, e:
-                pass
-            return
-        print "Script done."
-
-
-
-
-class ConsoleDock(DockBase):
-    implements(api.Dock)
-
-    title = i18n("Python Console")
-    toggle_shortcut = "Alt+2"
-    icon = "terminal"
-    statusbar = True
-    #toggle_menu = i18n("&View")
-    #toolbar = i18n("Views")
-    area = Qt.BottomDockWidgetArea
-    switch_shortcut = "Ctrl+2"
-
-
-    def create_widget(self, parent):
-        from codeaide.editors import PythonConsole
-        console = PythonConsole(parent)
-        console.new_buffer()
-        return console
-
-
-
-class OutlineItem(QTreeWidgetItem):
-
-
-    def __init__(self, parent, node):
-        QTreeWidgetItem.__init__(self, parent)
-        kind = node.get_kind()
-        if kind == "function":
-            self.setIcon(0, load_icon("code-function"))
-        elif kind == "class":
-            self.setIcon(0, load_icon("code-class"))
-        else:
-            print "unknown kind", kind
-        name = node.name
-        self.key = "%s.%s" % (parent.key, name)
-        self.setText(0, name)
-        self.node = node
-        self.items = []
-        root = self.treeWidget()
-        eflag = root.is_expanded.get(self.key, True)
-        self.setExpanded(eflag)
-        for child in node.get_children():
-            i = self.__class__(self, child)
-            self.items.append(i)
-            self.addChild(i)
-
-
-
-class OutlineDock(DockBase):
-    implements(api.Dock)
-
-    #toggle_menu = i18n("&View")
-    #toolbar = i18n("Views")
-    title = i18n("Python outline")
-    toggle_shortcut = "Alt+3"
-    switch_shortcut = "Ctrl+3"
-    icon = "view-list-tree"
-    area = Qt.LeftDockWidgetArea
-    statusbar = True
-
-
-    def create_widget(self, parent):
-        self.tree = None
-        self.items = []
-        self.connect(parent.window(), SIGNAL("active_document_changed(PyQt_PyObject)"), self.on_active_document_changed)
-        self.tree = QTreeWidget(parent)
-        self.tree.setFrameStyle(QFrame.NoFrame)
-        self.tree.key = ""
-        self.tree.is_expanded = {}
-        self.tree.setHeaderLabels(["Name"])
-        self.tree.setHeaderHidden(True)
-        self.tree.connect(self.tree, SIGNAL("itemActivated(QTreeWidgetItem*,int)"), self.on_activated)
-        self.tree.connect(self.tree, SIGNAL("itemExpanded(QTreeWidgetItem*)"), self.on_expanded)
-        self.tree.connect(self.tree, SIGNAL("itemCollapsed(QTreeWidgetItem*)"), self.on_collapsed)
-        #self.tree.setRootIsDecorated(False)
-        editor = view().currentWidget()
-        if editor:
-            self.on_active_document_changed(editor)
-        return self.tree
-
-
-    def on_active_document_changed(self, editor):
-        self.editor = editor
-        if self.tree:
-            #self.tree.is_expanded.clear()
-            self.tree.key = str(id(editor))
-            del self.items[:]
-            self.tree.clear()
-            if editor:
-                editor.connect(editor, SIGNAL("structure_changed"), self.update)
-            nodes = getattr(editor, "structure", None)
-            self.update(nodes)
-
-
-    def on_expanded(self, item):
-        self.tree.is_expanded[item.key] = True
-
-
-    def on_collapsed(self, item):
-        self.tree.is_expanded[item.key] = False
-
-
-    def update(self, nodes):
-        del self.items[:]
-        self.tree.clear()
-        if not nodes:
-            return
-        for n in nodes:
-            i = OutlineItem(self.tree, n)
-            self.items.append(i)
-        #self.tree.setColumnWidth(0, 48)
-        self.tree.resizeColumnToContents(0)
-
-
-    def on_activated(self, item, item_col):
-        row = item.node.get_line_number() - 1
-        self.editor.set_row_start(row)
-        self.editor.centerCursor()
-        self.editor.setFocus()
-
-
-
-
-
-
-class FileBrowser(QTreeView):
-
-    def __init__(self, parent):
-        QTreeView.__init__(self, parent)
-        #self.fs_model = QDirModel(self)
-        #self.fs_model.setLazyChildCount(True)
-        #self.fs_model.setNameFilters(["*.py"])
-        self.fs_model = QFileSystemModel()
-        #self.fs_model.setNameFilters(["*.py"])
-        self.fs_model.setFilter(QDir.AllEntries)
-        self.setFrameStyle(QFrame.NoFrame)
-        self.fs_model = QFileSystemModel()
-        self.fs_model.setNameFilters(["*.py"])
-        
-        #self.fs_model.setRootPath(QDir.currentPath())
-        self.fs_model.setRootPath(os.path.abspath(api.Project.instance.root_path))
-        self.fs_model.setNameFilterDisables(True)
-
-        self.setModel(self.fs_model)
-        #self.setCurrentIndex(self.fs_model.index(QDir.currentPath()))
-        #self.setCurrentIndex(self.fs_model.index(QDir.currentPath()))
-        self.setRootIndex(self.fs_model.index(QDir.currentPath()))
-        self.setColumnHidden(1, True)
-        self.setColumnHidden(2, True)
-        self.setColumnHidden(3, True)
-        self.setHeaderHidden(True)
-        self.connect(self, SIGNAL("activated(const QModelIndex&)"), self.on_activated)
-
-
-    def on_activated(self, idx):
-        fn = unicode(self.fs_model.filePath(idx))
-        if not os.path.isdir(fn):
-            print "*", fn
-            view().open_filename(fn)
-
-
-
-class FileDock(DockBase):
-
-
-    implements(api.Dock)
-
-    title = i18n("Filesystem")
-    toggle_shortcut = "Alt+4"
-    switch_shortcut = "Ctrl+4"
-    icon = "system-file-manager"
-    statusbar = True
-    #toggle_menu = i18n("&View")
-    #toolbar = i18n("Views")
-    area = Qt.LeftDockWidgetArea
-
-
-    def create_widget(self, parent):
-        browser = FileBrowser(parent)
-        return browser

File codeaide/ide/simple/utils.py

-#! -*- coding: utf-8 -*-
-from codeaide.ide.base import *
-
-
-
-def confirm_close(doc):
-    if doc.isModified():
-        ret = QMessageBox.warning(
-            self.parent.widget, i18n("Closing file"),
-            i18n("This document has been modified.\n"
-                 "Do you want to save your changes?"),
-            QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
-            QMessageBox.Cancel)
-        if ret == QMessageBox.Cancel:
-            return False
-        elif ret == QMessageBox.Save:
-            pass
-
-
-        
-class FileDialog(object):
-
-
-    def __init__(self, label, filters, path=None, remember=True):
-        self.label = label
-        self.filters = filters
-        self.path = path or os.getcwd()
-        self.remember = remember
-
-
-    def open(self, parent=None):
-        filename = QFileDialog.getOpenFileName(
-            parent, self.label, self.path, self.filters)
-        if filename:
-            filename = os.path.abspath(unicode(filename))
-            if self.remember:
-                self.path = os.path.dirname(filename)
-        return filename
-
-
-    def save(self, parent=None):
-        filename = QFileDialog.getSaveFileName(
-            parent, self.label, self.path, self.filters)
-        if filename:
-            filename = os.path.abspath(unicode(filename))
-            if self.remember:
-                self.path = os.path.dirname(filename)
-        return filename
-
-
-
-
-filename_dialog = FileDialog(i18n("Open file"), "Python Source (*.py *.pyw)")
-open_filename= filename_dialog.open
-save_filename = filename_dialog.save

File codeaide/main.py

     QPlainTextEdit, QPainter, QColor,
     QTextBlockUserData, QTextDocument, QPlainTextDocumentLayout, 
     QAbstractSlider, QScrollBar,
-    QMenu)
+    QMenu, QTextCursor)