示例#1
0
    def __init__(self, parent):
        QWidget.__init__(self)
        self.parent = parent
        l = QGridLayout()
        self.setLayout(QVBoxLayout())
        self.layout().addLayout(l)
        self.api = API()
        #        newpanel.layout().addWidget(QWidget().setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        l.addWidget(QLabel('Title:'), 0, 0)
        self.title = QLineEdit()
        l.addWidget(self.title, 0, 1)
        l.addWidget(QLabel('Template:'), 1, 0)
        self.cb = QComboBox()
        self.cb.addItems(os.listdir(self.api.CWD + 'templates/html'))
        l.addWidget(self.cb, 1, 1)

        self.iconpath = API().icons['newPage']
        icon = QPixmap(self.iconpath)
        iv = QLabel()
        iv.setPixmap(icon)
        l.addWidget(iv, 2, 0)
        self.icon = iv

        chi = QPushButton('Change')
        l.addWidget(chi, 2, 1)
        l.setAlignment(Qt.AlignTop)
        chi.clicked.connect(self.chi)

        apply = QPushButton('Apply')
        l.addWidget(apply, 3, 1)
        l.setAlignment(Qt.AlignTop)
        apply.clicked.connect(self.apply)

        self.title.returnPressed.connect(self.apply)
示例#2
0
def start():
    global ui
    ui.show()
    api = API()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)
示例#3
0
def start():
    global ui
    ui.show()
    api = API()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)
示例#4
0
def main():
    qtapp = QApplication(sys.argv)
    api = API()
    ui = UI(qtapp)

    ui.show()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)
    qtapp.exec_()
示例#5
0
文件: raven.py 项目: averrin/demesne
def main():
    qtapp = QApplication(sys.argv)
    api = API()
    ui = UI(qtapp)

    ui.show()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)
    qtapp.exec_()
示例#6
0
def start():
    global ui
    if ui.config.options.maximized:
        ui.showMaximized()
    else:
        ui.show()
    api = API()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)

    ui.mainWidget.view.js('$.ajax("/settings")')
示例#7
0
def start():
    global ui
    if ui.config.options.maximized:
        ui.showMaximized()
    else:
        ui.show()
    api = API()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)

    ui.mainWidget.view.js('$.ajax("/settings")')
示例#8
0
 def _afterInit(self):
     '''
         when application totally init
     '''
     self.api = API()
     self.view = self.app.mainWidget.view
     self.icons = loadIcons(CWD + 'static/icons/')
示例#9
0
    def __init__(self, parent):
        self.parent = parent
        WinterLine.__init__(self, parent.parent, 'Input command:')
        self.commands = {'tree': SBAction.objects.get(title='Content').forceShowWidget, 'new': self.parent.newPage,
                         'del': self.parent.tree.delPage, 'crypt': self.parent.tree.crypt,
                         'decrypt': self.parent.tree.decrypt, 'edit': SBAction.objects.get(title='Edit').forceShowWidget
            , 'ins': lambda *x: self.parent.tree.newPage(x, self.parent.tree.currentPage.path),
                         'view': self.parent.tree.viewPage}

        cc = [':%s' % c for c in self.commands]
        for page in Page.objects.all():
            cc.append(':view %s' % page.title)
        self.setComplete(cc)
        self.lineEditCompleter.setCompletionMode(QCompleter.InlineCompletion)

        self.api = API()
示例#10
0
    def newPage(self, title, root, template='', iconpath=''):
        if type(title).__name__ == 'tuple':
            title = title[0]

        content = ''
        if re.match('(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?', title):
            content, title = self.get_text(title)
            iconpath = API().icons['cloud']
        path = '%s/%s' % (root, title)
        try:
            os.mkdir(path)
            success = True
        except OSError, e:
            API().error(e)
            API().dialog('warning', 'Dublicate page name', 'Can\'t create new page. Plz change page title.')
            success = False
示例#11
0
    def calc(self, start, end):
        self.last_corner = False
        self.append(start)
        p3 = self.findWaypoint(end, start)
        self.append(p3)
        p4 = ''
        n = 0
        while p3 and end != p3 and n < 20 and p3 != p4:
            p4 = p3
            if p3 != self[-1]:
                self.append(p3)

            p3 = self.findWaypoint(end, p3)
            n += 1

        if p3 and n < 20:
            self.append(p3)
            self.findWaypoint(end, p3)
        self.last_corner = False

        s = self.smooth()
        while not s:
            s = self.smooth()

        if self[-1] != end:
            API().error('Pathfinding failed!')
示例#12
0
    def refresh(self):
        out = StringIO()
        compiler.Compiler(StringIO(str(self.parent.editor.text().toUtf8())), out).compile()
        static = 'file://' + self.api.CWD + 'templates/static'
        path = 'file://' + self.parent.tree.currentPage.path
        try:
            content = Template(out.getvalue()).substitute(static=static, path=path)
        except:
            content = out.getvalue()

        if hasattr(self.parent.tree.currentPage, 'config') and hasattr(self.parent.tree.currentPage.config, 'template'):
            tpl = self.parent.tree.currentPage.config.template
        else:
            tpl = API().config.options.app.default_template
        with file(self.api.CWD + 'templates/html/%s' % tpl) as f:
            page = Template(f.read()).substitute(static=static, content=content, path=path)

        enc = BeautifulSoup(page).originalEncoding
        print enc
        if enc is None:
            enc = 'utf8'

        content = page.decode(enc)

        if enc == 'ISO-8859-2':
            content = page.decode('cp1251')

        self.setHtml(content)
        self.js('reloadStylesheets()')
示例#13
0
def main():
    qtapp = QApplication(sys.argv)
    qtTranslator = QTranslator()
    if qtTranslator.load(CWD+"lang/%s.qm" % QLocale.system().name()):
        qtapp.installTranslator(qtTranslator)
        print QLocale.system().name(), qtapp.tr('Translate loaded')
    ui = UI(qtapp)

    ui.showMaximized()
    api = API()

    endtime = datetime.now()
    delta = endtime - starttime
    api.info('Initialization time: %s' % delta)

    print 'Started'
    qtapp.exec_()
示例#14
0
文件: core.py 项目: averrin/demesne
 def _afterInit(self):
     """
         when application totally init
     """
     self.api = API()
     self.api.ex = self.app.getMethod
     self.api.config = self.app.config
     self.main()
示例#15
0
 def _afterInit(self):
     """
         when application totally init
     """
     self.api = API()
     self.api.ex = self.app.getMethod
     self.api.config = self.app.config
     self.main()
示例#16
0
    def __init__(self, parent):
        QTreeWidget.__init__(self, parent)
        import gdata
        import gdata.docs.client

        client = gdata.docs.client.DocsClient()
        client.ClientLogin('*****@*****.**', 'oWertryN8..//vim', API().config.info.title)
        self.feed = client.GetDocList()
        self.fill()
示例#17
0
    def __init__(self, parent):
        QWidget.__init__(self)
        self.parent = parent
        self.api = API()
        l = QGridLayout()
        self.setLayout(QVBoxLayout())
        self.layout().addLayout(l)
        #        newpanel.layout().addWidget(QWidget().setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        l.addWidget(QLabel('Title:'), 0, 0)
        self.title = QLineEdit()
        l.addWidget(self.title, 0, 1)
        l.addWidget(QLabel('Template:'), 1, 0)
        self.cb = QComboBox()
        self.cb.addItems(os.listdir(self.api.CWD + 'templates/html'))
        l.addWidget(self.cb, 1, 1)

        self.iconpath = API().icons['newPage']
        icon = QPixmap(self.iconpath)
        iv = QLabel()
        iv.setPixmap(icon)
        l.addWidget(iv, 2, 0)
        self.icon = iv

        chi = QPushButton('Change')
        l.addWidget(chi, 2, 1)
        l.setAlignment(Qt.AlignTop)
        chi.clicked.connect(self.chi)

        create = QPushButton('Create')
        l.addWidget(create, 3, 1)
        l.setAlignment(Qt.AlignTop)
        create.clicked.connect(self.new)

        tpl = os.listdir(self.api.CWD + 'templates/html')
        tpl = tpl.index(API().config.options.app.default_template)
        self.cb.setCurrentIndex(tpl)

        self.title.returnPressed.connect(self.new)
示例#18
0
class CommandLine(WinterLine):
    def __init__(self, parent):
        self.parent = parent
        WinterLine.__init__(self, parent.parent, 'Input command:')
        self.commands = {'tree': SBAction.objects.get(title='Content').forceShowWidget, 'new': self.parent.newPage,
                         'del': self.parent.tree.delPage, 'crypt': self.parent.tree.crypt,
                         'decrypt': self.parent.tree.decrypt, 'edit': SBAction.objects.get(title='Edit').forceShowWidget
            , 'ins': lambda *x: self.parent.tree.newPage(x, self.parent.tree.currentPage.path),
                         'view': self.parent.tree.viewPage}

        cc = [':%s' % c for c in self.commands]
        for page in Page.objects.all():
            cc.append(':view %s' % page.title)
        self.setComplete(cc)
        self.lineEditCompleter.setCompletionMode(QCompleter.InlineCompletion)

        self.api = API()

    def shortcut(self, text):
        self.setText(text)
        self.setFocus()


    def checkLine(self):
        ln = str(self.text().toUtf8()).split(' ')[0]
        if ln[1:] in self.commands:
            return True
        return False

    def _command(self):
        ln = str(self.text().toUtf8()).split(' ')
        try:
            self.commands[ln[0][1:]](*ln[1:])
            self.clear()
            self.setStyleSheet('')
        except KeyError:
            self.api.error('No such command')
示例#19
0
    def apply(self):
        page = self.parent.tree.currentPage
        page.config.title = str(self.title.text().toUtf8())
        page.config.template = str(self.cb.currentText().toUtf8())
        page.prefs.save(file(page.path + '/__page.cfg', 'w'))

        if self.iconpath != page.path + '/__icon.png':
            shutil.copyfile(self.iconpath, page.path + '/__icon.png')
        self.parent.tree.fill()

        API().showMessage('%s saved' % page.title)
        SBAction.objects.get(title='Content').forceShowWidget()
        page = Page.objects.get(path=page.path)
        self.parent.tree.ic(page.item, 0)
        self.parent.toggle(1)
示例#20
0
    def __init__(self, parent=None):
        self.parent = parent
        QStackedWidget.__init__(self)
        self.view = View(self)
        self.api = API()

        self.editor = Editor(self.parent, self.api.CWD + "organizer/__page.text")
        self.editor.editor.textChanged.connect(self.pageChanged)
        self.editor.panel = self
        #            self.editor.editor.setCompleter()

        s = CustomStyle
        font = self.api.config.options.qsci.font
        font_size = self.api.config.options.qsci.font_size
        styles = [s('Default', '.*', self.parent.config.options.qsci.fg_color, font),
                  s('Numbers', '(\d+)', '#e33100', font, font_size),
                  s('Tag', '(\%\w+)', '#3366cc', font, font_size, bold=True),
                  s('Class', '\.([\w]+)', '#9c3', font, font_size, bold=True, offset=1),
                  s('Id', '\#([\w]+)', '#e33100', font, font_size, bold=True, offset=1),
                  s('Html', '(<.*?>)', '#3366cc', font, font_size, bold=True),
                  s('Variable', '(\$\w+)', 'violet', font, font_size, bold=True),
                  s('URL',
                      '((http|https|ftp):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)',
                      'darkcyan', font, font_size, italic=True),
                  s('Attrs', '(\{.*\})', 'darkgreen', font, font_size, bold=True),
                  s('DQuotes', '\"(.*?)\"', '#e33100', font, font_size, italic=True, offset=1),
                  s('SQuotes', '\'(.*?)\'', '#e33100', font, font_size, italic=True, offset=1),


                  s('Punct', '([\.#\'\"])', '#c93', font, font_size, bold=True),
                  s('Comment', '(-#.*$)', '#8c8c8c', font, font_size, italic=True),
                  ]

        lexer = CustomLexer(self.editor, styles)
        self.editor.editor.setLexer(lexer)
        self.addWidget(self.editor)

        self.view.setHtml('Something wrong=(')
        self.addWidget(self.view)

        Atoggle = QAction('Toggle', self)
        Atoggle.setShortcut('F4')
        Atoggle.triggered.connect(self._toggle)
        self.addAction(Atoggle)
示例#21
0
def showRavenor(ui):
    sys.path.append('../Ravenor')
    import raven
    from winterstone.base import WinterConfig
    from config import ConfigMerger

    raven.API().CWD += '../Ravenor/'
    ravenconfig = WinterConfig(file(raven.API().CWD + 'config/main.cfg'))
    darniconfig = WinterConfig(file(CWD + 'config/main.cfg'))
    merger = ConfigMerger(resolve)
    merger.merge(darniconfig.options.app, ravenconfig.options.app)
    API().config = darniconfig
    from etherstone.base import EtherIntegration

    wi = EtherIntegration(ui, UI=False)
    ravenor = raven.Panel(ui)
    ravenor.tree = raven.Tree(ravenor, ravenor.api.CWD)
    newpanel = raven.NewForm(ravenor)
    ui.sideBar = WinterSideBar(ui)
    ui.createSBAction('squares',
                      'Content',
                      ravenor.tree.getWidget(),
                      toolbar=True,
                      keyseq=darniconfig.options.app.tree_shortcut)
    ui.createSBAction('newPage',
                      'New',
                      newpanel,
                      toolbar=True,
                      keyseq=darniconfig.options.app.new_shortcut)
    ui.createSBAction('newPage',
                      'Edit',
                      newpanel,
                      toolbar=False,
                      keyseq=darniconfig.options.app.new_shortcut)

    cmd = raven.CommandLine(ravenor)
    lay = QWidget()
    lay.setLayout(QVBoxLayout())
    lay.layout().addWidget(cmd)
    lay.layout().addWidget(ravenor)

    ui.mainWidget.addTab(lay, QIcon(raven.API().CWD + 'icons/app.png'),
                         'Ravenor')
示例#22
0
文件: base.py 项目: averrin/demesne
 def __init__(self, inspect=False):
     QWebView.__init__(self)
     self.wi = EtherIntegration()
     self.hp = EtherUrl()
     self.api = API()
     self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
     self.linkClicked.connect(self.lc)
     self.titleChanged.connect(self.tc)
     self.setRenderHint(QPainter.HighQualityAntialiasing)
     self.setRenderHint(QPainter.SmoothPixmapTransform)
     self.setRenderHint(QPainter.Antialiasing)
     settings = self.page().settings()
     settings.setFontFamily(QWebSettings.StandardFont, self.wi.parent.config.options.webview.main_font)
     settings.setFontSize(QWebSettings.DefaultFontSize, 24)
     if inspect:
         self.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
     palette = QPalette()
     palette.setBrush(QPalette.Base, QBrush(QColor(self.wi.parent.config.options.webview.bg_color)))
     self.page().setPalette(palette)
示例#23
0
    def __init__(self, path):
        WinterObject.__init__(self)
        self.path = os.path.expanduser(path)
        self.text = ''
        try:
            self.prefs = WinterConfig(file(self.path + '/__page.cfg'))
            self.config = self.prefs.cfg

            if not self.config:
                raise IOError()
        except IOError:
            f = file(self.path + '/__page.cfg', 'w')
            f.write('cfg:{}')
            f.close()
            self.prefs = WinterConfig(file(self.path + '/__page.cfg'))
            self.config = self.prefs.cfg

            self.config['title'] = os.path.split(path)[1].decode('utf-8')
            self.config['template'] = API().config.options.app.default_template

        #        finally:
        self.title = self.config.title
        self.template = self.config.template
示例#24
0
文件: core.py 项目: averrin/demesne
class Core(QObject):                   #TODO: Split for CoreUI and Core (without using self.app)
    """
        Store all your app logic here
    """

    SetProgress = pyqtSignal(int)

    def __init__(self):
        QObject.__init__(self)
        self.app = None
        self.collection_desc = None

    def _afterInit(self):
        """
            when application totally init
        """
        self.api = API()
        self.api.ex = self.app.getMethod
        self.api.config = self.app.config
        self.main()
        # self.api.info('Core loaded.')


    def main(self):
        """
            dummy for main core method.
        """
        url = 'http://%s:%s/orlangur/_authenticate' % (
        self.api.config.options.app.orlangur_server, self.api.config.options.app.orlangur_port)
        data = {'username': self.api.config.options.app.orlangur_user,
                'password': self.api.config.options.app.orlangur_password}
        from urllib.error import URLError

        try:
            r = req.Request(url, parse.urlencode(data).encode('utf8'))
            req.urlopen(r).read()
            connection = Connection(self.api.config.options.app.orlangur_server,
                self.api.config.options.app.orlangur_port)
            db = connection.orlangur
            self.db = db
        except URLError:
            QMessageBox.warning(self.app, 'Error',
                'Orlangur server seems down')
            return


        self.compiler = pystache

        self.app.async(self.getConfig, self.assignConfig)


    def getConfig(self):
        """
            Fetch cloud config
        """
        return self.getCollection('en_clients', title='Orlangur')[0]


    def assignConfig(self, config):
        """
            Callback after getConfig
        """
        self.orlangur_config = config


    def fillList(self):
        """
            Refresh collections list. See fillList_callback as callback
        """
        self.app.list.clear()
        self.app.statusBar.showMessage('Fetching meta collection...')
        self.app.async(lambda: self.getCollection('__meta__'), self.fillList_callback)

    def fillList_callback(self, meta):
        """
            See fillList
        """
        meta = sorted(meta, key=lambda x: x['desc'])
        for collection_meta in meta:
            item = QListWidgetItem('%s' % collection_meta['desc'])
            self.app.list.addItem(item)
            item.collection = collection_meta['name']
        self.app.statusBar.showMessage('Collection list filled.')


    def onClick(self, item):
        """
            Collection mouse click handler #Yoda style comment
        """
        self.editCollection(item.collection, item.text())


    def editCollection(self, collection_name, collection_desc=None, callback=None):
        self.collection_name = collection_name
        if collection_desc is not None:
            self.collection_desc = collection_desc
        else:
            self.collection_desc = collection_name

        if callback is None:
            callback = self.editCollection_callback

        self.app.async(lambda: self.getCollection(collection_name, meta=True), callback)
        self.app.statusBar.showMessage('Fetching collection...')


    def editCollection_callback(self, collection):

        editor = self.app.addEditorTab(self.collection_desc)

        self.app.selectTab(self.collection_desc)
#        self.app.viewer.setHtml('')
#        self.app.item_list.clear()
        try:
            meta, collection = collection
        except ValueError:
            meta = ''

        if 'sort_field' in meta:
            collection = sorted(collection, key=lambda x: x[meta['sort_field']])

#        self.app.rp.setTabText(self.app.rp.tab_list['Editor'], self.collection_desc)
        self.app.statusBar.showMessage('Collection fetched successfully')
        editor.collection = self.collection_name

        content = json.dumps(collection, sort_keys=True, indent=4, ensure_ascii=False)

        editor.setText(content)
        editor.editor.setModified(False)
        editor.editor.setReadOnly(False)

        #TODO: make good html view

#        if 'item_template' in meta:
#            for item in collection:
#                self.app.addListItem(self.compiler.render(meta['item_template'], item))
#
#        if 'item_template_html' in meta:
#            html = '<div id="meta">'
#            for item in collection:
#                html += self.compiler.render('<div>%s</div>' % meta['item_template_html'], item)
#            html += '</div>'
#
#            self.app.viewer.setHtml(html)


    def getCollection(self, col_name, fetch=True, meta=False, order_by="", **kwargs):
        collection = self.db.__getattr__(col_name)
        if fetch:
            if not order_by:
                items = collection.find(criteria=kwargs)
            else:
                crit = kwargs
                crit['$sort'] = {'order_by': 1}
                items = collection.find(criteria=crit)
            if not meta or col_name == '__meta__':
                return items
            else:
                return [self.getCollection('__meta__', name=col_name)[0], items]
        else:
            if not meta or col_name == '__meta__':
                return collection
            else:
                return [self.getCollection('__meta__', name=col_name)[0], collection]


    def saveCollection(self, name, content, callback=None):
        edited = self.app.editors[name].editor.isModified()
        edited = True      #TODO: fix
        if edited:
            self.app.pb.setMaximum(len(content))
            self.SetProgress.connect(self.app.pb.setValue)
            self.app.async(lambda: self._saveCollection(name, content),
                lambda: self.saveCollection_callback(name, callback))
        else:
            self.app.statusBar.showMessage('Collection not modified')

    def saveCollection_callback(self, name, callback=None):
        self.api.info('Collection %s saved' % name)
        self.app.editors[name].setText(json.dumps(self.getCollection(name), sort_keys=True, indent=4, ensure_ascii=False))
        if callback is not None:
            callback()

    def _saveCollection(self, name, content):
        collection = self.getCollection(name, fetch=False)
        col_content = self.getCollection(name)
        items = [i['_id'] for i in col_content]
        new_ids = []
        for i in content:
            if '_id' in i:
                new_ids.append(i['_id'])
        for i in items:
            if i not in new_ids:
                collection.remove({'_id': i})

        for i, item in enumerate(content):
            self.SetProgress.emit(i)
            if '_id' in item:
                orig = ''
                for it in col_content:
                    if it['_id'] == item['_id']:
                        orig = it
                        break
                if orig and item != orig:
                    mods = {'$set': {}, '$unset': {}}
                    for key in item:
                        if key != '_id':
                            mods['$set'][key] = item[key]
                    for key in orig:
                        if key not in item:
                            mods['$unset'][key] = ""

                    print(mods)
                    collection.update({'_id': item['_id']}, mods)

            else:
                collection.insert(item)


    def editMeta(self):
        self.collection_name = '__meta__'
        self.collection_desc = 'Meta'
        self.app.async(lambda: self.getCollection('__meta__'), self.editCollection)


    def addCollection(self):
        name, status = QInputDialog.getText(self.app, 'Add collection', 'Collection name')
        if status:
            self.app.async(lambda: self._addCollection(name), self.fillList)


    def _addCollection(self, name):
        collection = self.getCollection('__meta__', fetch=False)
        collection.save({
            "desc": name,
            "name": name,
            "template": self.api.config.options.app.default_template})
        return True

    def delCollection(self):
        if self.app.list.currentItem():
            name = self.app.list.currentItem().collection
            msgBox = QMessageBox()
            msgBox.setText("Delete collection")
            msgBox.setInformativeText("Do you want to delete %s collection?" % name)
            msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msgBox.setDefaultButton(QMessageBox.No)
            msgBox.setDetailedText(json.dumps(self.getCollection(name), sort_keys=True, indent=4))
            ret = msgBox.exec_()
            if ret == QMessageBox.Yes:
#                self.app.editor.editor.setReadOnly(True)
                self.app.async(lambda: self._delCollection(name), self.fillList)

    def _delCollection(self, name):
        meta = self.getCollection('__meta__', fetch=False)
        meta.remove({'name': name})
        return True

    def backUp(self):
        self.app.pb.setVisible(True)
        self.app.async(self._backUp, lambda: self.app.statusBar.showMessage('Backuped successfully'))

    def _backUp(self):
        backup = {'__meta__': self.getCollection('__meta__')}
        self.app.pb.setMaximum(len(backup['__meta__']))
        for i, collection in enumerate(backup['__meta__']):
            print('Fetching %s' % collection['name'])
            backup[collection['name']] = self.getCollection(collection['name'])
            self.app.pb.setValue(i)

        json.dump(
            backup,
            open(os.path.join(self.api.CWD, 'backups', str(int(time())) + '.json'), 'w', encoding="utf8"),
            indent=4
        )
示例#25
0
class Tree(QTreeWidget):
    def __init__(self, parent, path):
        QTreeWidget.__init__(self, parent)
        self.path = os.path.expanduser(path)
        self.parent = parent
        self.parent.tree = self
        self.searchable_exts = ['.txt', '.html', '.text']
        self.currentPage = ''

        self.editor = parent.editor

        self.setHeaderLabel('Content')

        self.api = parent.api

        #            self.itemExpanded.connect(self.expanded)
        self.itemActivated.connect(self.ic)
        self.itemClicked.connect(self.ic)
        #            self.itemDoubleClicked.connect(self.dic)

        self.fill()

    def ic(self, item, column=0):
        page = self.pages[os.path.split(item.url)[0]]
        self.editor.open(item.url)
        #            self.editor.editor.setText(page.getText())
        #            self.editor.filename=item.url
        self.currentPage = page
        self.parent.toggle(1)
        self.parent.parent.setWindowTitle('%s [%s]' % (self.parent.parent.config.info.title, page.title))

    def fill(self):
        self.clear()
        n = 0
        items = {}
        for (path, dirs, files) in os.walk(self.path + 'organizer'):
            if '__page.text' in files:
                page = Page(path)
                if not n:
                    item = self.headerItem()
                    item.path = self.path

                    self.insertTopLevelItem(0, item)
                    item.setExpanded(True)

                name = page.title
                it = QTreeWidgetItem([name])
                it.name = name
                if os.path.isfile(path + '/__icon.png'):
                    it.setIcon(0, QIcon(path + '/__icon.png'))
                else:
                    if dirs:
                        it.setIcon(0, QIcon(self.api.icons['dot']))
                    else:
                        it.setIcon(0, QIcon(self.api.icons['blank']))

                if not n:
                    self.insertTopLevelItem(0, it)
                    it.setExpanded(True)
                    self.currentPage = page
                    self.root = path
                else:
                    rootitem = items[os.path.split(path)[0]].item
                    rootitem.addChild(it)
                n += 1
                it.url = path + '/__page.text'
                page.item = it
                it.page = page
                items[path] = page
        self.pages = items
        self.items = items.values()


    def dropEvent(self, event):
        shutil.move(self.currentItem().page.path, self.itemAt(event.pos()).page.path)
        event.accept()
        self.fill()


    def WFind(self, text, full=False, getlist=False):
        its = []
        if self.full_text.checkState() == Qt.Checked or full:
            for i in self.items:
                i = i.item
                basename, extension = os.path.splitext(i.url)
                if extension in self.searchable_exts:
                    f = open(i.url)
                    for line in f:
                        if str(text.toUtf8()).lower() in line.lower():
                            its.append(i)
                            break
                    f.close()
        else:
            its = self.findItems(text, Qt.MatchContains)

        for i in self.items:
            i = i.item
            if i not in its:
                i.setHidden(True)
            else:
                i.setHidden(False)
        if not getlist:
            return len(its)
        else:
            return its

    def getWidget(self, search=False, full=False):
        frame = FocusProxy(self)
        lay = QVBoxLayout()
        if search:
            frame.tb = QToolBar(frame)
            lay.addWidget(frame.tb)
            frame.tb.addWidget(QLabel('Search:  '))
            frame.tb.addWidget(WinterSearch(self))
            #            frame.tb.addWidget(QWidget().setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
            if full:
                self.full_text = QCheckBox('Full text')
                frame.tb.addWidget(self.full_text)
        lay.addWidget(self)
        frame.setLayout(lay)

        return frame

    def get_text(self, link):
        content = urllib2.urlopen('http://www.instapaper.com/text?u=' + link).read()
        soup = BeautifulSoup(content)
        title = soup.find('title').getText().decode('utf8')
        title = re.sub('\W*', '', title)
        print title
        content = str(soup.find('div', {'id': 'story'}))
        content += '<script>document.getElementById("sm").innerHTML="%s";' % str(
            soup.find('div', {'class': 'sm'}).getText())
        content += 'document.getElementById("orig").href="%s";' % str(
            soup.find('div', {'class': 'bar top'}).fetch()[0].attrs[0][1])
        content += '</script>'
        content = re.sub('(?<![>\s])\n+(?![<\s])', ' ', content)
        return content, title

    def newPage(self, title, root, template='', iconpath=''):
        if type(title).__name__ == 'tuple':
            title = title[0]

        content = ''
        if re.match('(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?', title):
            content, title = self.get_text(title)
            iconpath = API().icons['cloud']
        path = '%s/%s' % (root, title)
        try:
            os.mkdir(path)
            success = True
        except OSError, e:
            API().error(e)
            API().dialog('warning', 'Dublicate page name', 'Can\'t create new page. Plz change page title.')
            success = False
        if success:
            for fn in ['__page.text', '__page.cfg']:
                f = file(path + '/' + fn, 'w')
                if fn == '__page.text':
                    tf = content
                else:
                    tf = ''
                f.write(tf)
                f.close()
            cfg = WinterConfig(file(path + '/' + '__page.cfg'))
            if not template:
                template = API().config.options.app.default_template
            cfg.cfg = {'title': title, 'template': template}
            cfg.save(file(path + '/' + '__page.cfg', 'w'))

            if iconpath:
                shutil.copyfile(iconpath, path + '/__icon.png')

            self.parent.tree.fill()
            SBAction.objects.get(title='Content').forceShowWidget()
            page = Page.objects.get(path=path)
            self.parent.tree.ic(page.item, 0)
            self.parent.toggle(0)
示例#26
0
class UI(WinterQtApp):
    """
        Main class
    """
    def __init__(self, app):
        """
            Create your own mymainwidget inherits QWidget and set it through self.setMainWidget. For future access use self.mainWidget property
        """
        WinterQtApp.__init__(self, app)

    def _afterMWInit(self):
        """
            Fired after MainWindow initialisation
        """

        pass

    def _afterAppInit(self):
        """
            Fired after WinterApp initialisation
        """
        wi = EtherIntegration(self, UI=False)
        mymainwidget = wi.getWebView(toolbar=True)

        def nfilter(name, root):
            if not os.path.isdir(os.path.join(root, name)):
                file = open(os.path.join(root, name))
                title = re.findall('<TITLE>([^<]*)</TITLE>', file.read())
                if title:
                    title = title[0].replace('Improved ADOM Guidebook - ',
                                             'GB - ')
                    title = title.replace('ADOM Manual - ', 'Manual - ')
                else:
                    title = name
                file.close()
                return title
            else:
                return name

        def ffilter(path):
            if not os.path.isdir(path):
                if path.endswith('.html'):
                    return True

            return False

        global app
        app = mymainwidget

        def onEmptyFind(reverse=False):
            if not hasattr(self, 'cpos'):
                self.cpos = 0
                self.q = app.view.q
            else:
                self.cpos += 1
                self.nf = False

            if self.q != app.view.q:
                del self.cpos
                app.view.onEmptyFind()
            else:
                items = app.dirtree.WFind(app.view.q, True, True)
                if items and len(items) == self.cpos + 1:
                    del self.cpos
                else:
                    try:
                        url = items[self.cpos].url
                        app.view.show(url)
                        self.nf = True
                        self.api.showMessage('File num: %d' % (self.cpos + 1))
                        app.view.WFind(app.view.q)
                    except Exception, e:
                        try:
                            del self.cpos
                        except:
                            pass

        def retryFind():
            if hasattr(self, 'q') and self.nf:
                app.view.WFind(self.q)

        mymainwidget.view.onEmptyFind = onEmptyFind
        mymainwidget.api = API()

        mymainwidget.dirtree = WinterDirTree(mymainwidget, CWD + 'adomgb/',
                                             'Guide book', mymainwidget.view,
                                             ffilter, nfilter)

        mymainwidget.view.setHomePage(CWD + 'adomgb/adomgb-toc.html')
        mymainwidget.view.loadHomePage()
        mymainwidget.view.loadFinished.connect(retryFind)

        self.sideBar = WinterSideBar(self)

        self.createSBAction('list',
                            'Content',
                            mymainwidget.dirtree.getWidget(True, True),
                            toolbar=True,
                            keyseq='ALT+1')

        self.setMainWidget(mymainwidget)
示例#27
0
 def _afterInit(self):
     """
         when application totally init
     """
     self.api = API()
     self.main()
示例#28
0
文件: base.py 项目: averrin/demesne
class EtherWebView(QWebView):
    def __init__(self, inspect=False):
        QWebView.__init__(self)
        self.wi = EtherIntegration()
        self.hp = EtherUrl()
        self.api = API()
        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.linkClicked.connect(self.lc)
        self.titleChanged.connect(self.tc)
        self.setRenderHint(QPainter.HighQualityAntialiasing)
        self.setRenderHint(QPainter.SmoothPixmapTransform)
        self.setRenderHint(QPainter.Antialiasing)
        settings = self.page().settings()
        settings.setFontFamily(QWebSettings.StandardFont, self.wi.parent.config.options.webview.main_font)
        settings.setFontSize(QWebSettings.DefaultFontSize, 24)
        if inspect:
            self.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        palette = QPalette()
        palette.setBrush(QPalette.Base, QBrush(QColor(self.wi.parent.config.options.webview.bg_color)))
        self.page().setPalette(palette)


    def tc(self, text):
        print(text)
        if text:
            self.lc(QUrl(text))

    def lc(self, link):
        print(link)
        if link.scheme() == 'winter':
            args = str(link.path())[1:].split('/')
            method = str(link.authority())
            try:
                module, method = method.split('.')
            except ValueError:
                module = 'main'
            try:
                if args[0]:
                    self.emit('exec',method, module,*args)
                else:
                    self.emit('exec',method, module)
                self.wi.parent.debug('Execute: %s(%s) [%s]' % (method, args, module))
            except Exception as e:
                self.api.error(e)
#        elif link.authority() not in ['#', '','localhost:4801']:
        elif link.authority() not in ['#', '']:
            self.wi.parent.debug('GoTo: [%s] %s%s' % (link.scheme(), link.authority(), link.path()))
            self.setUrl(link)
        else:
            pass


    def loadHomePage(self):
        self.load(self.hp)


    def setHomePage(self, link):
        print(link)
        self.hp = EtherUrl(link)

    def show(self, item):
        self.setUrl(EtherUrl(item.url))
        self.wi.parent.setTitle(item.name)

    def cd(self, path):
        pass

    def WFind(self, text):
    #        self.findText('', QWebPage.HighlightAllOccurrences)
        self.q = text
        return self.findText(text)

    def WFindNext(self):
        res = self.findText(self.q)
        if res:
            return res
        else:
            self.onEmptyFind()
            return res

    def WFindPrev(self):
        res = self.findText(self.q, QWebPage.FindBackward)
        if res:
            return res
        else:
            self.onEmptyFind(reverse=True)
            return res

    def js(self, line):
        self.page().currentFrame().evaluateJavaScript(line)

    def onEmptyFind(self, reverse=False):
        self.api.showMessage('No string found')