def command(self, command): """Perform one command.""" command = command.split() cmd = command[0] args = command[1:] win = QApplication.activeWindow() if win not in app.windows: win = app.windows[0] if cmd == b'open': url = QUrl.fromEncoded(args[0]) app.openUrl(url, self.encoding) elif cmd == b'encoding': self.encoding = str(args[0]) elif cmd == b'activate_window': win.activateWindow() win.raise_() elif cmd == b'set_current': url = QUrl.fromEncoded(args[0]) win.setCurrentDocument(app.openUrl(url, self.encoding)) elif cmd == b'set_cursor': line, column = map(int, args) cursor = win.textCursor() pos = cursor.document().findBlockByNumber(line - 1).position() + column cursor.setPosition(pos) win.currentView().setTextCursor(cursor) elif cmd == b'bye': self.close()
def cursor(self, load): """Returns a QTextCursor for this reference. load should be True or False and determines if a not-loaded document should be loaded. Returns None if the document could not be loaded. """ if self._cursor: return self._cursor if load: app.openUrl(QUrl.fromLocalFile(self._filename)) # also calls bind if self._cursor: return self._cursor
def restoreSession(key): """Restore a session specified by key, previously saved by the session manager.""" settings = sessionSettings(key) ## restore current named session name session_name = settings.value('session_name', "", str) if session_name: import sessions sessions.setCurrentSession(session_name) ## restore documents numdocuments = settings.value('numdocuments', 0, int) doc = None for index in range(numdocuments): settings.beginGroup("document{0}".format(index)) url = settings.value("url", QUrl(), QUrl) if url.isEmpty(): import document doc = document.EditorDocument() else: try: doc = app.openUrl(url) except IOError: pass settings.endGroup() # open at least one if doc is None: doc = app.openUrl(QUrl()) ## restore windows numwindows = settings.value('numwindows', 0, int) if numwindows > 0: for index in range(numwindows): settings.beginGroup("mainwindow{0}".format(index)) win = mainwindow.MainWindow() win.readSessionSettings(settings) win.show() app.qApp.processEvents() # init (re)size dock tools u = settings.value("active_document", QUrl(), QUrl) # we don't use app.findDocument because it does not allow empty url for d in app.documents: if u == d.url(): win.setCurrentDocument(d) break else: win.setCurrentDocument(app.documents[0]) settings.endGroup() else: win = mainwindow.MainWindow() win.show() app.qApp.processEvents() # init (re)size dock tools
def slot_session_action(action): name = action.objectName() import sessions doc = sessions.loadSession(name) or app.openUrl(QUrl()) w = mainwindow() w.setCurrentDocument(doc)
def command(self, command): """Perform one command.""" command = command.split() cmd = command[0] args = command[1:] win = app.activeWindow() if not win: import mainwindow win = mainwindow.MainWindow() win.show() if cmd == b'open': url = QUrl.fromEncoded(args[0]) win.openUrl(url, self.encoding) elif cmd == b'encoding': self.encoding = str(args[0]) elif cmd == b'activate_window': win.activateWindow() win.raise_() elif cmd == b'set_current': url = QUrl.fromEncoded(args[0]) try: win.setCurrentDocument(app.openUrl(url)) # already loaded except IOError: pass elif cmd == b'set_cursor': line, column = map(int, args) cursor = win.textCursor() pos = cursor.document().findBlockByNumber(line - 1).position() + column cursor.setPosition(pos) win.currentView().setTextCursor(cursor) elif cmd == b'bye': self.close()
def open_file_at_cursor(cursor, mainwin): """Opens the filename mentioned at the text cursor.""" # take either the selection or the include-args found by ly.parse if cursor.hasSelection(): fnames = [cursor.selection().toPlainText()] else: fnames = list(ly.parse.includeargs(iter(tokeniter.tokens(cursor.block())))) # detemine search path: doc dir and other include path names filename = cursor.document().url().toLocalFile() if filename: path = [os.path.dirname(filename)] else: path = [] path.extend(documentinfo.info(cursor.document()).includepath()) # load all docs, trying all include paths d = None for f in fnames: for p in path: name = os.path.normpath(os.path.join(p, f)) if os.access(name, os.R_OK): d = app.openUrl(QUrl.fromLocalFile(name)) break if d: mainwin.setCurrentDocument(d, True)
def loadSession(name): """Loads the given session (without closing other docs first). Return the document that should become the active one. If None is returned, the session did not open any documents! """ session = sessionGroup(name) try: urls = session.value("urls", [], QUrl) except TypeError: urls = [] else: if not isinstance(urls, (list, tuple)): urls = [] active = session.value("active", -1, int) result = None docs = [] for url in urls: try: doc = app.openUrl(url) except IOError: pass else: docs.append(doc) setCurrentSession(name) if docs: if active not in range(len(docs)): active = 0 return docs[active]
def command(self, command): """Perform one command.""" command = command.split() cmd = command[0] args = command[1:] win = QApplication.activeWindow() if win not in app.windows: if not app.windows: import mainwindow mainwindow.MainWindow().show() win = app.windows[0] if cmd == b'open': url = QUrl.fromEncoded(args[0]) win.openUrl(url, self.encoding) elif cmd == b'encoding': self.encoding = str(args[0]) elif cmd == b'activate_window': win.activateWindow() win.raise_() elif cmd == b'set_current': url = QUrl.fromEncoded(args[0]) win.setCurrentDocument(app.openUrl(url, self.encoding)) elif cmd == b'set_cursor': line, column = map(int, args) cursor = win.textCursor() pos = cursor.document().findBlockByNumber(line - 1).position() + column cursor.setPosition(pos) win.currentView().setTextCursor(cursor) elif cmd == b'bye': self.close()
def cursor(self, filename, line, column, load=False): """Returns the destination of a link as a QTextCursor of the destination document. If load (defaulting to False) is True, the document is loaded if it is not yet loaded. Returns None if the document could not be loaded. """ bound = self._docs.get(filename) if bound: return bound.cursor(line, column) elif load and os.path.isfile(filename): # this also calls bind(), via app.documentLoaded app.openUrl(QUrl.fromLocalFile(filename)) bound = self._docs.get(filename) if bound: return bound.cursor(line, column)
def openUrl(url): """Open Url. If there is an active MainWindow, the document is made the current document in that window. """ if app.windows: win = QApplication.activeWindow() if win not in app.windows: win = app.windows[0] doc = win.openUrl(url) if doc: win.setCurrentDocument(doc) else: app.openUrl(url)
def goto_target(mainwindow, target): """Switch to the document and location where the node target is.""" filename = target.document.filename doc = app.openUrl(QUrl.fromLocalFile(filename)) cursor = QTextCursor(doc) cursor.setPosition(target.position) browseriface.get(mainwindow).setTextCursor(cursor) mainwindow.currentView().centerCursor()
def restoreSession(key): """Restore a session specified by key, previously saved by the session manager.""" settings = sessionSettings(key) ## restore current named session name session_name = settings.value('session_name', "", str) if session_name: import sessions sessions.setCurrentSession(session_name) ## restore documents numdocuments = settings.value('numdocuments', 0, int) doc = None for index in range(numdocuments): settings.beginGroup("document{0}".format(index)) url = settings.value("url", QUrl(), QUrl) if url.isEmpty(): import document doc = document.EditorDocument() else: try: doc = app.openUrl(url) except IOError: pass settings.endGroup() # open at least one if doc is None: doc = app.openUrl(QUrl()) ## restore windows numwindows = settings.value('numwindows', 0, int) if numwindows > 0: for index in range(numwindows): settings.beginGroup("mainwindow{0}".format(index)) win = mainwindow.MainWindow() win.readSessionSettings(settings) win.show() u = settings.value("active_document", QUrl(), QUrl) # we don't use app.findDocument because it does not allow empty url for d in app.documents: if u == d.url(): win.setCurrentDocument(d) break else: win.setCurrentDocument(app.documents[0]) settings.endGroup() else: win = mainwindow.MainWindow() win.show()
def openUrl(self, url, encoding=None): """Same as app.openUrl but with some error checking and recent files.""" if not url.toLocalFile(): # we only support local files QMessageBox.warning(self, app.caption(_("Warning")), _("Can't load non-local document:\n\n{url}").format( url=url.toString())) else: recentfiles.add(url) return app.openUrl(url, encoding)
def slotAccepted(self): """Makes the score and puts it in the editor.""" if self._createNewDocument: self.parent().setCurrentDocument(app.openUrl(QUrl())) from . import build builder = build.Builder(self) cursor = self.parent().currentView().textCursor() cursortools.insert_select(cursor, builder.text()) with cursortools.compress_undo(cursor, True): indent.re_indent(cursor)
def applySnippet(self, name): d = app.openUrl(QUrl()) self.mainwindow().setCurrentDocument(d) super(TemplateMenu, self).applySnippet(name) d.setUndoRedoEnabled(False) d.setUndoRedoEnabled(True) # d.clearUndoRedoStacks() only in Qt >= 4.7 d.setModified(False) from . import snippets if 'template-run' in snippets.get(name).variables: import engrave engrave.engraver(self.mainwindow()).engrave('preview', d)
def document(self, filename, load=False): """Get the document with the specified filename. If load is True, the document is loaded if it wasn't already. Also takes scratchdir into account for unnamed or non-local documents. """ doc = scratchdir.findDocument(filename) if not doc and load: doc = app.openUrl(QUrl.fromLocalFile(filename)) return doc
def document(self): """Return the Document that should be engraved.""" doc = self.stickyDocument() if not doc: doc = self.mainwindow().currentDocument() if not doc.url().isEmpty(): master = variables.get(doc, "master") if master: url = doc.url().resolved(QUrl(master)) doc = app.openUrl(url) return doc
def openUrl(self, url, encoding=None): """Same as app.openUrl but with some error checking and recent files.""" if not url.toLocalFile(): # we only support local files QMessageBox.warning( self, app.caption(_("Warning")), _("Can't load non-local document:\n\n{url}").format( url=url.toString())) else: recentfiles.add(url) return app.openUrl(url, encoding)
def slotAccepted(self): """Makes the score and puts it in the editor.""" from . import build builder = build.Builder(self) # get the builder text = builder.text() # get the source text lydoc = ly.document.Document(text) # temporarily store it in a lydoc cursor = ly.document.Cursor(lydoc) # make a cursor selecting it indent.indenter().indent(cursor) # indent it according to user prefs doc = app.openUrl(QUrl()) # get a new Frescobaldi document doc.setPlainText(lydoc.plaintext()) # write the text in it doc.setModified(False) # make it "not modified" self.parent().setCurrentDocument(doc)
def cursor(self, link, load=False): """Returns the destination of a link as a QTextCursor of the destination document. If load (defaulting to False) is True, the document is loaded if it is not yet loaded. Returns None if the url was not valid or the document could not be loaded. """ import popplerqt4 if not isinstance(link, popplerqt4.Poppler.LinkBrowse) or not link.url(): return m = textedit_match(link.url()) if m: filename, line, col = readurl(m) bound = self._docs.get(filename) if bound: return bound.cursor(line, col) elif load and os.path.isfile(filename): # this also calls bind(), via app.documentLoaded app.openUrl(QUrl.fromLocalFile(filename)) bound = self._docs.get(filename) if bound: return bound.cursor(line, col)
def createDocument(self, filename, contents): """Create a new document using the specified filename and contents. Make it the current document in our mainwindow. """ while os.path.exists(filename) or app.findDocument(QUrl.fromLocalFile(filename)): filename = util.next_file(filename) doc = app.openUrl(QUrl()) doc.setPlainText(contents) doc.setUrl(QUrl.fromLocalFile(filename)) doc.setModified(True) self.mainwindow().setCurrentDocument(doc) return doc
def goto_target(mainwindow, target): """Switch to the document and location where the node target is.""" lydoc = target.document try: # this succeeds if this is a document that is currently open doc = lydoc.document except AttributeError: # it is an included file, just load it filename = target.document.filename doc = app.openUrl(QUrl.fromLocalFile(filename)) cursor = QTextCursor(doc) cursor.setPosition(target.position) browseriface.get(mainwindow).setTextCursor(cursor) mainwindow.currentView().centerCursor()
def document(self, filename, load=False): """Get the document with the specified filename. If load is True, the document is loaded if it wasn't already. Also takes scratchdir into account for unnamed or non-local documents. """ for d in app.documents: s = scratchdir.scratchdir(d) if (s.directory() and util.equal_paths(filename, s.path()) or d.url().toLocalFile() == filename): return d if load: return app.openUrl(QtCore.QUrl.fromLocalFile(filename))
def slot_file_new_from_template_action(action): name = action.objectName() d = app.openUrl(QUrl()) win = mainwindow() win.setCurrentDocument(d) from snippet import insert, snippets view = win.currentView() view.setFocus() insert.insert(name, view) d.setUndoRedoEnabled(False) d.setUndoRedoEnabled(True) # d.clearUndoRedoStacks() only in Qt >= 4.7 d.setModified(False) if 'template-run' in snippets.get(name).variables: import engrave engrave.engraver(win).engrave('preview', d)
def import_done(self): j = self._import_job conf_dlg = self._import_dialog conf_dlg.saveSettings() lyfile = os.path.splitext(self._import_file)[0] + ".ly" while (os.path.exists(lyfile) or app.findDocument(QUrl.fromLocalFile(lyfile))): lyfile = util.next_file(lyfile) shutil.move(j.output_file(), lyfile) doc = app.openUrl(QUrl.fromLocalFile(lyfile)) doc.setModified(True) self.mainwindow().setCurrentDocument(doc) self.post_import(conf_dlg.get_post_settings(), doc) self.mainwindow().saveDocument(doc)
def document(self, filename, load=False): """Get the document with the specified filename. If load is True, the document is loaded if it wasn't already. Also takes scratchdir into account for unnamed or non-local documents. """ for d in app.documents: s = scratchdir.scratchdir(d) if (s.directory() and util.equal_paths(filename, s.path()) or d.url().toLocalFile() == filename): return d if load: doc = app.openUrl(QtCore.QUrl.fromLocalFile(filename)) return doc
def loadSession(name): """Loads the given session (without closing other docs first).""" session = sessionGroup(name) try: urls = session.value("urls", [], QUrl) except TypeError: urls = [] active = session.value("active", -1, int) result = None if urls: docs = [app.openUrl(url) for url in urls] if active not in range(len(docs)): active = 0 result = docs[active] setCurrentSession(name) return result
def loadSession(name): """Loads the given session (without closing other docs first).""" session = sessionGroup(name) urls = [] for url in session.value("urls", []) or []: if isinstance(url, QUrl): urls.append(url) active = int(session.value("active", -1)) result = None if urls: docs = [app.openUrl(url) for url in urls] if active not in range(len(docs)): active = 0 result = docs[active] setCurrentSession(name) return result
def command(self, command): """Perform one command.""" command = command.split() cmd = command[0] args = command[1:] win = QApplication.activeWindow() if win not in app.windows: if not app.windows: import mainwindow mainwindow.MainWindow().show() win = app.windows[0] if cmd == b'open': url = QUrl.fromEncoded(args[0]) try: win.openUrl(url, self.encoding) except IOError as e: filename = url.toLocalFile() msg = _("{message}\n\n{strerror} ({errno})").format( message=_("Could not read from: {url}").format( url=filename), strerror=e.strerror, errno=e.errno) QMessageBox.critical(win, app.caption(_("Error")), msg) elif cmd == b'encoding': self.encoding = str(args[0]) elif cmd == b'activate_window': win.activateWindow() win.raise_() elif cmd == b'set_current': url = QUrl.fromEncoded(args[0]) try: win.setCurrentDocument(app.openUrl(url)) # already loaded except IOError: pass elif cmd == b'set_cursor': line, column = map(int, args) cursor = win.textCursor() pos = cursor.document().findBlockByNumber(line - 1).position() + column cursor.setPosition(pos) win.currentView().setTextCursor(cursor) elif cmd == b'bye': self.close()
def slotAccepted(self): """Makes the score and puts it in the editor.""" from . import build builder = build.Builder(self) # get the builder doc = builder.document() # get the ly.dom document tree if not self.settings.widget().generalPreferences.relpitch.isChecked(): # remove pitches from \relative commands for n in doc.find(ly.dom.Relative): for n1 in n.find(ly.dom.Pitch, 1): n.remove(n1) text = builder.text(doc) # convert to LilyPond source text lydoc = ly.document.Document(text) # temporarily store it in a lydoc cursor = ly.document.Cursor(lydoc) # make a cursor selecting it indent.indenter().indent(cursor) # indent it according to user prefs doc = app.openUrl(QUrl()) # get a new Frescobaldi document doc.setPlainText(lydoc.plaintext()) # write the text in it doc.setModified(False) # make it "not modified" self.parent().setCurrentDocument(doc)
def command(self, command): """Perform one command.""" command = command.split() cmd = command[0] args = command[1:] win = QApplication.activeWindow() if win not in app.windows: if not app.windows: import mainwindow mainwindow.MainWindow().show() win = app.windows[0] if cmd == b'open': url = QUrl.fromEncoded(args[0]) try: win.openUrl(url, self.encoding) except IOError as e: filename = url.toLocalFile() msg = _("{message}\n\n{strerror} ({errno})").format( message = _("Could not read from: {url}").format(url=filename), strerror = e.strerror, errno = e.errno) QMessageBox.critical(win, app.caption(_("Error")), msg) elif cmd == b'encoding': self.encoding = str(args[0]) elif cmd == b'activate_window': win.activateWindow() win.raise_() elif cmd == b'set_current': url = QUrl.fromEncoded(args[0]) try: win.setCurrentDocument(app.openUrl(url)) # already loaded except IOError: pass elif cmd == b'set_cursor': line, column = map(int, args) cursor = win.textCursor() pos = cursor.document().findBlockByNumber(line - 1).position() + column cursor.setPosition(pos) win.currentView().setTextCursor(cursor) elif cmd == b'bye': self.close()
def openUrls(self, urls, encoding=None, ignore_errors=False): """Open a list of urls, using encoding if specified. Returns the list of documents that were successfully loaded. If encoding is None, the encoding is read from the document, defaulting to UTF-8. If ignore_errors is False (the default), an error message is given showing the url or urls that failed to load. If ignore_errors is True, load errors are silently ignored. If an url fails to load, a document is not created. To create an empty document with an url, use the document.Document constructor. Successfully loaded urls are added to the recent files. """ docs = [] failures = [] for url in urls: try: doc = app.openUrl(url, encoding) except IOError as e: failures.append((url, e)) else: docs.append(doc) recentfiles.add(url) if failures and not ignore_errors: if len(failures) == 1: url, e = failures[0] filename = url.toLocalFile() msg = _("{message}\n\n{strerror} ({errno})").format( message = _("Could not read from: {url}").format(url=filename), strerror = e.strerror, errno = e.errno) else: msg = _("Could not read:") + "\n\n" + "\n".join( "{url}: {strerror} ({errno})".format( url = url.toLocalFile(), strerror = e.strerror, errno = e.errno) for url, e in failures) QMessageBox.critical(self, app.caption(_("Error")), msg) return docs
def loadSession(name): """Loads the given session (without closing other docs first). Return the document that should become the active one. If None is returned, the session did not open any documents! """ session = sessionGroup(name) urls = qsettings.get_url_list(session, "urls") active = session.value("active", -1, int) result = None docs = [] for url in urls: try: doc = app.openUrl(url) except IOError: pass else: docs.append(doc) setCurrentSession(name) if docs: if active not in range(len(docs)): active = 0 return docs[active]
def openUrl(self, url, encoding=None): """Same as app.openUrl but adds url to recent files.""" d = app.openUrl(url, encoding) recentfiles.add(url) return d