repo
string
commit
string
message
string
diff
string
nex3/mdb
50bb9b11ceeed284e3a5f6a7f25c3125c9f041e7
Minor formatting cleanup.
diff --git a/mdb-slurp b/mdb-slurp index c077dca..beab0a0 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,19 +1,19 @@ #!/usr/bin/env python import sys import os import traceback from mdb import Database -server = 'http://localhost:5984/' +server = 'http://localhost:5984/' name = 'mdb' for path in sys.argv[1:]: db = Database(server, name) if os.path.isfile(path): db.record(path) break for (dirname, _, files) in os.walk(path): try: db.add_many([os.path.join(dirname, f) for f in files]) except Exception: print "Error when importing %s:" % dirname traceback.print_exc()
nex3/mdb
08e0d5cd5296dc4990c8115be47ab63e4517ffd0
Set default value for ~#disc and ~#discs.
diff --git a/mdb/__init__.py b/mdb/__init__.py index e63bd4f..cbed66d 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,41 +1,45 @@ from datetime import datetime from mdb.formats import MusicFile from couchdb.client import Server SAVED_METATAGS = [ "~filename", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] +DEFAULTS = {"~#disc": 1, "~#discs": 1} + class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) def add(self, path): song = self.song_for(path) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): self.db.update(map(self.dict_for, filter(None, map(self.song_for, paths)))) def song_for(self, path): try: return MusicFile(path.decode("utf-8", "replace")) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): song = song(tag) if song: if isinstance(song, basestring): song = song.split("\n") d[tag] = song + for tag, default in defaults.items(): + if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = song.key.replace("'", "_") return d
nex3/mdb
b2bf69aae2c64a47b085942f49f1d4b062a0e6be
Don't insert empty attributes.
diff --git a/mdb/__init__.py b/mdb/__init__.py index ef33c46..e63bd4f 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,39 +1,41 @@ from datetime import datetime from mdb.formats import MusicFile from couchdb.client import Server SAVED_METATAGS = [ "~filename", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) def add(self, path): song = self.song_for(path) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): self.db.update(map(self.dict_for, filter(None, map(self.song_for, paths)))) def song_for(self, path): try: return MusicFile(path.decode("utf-8", "replace")) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): - d[tag] = song(tag) - if isinstance(d[tag], str) or isinstance(d[tag], unicode): - d[tag] = d[tag].split("\n") - d["_id"] = song.key + song = song(tag) + if song: + if isinstance(song, basestring): song = song.split("\n") + d[tag] = song + # CouchDB doesn't like apostrophes in keys for some reason... + d["_id"] = song.key.replace("'", "_") return d
nex3/mdb
01854403a2b1f7623d23a33cf30a2bfbc511b7a8
Catch exceptions in mdb-slurp.
diff --git a/mdb-slurp b/mdb-slurp index f71f354..c077dca 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,15 +1,19 @@ #!/usr/bin/env python import sys import os +import traceback from mdb import Database server = 'http://localhost:5984/' name = 'mdb' for path in sys.argv[1:]: db = Database(server, name) if os.path.isfile(path): db.record(path) break for (dirname, _, files) in os.walk(path): - db.add_many([os.path.join(dirname, f) for f in files]) + try: db.add_many([os.path.join(dirname, f) for f in files]) + except Exception: + print "Error when importing %s:" % dirname + traceback.print_exc()
nex3/mdb
cf1808317663d01aafd5dd241c56fb9f2d4d6ae0
Make sure pathnames are unicode objects.
diff --git a/mdb/__init__.py b/mdb/__init__.py index e4153c0..ef33c46 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,39 +1,39 @@ from datetime import datetime from mdb.formats import MusicFile from couchdb.client import Server SAVED_METATAGS = [ "~filename", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) def add(self, path): song = self.song_for(path) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): self.db.update(map(self.dict_for, filter(None, map(self.song_for, paths)))) def song_for(self, path): - try: return MusicFile(path) + try: return MusicFile(path.decode("utf-8", "replace")) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): d[tag] = song(tag) if isinstance(d[tag], str) or isinstance(d[tag], unicode): d[tag] = d[tag].split("\n") d["_id"] = song.key return d
nex3/mdb
9cc23d83b8cc9a0523d177975581ab7cbafe0454
Support bulk update and use it at album level.
diff --git a/mdb-slurp b/mdb-slurp index a2b57bb..f71f354 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,15 +1,15 @@ #!/usr/bin/env python import sys import os from mdb import Database server = 'http://localhost:5984/' name = 'mdb' for path in sys.argv[1:]: db = Database(server, name) if os.path.isfile(path): db.record(path) break for (dirname, _, files) in os.walk(path): - for f in files: db.record(os.path.join(dirname, f)) + db.add_many([os.path.join(dirname, f) for f in files]) diff --git a/mdb/__init__.py b/mdb/__init__.py index 026356f..e4153c0 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,31 +1,39 @@ from datetime import datetime from mdb.formats import MusicFile from couchdb.client import Server SAVED_METATAGS = [ "~filename", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) - def record(self, path): - try: song = MusicFile(path) - except IOError: return + def add(self, path): + song = self.song_for(path) if song is None: return + self.db[song.key] = self.dict_for(song) - self.db.create(self.dict_for(song)) + def add_many(self, paths): + self.db.update(map(self.dict_for, + filter(None, + map(self.song_for, paths)))) + + def song_for(self, path): + try: return MusicFile(path) + except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): d[tag] = song(tag) if isinstance(d[tag], str) or isinstance(d[tag], unicode): d[tag] = d[tag].split("\n") + d["_id"] = song.key return d
nex3/mdb
1a434e10eb1c9c57d7d12dbbe619d3d79b8da3ae
Add basic slurping capabilities.
diff --git a/mdb-slurp b/mdb-slurp new file mode 100755 index 0000000..a2b57bb --- /dev/null +++ b/mdb-slurp @@ -0,0 +1,15 @@ +#!/usr/bin/env python +import sys +import os +from mdb import Database + +server = 'http://localhost:5984/' +name = 'mdb' + +for path in sys.argv[1:]: + db = Database(server, name) + if os.path.isfile(path): + db.record(path) + break + for (dirname, _, files) in os.walk(path): + for f in files: db.record(os.path.join(dirname, f)) diff --git a/mdb/__init__.py b/mdb/__init__.py new file mode 100644 index 0000000..026356f --- /dev/null +++ b/mdb/__init__.py @@ -0,0 +1,31 @@ +from datetime import datetime + +from mdb.formats import MusicFile +from couchdb.client import Server + +SAVED_METATAGS = [ + "~filename", "~format", "~mountpoint", "~performers", "~people", + "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", + "~#disc", "~#discs", "~#track", "~#tracks" + ] + +class Database: + def __init__(self, server, name): + self.server = Server(server) + if name in self.server: self.db = self.server[name] + else: self.db = self.server.create(name) + + def record(self, path): + try: song = MusicFile(path) + except IOError: return + if song is None: return + + self.db.create(self.dict_for(song)) + + def dict_for(self, song): + d = {} + for tag in SAVED_METATAGS + song.realkeys(): + d[tag] = song(tag) + if isinstance(d[tag], str) or isinstance(d[tag], unicode): + d[tag] = d[tag].split("\n") + return d
nex3/mdb
88d8896eda2038cb76cd1d959d006531e13cbf6b
Don't catch errors in mdb.formats.MusicFile.
diff --git a/mdb/formats/__init__.py b/mdb/formats/__init__.py index fab1999..058a1f8 100644 --- a/mdb/formats/__init__.py +++ b/mdb/formats/__init__.py @@ -1,74 +1,60 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import sys import traceback from warnings import warn from glob import glob from os.path import dirname, basename, join base = dirname(__file__) self = basename(base) parent = basename(dirname(base)) modules = [f[:-3] for f in glob(join(base, "[!_]*.py"))] modules = ["%s.%s.%s" % (parent, self, basename(m)) for m in modules] _infos = {} for i, name in enumerate(modules): try: format = __import__(name, {}, {}, self) except Exception, err: traceback.print_exc() continue format = __import__(name, {}, {}, self) for ext in format.extensions: _infos[ext] = format.info # Migrate pre-0.16 library, which was using an undocumented "feature". sys.modules[name.replace(".", "/")] = format if name and name.startswith("mdb."): sys.modules[name.split(".", 1)[1]] = sys.modules[name] modules[i] = (format.extensions and name.split(".")[-1]) try: sys.modules["formats.flac"] = sys.modules["formats.xiph"] except KeyError: pass try: sys.modules["formats.oggvorbis"] = sys.modules["formats.xiph"] except KeyError: pass modules = filter(None, modules) modules.sort() def MusicFile(filename): for ext in _infos.keys(): if filename.lower().endswith(ext): - try: - # The sys module docs say this is where the interactive - # interpreter stores exceptions, so it should be safe for - # us to do it -- if we're in the interpreter this does - # nothing, and if we're not it lets us access them elsewhere. - # WARNING: Not threadsafe. Don't add files from threads - # other than the main one. - sys.last_type = sys.last_value = sys.last_traceback = None - return _infos[ext](filename) - except: - print "Error loading %r" % filename - traceback.print_exc() - lt, lv, tb = sys.exc_info() - sys.last_type, sys.last_value, sys.last_traceback = lt, lv, tb - return None + return _infos[ext](filename) else: return None def supported(song): for ext in _infos.keys(): if song.key.lower().endswith(ext): return True return False def filter(filename): for ext in _infos.keys(): if filename.lower().endswith(ext): return True return False
nex3/mdb
1b32e6f9df2dfc9ec79abdd05097e8579acf0848
Add .gitignore.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d20b64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.pyc
nex3/mdb
1fc118bf8141a3ad99d0d624644bddcb2df4f3f6
Remove the dependency of mdb.formats on Quod Libet.
diff --git a/mdb/formats/__init__.py b/mdb/formats/__init__.py index 13edb71..fab1999 100644 --- a/mdb/formats/__init__.py +++ b/mdb/formats/__init__.py @@ -1,75 +1,74 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import sys import traceback +from warnings import warn from glob import glob from os.path import dirname, basename, join base = dirname(__file__) self = basename(base) parent = basename(dirname(base)) modules = [f[:-3] for f in glob(join(base, "[!_]*.py"))] modules = ["%s.%s.%s" % (parent, self, basename(m)) for m in modules] _infos = {} for i, name in enumerate(modules): try: format = __import__(name, {}, {}, self) except Exception, err: traceback.print_exc() continue format = __import__(name, {}, {}, self) for ext in format.extensions: _infos[ext] = format.info # Migrate pre-0.16 library, which was using an undocumented "feature". sys.modules[name.replace(".", "/")] = format - if name and name.startswith("quodlibet."): + if name and name.startswith("mdb."): sys.modules[name.split(".", 1)[1]] = sys.modules[name] modules[i] = (format.extensions and name.split(".")[-1]) try: sys.modules["formats.flac"] = sys.modules["formats.xiph"] except KeyError: pass try: sys.modules["formats.oggvorbis"] = sys.modules["formats.xiph"] except KeyError: pass modules = filter(None, modules) modules.sort() def MusicFile(filename): for ext in _infos.keys(): if filename.lower().endswith(ext): try: # The sys module docs say this is where the interactive # interpreter stores exceptions, so it should be safe for # us to do it -- if we're in the interpreter this does # nothing, and if we're not it lets us access them elsewhere. # WARNING: Not threadsafe. Don't add files from threads # other than the main one. sys.last_type = sys.last_value = sys.last_traceback = None return _infos[ext](filename) except: - print_w(_("Error loading %r") % filename) + print "Error loading %r" % filename traceback.print_exc() lt, lv, tb = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = lt, lv, tb return None else: return None def supported(song): for ext in _infos.keys(): if song.key.lower().endswith(ext): return True return False def filter(filename): for ext in _infos.keys(): if filename.lower().endswith(ext): return True return False - -from quodlibet.formats._audio import USEFUL_TAGS, MACHINE_TAGS, PEOPLE diff --git a/mdb/formats/_apev2.py b/mdb/formats/_apev2.py index c72a95b..bd271b1 100644 --- a/mdb/formats/_apev2.py +++ b/mdb/formats/_apev2.py @@ -1,67 +1,67 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile try: import mutagen.apev2 except ImportError: pass class APEv2File(AudioFile): # Map APE names to QL names. APE tags are also usually capitalized. # Also blacklist a number of tags. IGNORE = ["file", "index", "introplay", "dummy"] TRANS = { "subtitle": "version", "track": "tracknumber", "catalog": "labelid", "year": "date", "record location": "location", "album artist": "albumartist", "debut album": "originalalbum", "record date": "recordingdate", "original artist": "originalartist", "mixartist": "remixer", } SNART = dict([(v, k) for k, v in TRANS.iteritems()]) def __init__(self, filename, audio=None): if audio: tag = audio.tags or {} else: try: tag = mutagen.apev2.APEv2(filename) except mutagen.apev2.APENoHeaderError: tag = {} for key, value in tag.items(): key = self.TRANS.get(key.lower(), key.lower()) if (value.kind == mutagen.apev2.TEXT and key not in self.IGNORE): self[key] = "\n".join(list(value)) def can_change(self, key=None): if key is None: return True else: return (super(APEv2File, self).can_change(key) and key not in self.IGNORE and key not in self.TRANS) def write(self): try: tag = mutagen.apev2.APEv2(self['~filename']) except mutagen.apev2.APENoHeaderError: tag = mutagen.apev2.APEv2() keys = tag.keys() for key in keys: # remove any text keys we read in value = tag[key] if (value.kind == mutagen.apev2.TEXT and key not in self.IGNORE): del(tag[key]) for key in self.realkeys(): if key in self.IGNORE: continue value = self[key] key = self.SNART.get(key, key) if key in ["isrc", "isbn", "ean/upc"]: key = key.upper() else: key = key.title() tag[key] = value.split("\n") tag.save(self["~filename"]) self.sanitize() diff --git a/mdb/formats/_audio.py b/mdb/formats/_audio.py index 18bb336..c4e06ea 100644 --- a/mdb/formats/_audio.py +++ b/mdb/formats/_audio.py @@ -1,496 +1,458 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ # Much of this code is highly optimized, because many of the functions # are called in tight loops. Don't change things just to make them # more readable, unless they're also faster. import os import glob import shutil import time +from urllib import pathname2url -from quodlibet import const -from quodlibet import util - -from quodlibet.util.uri import URI - -from quodlibet.util.tags import STANDARD_TAGS as USEFUL_TAGS -from quodlibet.util.tags import MACHINE_TAGS +from mdb import util MIGRATE = ("~#playcount ~#laststarted ~#lastplayed ~#added " "~#skipcount ~#rating ~bookmark").split() PEOPLE = ("albumartist artist author composer ~performers originalartist " "lyricist arranger conductor").split() TAG_TO_SORT = { "artist": "artistsort", "album": "albumsort", "albumartist": "albumartistsort", "performersort": "performersort", "~performerssort": "~performerssort" } SORT_TO_TAG = dict([(v, k) for (k, v) in TAG_TO_SORT.iteritems()]) PEOPLE_SORT = [TAG_TO_SORT.get(k, k) for k in PEOPLE] class AudioFile(dict): """An audio file. It looks like a dict, but implements synthetic and tied tags via __call__ rather than __getitem__. This means __getitem__, get, and so on can be used for efficiency. If you need to sort many AudioFiles, you can use their sort_key attribute as a decoration.""" fill_metadata = False multisong = False can_add = True is_file = True multiple_values = True format = "Unknown Audio File" def __sort_key(self): return (self("albumsort", ""), self.get("labelid") or self.get("musicbrainz_albumid"), self("~#disc", self.get("discnumber")), self("~#track", self.get("tracknumber")), self("artistsort"), self.get("musicbrainz_artistid"), self.get("title"), self.get("~filename")) sort_key = property(__sort_key) key = property(lambda self: self["~filename"]) mountpoint = property(lambda self: self["~mountpoint"]) def __album_key(self): return (self("albumsort", ""), self.get("album_grouping_key") or self.get("labelid") or self.get("musicbrainz_albumid") or "") album_key = property(__album_key) def __cmp__(self, other): if not other: return -1 try: return cmp(self.sort_key, other.sort_key) except AttributeError: return -1 def __hash__(self): # Dicts aren't hashable by default, so we need a hash # function. Previously this used ~filename. That created a # situation when an object could end up in two buckets by # renaming files. So now it uses identity. return hash(id(self)) def __eq__(self, other): # And to preserve Python hash rules, we need a strict __eq__. return self is other def reload(self): """Reload an audio file from disk. The caller is responsible for handling any errors.""" fn = self["~filename"] saved = {} for key in self: if key in MIGRATE: saved[key] = self[key] self.clear() self["~filename"] = fn self.__init__(fn) self.update(saved) def realkeys(self): """Returns a list of keys that are not internal, i.e. they don't have '~' in them.""" return filter(lambda s: s[:1] != "~", self.keys()) def __call__(self, key, default=u"", connector=" - "): """Return a key, synthesizing it if necessary. A default value may be given (like dict.get); the default default is an empty - unicode string (even if the tag is numeric). - - If a tied tag ('a~b') is requested, the 'connector' keyword - argument may be used to specify what it is tied with. - - For details on tied tags, see the documentation for util.tagsplit.""" + unicode string (even if the tag is numeric).""" if key[:1] == "~": key = key[1:] - if "~" in key: - return connector.join( - filter(None, map(self.__call__, util.tagsplit("~" + key)))) - elif key == "#track": + if key == "#track": try: return int(self["tracknumber"].split("/")[0]) except (ValueError, TypeError, KeyError): return default elif key == "#disc": try: return int(self["discnumber"].split("/")[0]) except (ValueError, TypeError, KeyError): return default - elif key == "length": - if self.get("~#length", 0) == 0: return default - else: return util.format_time(self.get("~#length", 0)) - elif key == "rating": - return util.format_rating(self.get("~#rating", 0)) elif key == "people": join = "\n".join people = filter(None, map(self.__call__, PEOPLE)) people = join(people).split("\n") index = people.index return join([person for (i, person) in enumerate(people) if index(person) == i]) elif key == "peoplesort": join = "\n".join people = filter(None, map(self.__call__, PEOPLE_SORT)) people = join(people).split("\n") index = people.index return (join([person for (i, person) in enumerate(people) if index(person) == i]) or self("~people", default, connector)) elif key == "performers": values = [] for key in self.realkeys(): if key.startswith("performer:"): role = key.split(":", 1)[1] for value in self.list(key): values.append("%s (%s)" % (value, role)) values.extend(self.list("performer")) return "\n".join(values) elif key == "performerssort": values = [] for key in self.realkeys(): if key.startswith("performersort:"): role = key.split(":", 1)[1] for value in self.list(key): values.append("%s (%s)" % (value, role)) values.extend(self.list("performersort")) return ("\n".join(values) or self("~performers", default, connector)) elif key == "basename": return os.path.basename(self["~filename"]) or self["~filename"] elif key == "dirname": return os.path.dirname(self["~filename"]) or self["~filename"] elif key == "uri": try: return self["~uri"] except KeyError: - return URI.frompath(self["~filename"]) + return "file://" + pathname2url(self["~filename"]) elif key == "format": return self.get("~format", self.format) elif key == "year": return self.get("date", default)[:4] elif key == "#year": try: return int(self.get("date", default)[:4]) except (ValueError, TypeError, KeyError): return default elif key == "#tracks": try: return int(self["tracknumber"].split("/")[1]) except (ValueError, IndexError, TypeError, KeyError): return default elif key == "#discs": try: return int(self["discnumber"].split("/")[1]) except (ValueError, IndexError, TypeError, KeyError): return default - elif key == "lyrics": - try: fileobj = file(self.lyric_filename, "rU") - except EnvironmentError: return default - else: return fileobj.read().decode("utf-8", "replace") elif key[:1] == "#" and "~" + key not in self: try: return int(self[key[1:]]) except (ValueError, TypeError, KeyError): return default else: return dict.get(self, "~" + key, default) elif key == "title": title = dict.get(self, "title") if title is None: basename = self("~basename") - basename = basename.decode(const.FSCODING, "replace") - return "%s [%s]" % (basename, _("Unknown")) + basename = util.fsdecode(basename) + return "%s [%s]" % (basename, "Unknown") else: return title elif key in SORT_TO_TAG: try: return self[key] except KeyError: key = SORT_TO_TAG[key] return dict.get(self, key, default) - lyric_filename = property(lambda self: util.fsencode( - os.path.join(os.path.expanduser("~/.lyrics"), - self.comma("artist").replace('/', '')[:128], - self.comma("title").replace('/', '')[:128] + '.lyric'))) - def comma(self, key): """Get all values of a tag, separated by commas. Synthetic tags are supported, but will be slower. If the value is numeric, that is returned rather than a list.""" if "~" in key or key == "title": v = self(key, u"") else: v = self.get(key, u"") if isinstance(v, int): return v elif isinstance(v, float): return v else: return v.replace("\n", ", ") def list(self, key): """Get all values of a tag, as a list. Synthetic tags are supported, but will be slower. Numeric tags are not supported. An empty synthetic tag cannot be distinguished from a non-existent synthetic tag; both result in [].""" if "~" in key or key == "title": v = self(key, connector="\n") if v == "": return [] else: return v.split("\n") elif key in self: return self[key].split("\n") else: return [] def exists(self): """Return true if the file still exists (or we can't tell).""" return os.path.exists(self["~filename"]) def valid(self): """Return true if the file cache is up-to-date (checked via mtime), or we can't tell.""" return (self.get("~#mtime", 0) and self["~#mtime"] == util.mtime(self["~filename"])) def mounted(self): """Return true if the disk the file is on is mounted, or the file is not on a disk.""" return os.path.ismount(self.get("~mountpoint", "/")) def can_change(self, k=None): """See if this file supports changing the given tag. This may be a limitation of the file type, or the file may not be writable. If no arguments are given, return a list of tags that can be changed, or True if 'any' tags can be changed (specific tags should be checked before adding).""" if k is None: if os.access(self["~filename"], os.W_OK): return True else: return [] else: return (k and "=" not in k and "~" not in k and os.access(self["~filename"], os.W_OK)) - def rename(self, newname): - """Rename a file. Errors are not handled. This shouldn't be used - directly; use library.rename instead.""" - - if newname[0] == os.sep: util.mkdir(os.path.dirname(newname)) - else: newname = os.path.join(self('~dirname'), newname) - if not os.path.exists(newname): - shutil.move(self['~filename'], newname) - elif newname != self['~filename']: raise ValueError - self.sanitize(newname) - def website(self): """Look for a URL in the audio metadata, or a Google search if no URL can be found.""" if "website" in self: return self.list("website")[0] for cont in self.list("contact") + self.list("comment"): c = cont.lower() if (c.startswith("http://") or c.startswith("https://") or c.startswith("www.")): return cont elif c.startswith("//www."): return "http:" + cont else: text = "http://www.google.com/search?q=" esc = lambda c: ord(c) > 127 and '%%%x'%ord(c) or c if "labelid" in self: text += ''.join(map(esc, self["labelid"])) else: artist = util.escape("+".join(self("artist").split())) album = util.escape("+".join(self("album").split())) artist = util.encode(artist) album = util.encode(album) artist = "%22" + ''.join(map(esc, artist)) + "%22" album = "%22" + ''.join(map(esc, album)) + "%22" text += artist + "+" + album text += "&ie=UTF8" return text def sanitize(self, filename=None): """Fill in metadata defaults. Find ~mountpoint, ~#mtime, and ~#added.""" if filename: self["~filename"] = filename elif "~filename" not in self: raise ValueError("Unknown filename!") if self.is_file: self["~filename"] = os.path.realpath(self["~filename"]) # Find mount point (terminating at "/" if necessary) head = self["~filename"] while "~mountpoint" not in self: head, tail = os.path.split(head) # Prevent infinite loop without a fully-qualified filename # (the unit tests use these). head = head or "/" if os.path.ismount(head): self["~mountpoint"] = head else: self["~mountpoint"] = "/" # Fill in necessary values. self.setdefault("~#lastplayed", 0) self.setdefault("~#laststarted", 0) self.setdefault("~#playcount", 0) self.setdefault("~#skipcount", 0) self.setdefault("~#length", 0) self.setdefault("~#bitrate", 0) - self.setdefault("~#rating", const.DEFAULT_RATING) + self.setdefault("~#rating", 0.5) self.setdefault("~#added", int(time.time())) self["~#mtime"] = util.mtime(self['~filename']) def to_dump(self): """A string of 'key=value' lines, similar to vorbiscomment output.""" s = [] for k in self.keys(): if isinstance(self[k], int) or isinstance(self[k], long): s.append("%s=%d" % (k, self[k])) elif isinstance(self[k], float): s.append("%s=%f" % (k, self[k])) else: for v2 in self.list(k): if isinstance(v2, str): s.append("%s=%s" % (k, v2)) else: s.append("%s=%s" % (k, util.encode(v2))) s.append("~format=%s" % self.format) s.append("") return "\n".join(s) def change(self, key, old_value, new_value): """Change 'old_value' to 'new_value' for the given metadata key. If the old value is not found, set the key to the new value.""" try: parts = self.list(key) try: parts[parts.index(old_value)] = new_value except ValueError: self[key] = new_value else: self[key] = "\n".join(parts) except KeyError: self[key] = new_value def add(self, key, value): """Add a value for the given metadata key.""" if key not in self: self[key] = value else: self[key] += "\n" + value def remove(self, key, value): """Remove a value from the given key; if the value is not found, remove all values for that key.""" if key not in self: return elif self[key] == value: del(self[key]) else: try: parts = self.list(key) parts.remove(value) self[key] = "\n".join(parts) except ValueError: if key in self: del(self[key]) def find_cover(self): """Return a file-like containing cover image data, or None if no cover is available.""" base = self('~dirname') fns = [] # We can't pass 'base' alone to glob.glob because it probably # contains confusing metacharacters, and Python's glob doesn't # support any kind of escaping, so chdir and use relative # paths with known safe strings. try: olddir = os.getcwd() os.chdir(base) except EnvironmentError: pass else: for subdir in ["", "scan", "scans", "images", "covers"]: for ext in ["jpg", "jpeg", "png", "gif"]: subdir = util.make_case_insensitive(subdir) ext = util.make_case_insensitive(ext) fns.extend(glob.glob(os.path.join(subdir, "*." + ext))) fns.extend(glob.glob(os.path.join(subdir, ".*." + ext))) os.chdir(olddir) images = [] for fn in sorted(fns): lfn = fn.lower() score = 0 # check for the album label number if self.get("labelid", fn + ".").lower() in lfn: score += 100 score += sum(map(lfn.__contains__, ["front", "cover", "jacket", "folder", "albumart"])) if score: images.append((score, os.path.join(base, fn))) # Highest score wins. if images: try: return file(max(images)[1], "rb") except IOError: return None elif "~picture" in self: # Otherwise, we might have a picture stored in the metadata... return self.get_format_cover() else: return None def replay_gain(self, profiles): """Return the recommended Replay Gain scale factor. profiles is a list of Replay Gain profile names ('album', 'track') to try before giving up. The special profile name 'none' will cause no scaling to occur. """ for profile in profiles: if profile is "none": return 1.0 try: db = float(self["replaygain_%s_gain" % profile].split()[0]) peak = float(self.get("replaygain_%s_peak" % profile, 1)) except (KeyError, ValueError): continue else: scale = 10.**(db / 20) if scale * peak > 1: scale = 1.0 / peak # don't clip return min(15, scale) else: return 1.0 def write(self): """Write metadata back to the file.""" raise NotImplementedError def __get_bookmarks(self): marks = [] invalid = [] for line in self.list("~bookmark"): try: time, mark = line.split(" ", 1) except: invalid.append((-1, line)) else: try: time = util.parse_time(time, None) except: invalid.append((-1, line)) else: if time >= 0: marks.append((time, mark)) else: invalid.append((-1, line)) marks.sort() marks.extend(invalid) return marks def __set_bookmarks(self, marks): result = [] for time, mark in marks: if time < 0: raise ValueError("mark times must be positive") result.append(u"%s %s" % (util.format_time(time), mark)) result = u"\n".join(result) if result: self["~bookmark"] = result elif "~bookmark" in self: del(self["~bookmark"]) bookmarks = property( __get_bookmarks, __set_bookmarks, doc="""Parse and return song position bookmarks, or set them. Accessing this returns a copy, so song.bookmarks.append(...) will not work; you need to do marks = song.bookmarks marks.append(...) song.bookmarks = marks""") diff --git a/mdb/formats/_id3.py b/mdb/formats/_id3.py index 0fcfe97..ca2816b 100644 --- a/mdb/formats/_id3.py +++ b/mdb/formats/_id3.py @@ -1,319 +1,291 @@ # Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import mutagen.id3 import tempfile -from quodlibet import config -from quodlibet import const - -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile def isascii(s): return ((len(s) == 0) or (ord(max(s)) < 128)) class ID3hack(mutagen.id3.ID3): "Override 'correct' behavior with desired behavior" def add(self, tag): if len(type(tag).__name__) == 3: tag = type(tag).__base__(tag) if tag.HashKey in self and tag.FrameID[0] == "T": self[tag.HashKey].extend(tag[:]) else: self[tag.HashKey] = tag # ID3 is absolutely the worst thing ever. class ID3File(AudioFile): # http://www.unixgods.org/~tilo/ID3/docs/ID3_comparison.html # http://www.id3.org/id3v2.4.0-frames.txt IDS = { "TIT1": "grouping", "TIT2": "title", "TIT3": "version", "TPE1": "artist", "TPE2": "performer", "TPE3": "conductor", "TPE4": "arranger", "TEXT": "lyricist", "TCOM": "composer", "TENC": "encodedby", "TALB": "album", "TRCK": "tracknumber", "TPOS": "discnumber", "TSRC": "isrc", "TCOP": "copyright", "TPUB": "organization", "TSST": "discsubtitle", "TOLY": "author", "TMOO": "mood", "TBPM": "bpm", "TDRC": "date", "TDOR": "originaldate", "TOAL": "originalalbum", "TOPE": "originalartist", "WOAR": "website", "TSOP": "artistsort", "TSOA": "albumsort", "TSOT": "artistsort", "TMED": "media", "TCMP": "compilation", # "language" should not make to TLAN. TLAN requires # an ISO language code, and QL tags are freeform. } SDI = dict([(v, k) for k, v in IDS.iteritems()]) # At various times, information for this came from # http://musicbrainz.org/docs/specs/metadata_tags.html # http://bugs.musicbrainz.org/ticket/1383 # http://musicbrainz.org/doc/MusicBrainzTag TXXX_MAP = { u"MusicBrainz Artist Id": "musicbrainz_artistid", u"MusicBrainz Album Id": "musicbrainz_albumid", u"MusicBrainz Album Artist Id": "musicbrainz_albumartistid", u"MusicBrainz TRM Id": "musicbrainz_trmid", u"MusicIP PUID": "musicip_puid", u"MusicMagic Fingerprint": "musicip_fingerprint", u"MusicBrainz Album Status": "musicbrainz_albumstatus", u"MusicBrainz Album Type": "musicbrainz_albumtype", u"MusicBrainz Album Release Country": "releasecountry", u"MusicBrainz Disc Id": "musicbrainz_discid", u"ASIN": "asin", u"ALBUMARTISTSORT": "albumartistsort", u"BARCODE": "barcode", } PAM_XXXT = dict([(v, k) for k, v in TXXX_MAP.iteritems()]) - CODECS = ["utf-8"] - try: CODECS.extend(config.get("editing", "id3encoding").strip().split()) - except: pass # Uninitialized config... - CODECS.append("iso-8859-1") + CODECS = ["utf-8", "iso-8859-1"] Kind = None def __init__(self, filename): audio = self.Kind(filename, ID3=ID3hack) tag = audio.tags or {} for frame in tag.values(): if frame.FrameID == "APIC" and len(frame.data): self["~picture"] = "y" continue elif frame.FrameID == "TCON": self["genre"] = "\n".join(frame.genres) continue elif frame.FrameID == "TLEN": try: self["~#length"] = +frame // 1000 except ValueError: pass continue elif (frame.FrameID == "UFID" and frame.owner == "http://musicbrainz.org"): self["musicbrainz_trackid"] = frame.data continue - elif frame.FrameID == "POPM": - count = frame.count - rating = frame.rating / 255.0 - if frame.email == const.EMAIL: - self.setdefault("~#playcount", count) - self.setdefault("~#rating", rating) - elif frame.email == config.get("editing", "save_email"): - self["~#playcount"] = count - self["~#rating"] = rating - continue elif frame.FrameID == "COMM" and frame.desc == "": name = "comment" elif frame.FrameID in ["COMM", "TXXX"]: if frame.desc.startswith("QuodLibet::"): name = frame.desc[11:] elif frame.desc.startswith("replaygain_"): # Some versions of Foobar2000 write broken Replay Gain # tags in this format. name = frame.desc elif frame.desc in self.TXXX_MAP: name = self.TXXX_MAP[frame.desc] else: continue elif frame.FrameID == "RVA2": self.__process_rg(frame) continue elif frame.FrameID == "TMCL": for role, name in frame.people: role = role.encode('utf-8') self.add("performer:" + role, name) continue else: name = self.IDS.get(frame.FrameID, "").lower() name = name.lower() if not name: continue id3id = frame.FrameID if id3id.startswith("T"): text = "\n".join(map(unicode, frame.text)) elif id3id == "COMM": text = "\n".join(frame.text) elif id3id.startswith("W"): text = frame.url frame.encoding = 0 else: continue if not text: continue text = self.__distrust_latin1(text, frame.encoding) if text is None: continue if name in self: self[name] += "\n" + text else: self[name] = text self[name] = self[name].strip() self.setdefault("~#length", int(audio.info.length)) try: self.setdefault("~#bitrate", int(audio.info.bitrate)) except AttributeError: pass self.sanitize(filename) def __process_rg(self, frame): if frame.channel == 1: if frame.desc == "album": k = "album" elif frame.desc == "track": k = "track" elif "replaygain_track_gain" not in self: k = "track" # fallback else: return self["replaygain_%s_gain" % k] = "%+f dB" % frame.gain self["replaygain_%s_peak" % k] = str(frame.peak) def __distrust_latin1(self, text, encoding): assert isinstance(text, unicode) if encoding == 0: text = text.encode('iso-8859-1') for codec in self.CODECS: try: text = text.decode(codec) except (UnicodeError, LookupError): pass else: break else: return None return text def write(self): try: tag = mutagen.id3.ID3(self['~filename']) except mutagen.id3.error: tag = mutagen.id3.ID3() tag.delall("COMM:QuodLibet:") tag.delall("TXXX:QuodLibet:") - for key in ["UFID:http://musicbrainz.org", - "TMCL", - "POPM:%s" % const.EMAIL, - "POPM:%s" % config.get("editing", "save_email")]: + for key in ["UFID:http://musicbrainz.org", "TMCL"]: if key in tag: del(tag[key]) for key, id3name in self.SDI.items(): tag.delall(id3name) if key not in self: continue elif not isascii(self[key]): enc = 1 else: enc = 3 Kind = mutagen.id3.Frames[id3name] text = self[key].split("\n") if id3name == "WOAR": for t in text: tag.add(Kind(url=t)) else: tag.add(Kind(encoding=enc, text=text)) dontwrite = ["genre", "comment", "replaygain_album_peak", "replaygain_track_peak", "replaygain_album_gain", "replaygain_track_gain", "musicbrainz_trackid", ] + self.TXXX_MAP.values() if "musicbrainz_trackid" in self.realkeys(): f = mutagen.id3.UFID(owner="http://musicbrainz.org", data=self["musicbrainz_trackid"]) tag.add(f) mcl = mutagen.id3.TMCL(encoding=3, people=[]) for key in filter(lambda x: x not in self.SDI and x not in dontwrite, self.realkeys()): if not isascii(self[key]): enc = 1 else: enc = 3 if key.startswith("performer:"): mcl.people.append([key.split(":", 1)[1], self[key]]) continue f = mutagen.id3.TXXX( encoding=enc, text=self[key].split("\n"), desc=u"QuodLibet::%s" % key) tag.add(f) if mcl.people: tag.add(mcl) if "genre" in self: if not isascii(self["genre"]): enc = 1 else: enc = 3 t = self["genre"].split("\n") tag.add(mutagen.id3.TCON(encoding=enc, text=t)) else: try: del(tag["TCON"]) except KeyError: pass tag.delall("COMM:") if "comment" in self: if not isascii(self["comment"]): enc = 1 else: enc = 3 t = self["comment"].split("\n") tag.add(mutagen.id3.COMM( encoding=enc, text=t, desc=u"", lang="\x00\x00\x00")) for k in ["normalize", "album", "track"]: try: del(tag["RVA2:"+k]) except KeyError: pass for k in ["track_peak", "track_gain", "album_peak", "album_gain"]: # Delete Foobar droppings. try: del(tag["TXXX:replaygain_" + k]) except KeyError: pass for k in ["track", "album"]: if ('replaygain_%s_gain' % k) in self: gain = float(self["replaygain_%s_gain" % k].split()[0]) try: peak = float(self["replaygain_%s_peak" % k]) except (ValueError, KeyError): peak = 0 f = mutagen.id3.RVA2(desc=k, channel=1, gain=gain, peak=peak) tag.add(f) for key in self.TXXX_MAP: try: del(tag["TXXX:" + key]) except KeyError: pass for key in self.PAM_XXXT: if key in self: f = mutagen.id3.TXXX( encoding=0, text=self[key].split("\n"), desc=self.PAM_XXXT[key]) tag.add(f) - if (config.getboolean("editing", "save_to_songs") and - (self["~#rating"] != 0.5 or self["~#playcount"] != 0)): - email = config.get("editing", "save_email").strip() - email = email or const.EMAIL - t = mutagen.id3.POPM(email=email, - rating=int(255*self["~#rating"]), - count=self["~#playcount"]) - tag.add(t) - tag.save(self["~filename"]) self.sanitize() def get_format_cover(self): try: tag = mutagen.id3.ID3(self["~filename"]) except (EnvironmentError, mutagen.id3.error): return None else: for frame in tag.getall("APIC"): f = tempfile.NamedTemporaryFile() f.write(frame.data) f.flush() f.seek(0, 0) return f else: f.close() return None diff --git a/mdb/formats/mod.py b/mdb/formats/mod.py index 03db074..12420d9 100644 --- a/mdb/formats/mod.py +++ b/mdb/formats/mod.py @@ -1,52 +1,52 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import os -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile extensions = [ '.669', '.amf', '.ams', '.dsm', '.far', '.it', '.med', '.mod', '.mt2', '.mtm', '.okt', '.s3m', '.stm', '.ult', '.gdm', '.xm'] try: import ctypes _modplug = ctypes.cdll.LoadLibrary("libmodplug.so.0") _modplug.ModPlug_GetName.restype = ctypes.c_char_p except (ImportError, OSError): extensions = [] class ModFile(AudioFile): format = "MOD/XM/IT" def __init__(self, filename): size = os.path.getsize(filename) data = file(filename).read() f = _modplug.ModPlug_Load(data, len(data)) if not f: raise IOError("%r not a valid MOD file" % filename) self["~#length"] = _modplug.ModPlug_GetLength(f) // 1000 title = _modplug.ModPlug_GetName(f) or os.path.basename(filename) try: self["title"] = title.decode('utf-8') except UnicodeError: self["title"] = title.decode("iso-8859-1") _modplug.ModPlug_Unload(f) self.sanitize(filename) def write(self): pass def reload(self, *args): artist = self.get("artist") super(ModFile, self).reload(*args) if artist is not None: self.setdefault("artist", artist) def can_change(self, k=None): if k is None: return ["artist"] else: return k == "artist" info = ModFile diff --git a/mdb/formats/mp3.py b/mdb/formats/mp3.py index 8f725c5..3c6ea3b 100644 --- a/mdb/formats/mp3.py +++ b/mdb/formats/mp3.py @@ -1,18 +1,18 @@ # Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ from mutagen.mp3 import MP3 -from quodlibet.formats._id3 import ID3File +from mdb.formats._id3 import ID3File extensions = [".mp3", ".mp2"] class MP3File(ID3File): format = "MP3" Kind = MP3 info = MP3File diff --git a/mdb/formats/mp4.py b/mdb/formats/mp4.py index f4874ad..6bb635e 100644 --- a/mdb/formats/mp4.py +++ b/mdb/formats/mp4.py @@ -1,130 +1,130 @@ # Copyright 2005 Alexey Bobyakov <[email protected]>, Joe Wreschnig # Copyright 2006 Lukas Lalinsky # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import tempfile -from quodlibet import util -from quodlibet.formats._audio import AudioFile +from mdb import util +from mdb.formats._audio import AudioFile extensions = ['.mp4', '.m4a'] try: from mutagen.mp4 import MP4 except ImportError: extensions = [] class MP4File(AudioFile): multiple_values = False format = "MPEG-4 AAC" __translate = { "\xa9nam": "title", "\xa9alb": "album", "\xa9ART": "artist", "aART": "albumartist", "\xa9wrt": "composer", "\xa9day": "date", "\xa9cmt": "comment", "\xa9grp": "grouping", "\xa9gen": "genre", "tmpo": "bpm", "\xa9too": "encodedby", "----:com.apple.iTunes:MusicBrainz Artist Id": "musicbrainz_artistid", "----:com.apple.iTunes:MusicBrainz Track Id": "musicbrainz_trackid", "----:com.apple.iTunes:MusicBrainz Album Id": "musicbrainz_albumid", "----:com.apple.iTunes:MusicBrainz Album Artist Id": "musicbrainz_albumartistid", "----:com.apple.iTunes:MusicIP PUID": "musicip_puid", "----:com.apple.iTunes:MusicBrainz Album Status": "musicbrainz_albumstatus", "----:com.apple.iTunes:MusicBrainz Album Type": "musicbrainz_albumtype", "----:com.apple.iTunes:MusicBrainz Album Release Country": "releasecountry", } __rtranslate = dict([(v, k) for k, v in __translate.iteritems()]) __tupletranslate = { "disk": "discnumber", "trkn": "tracknumber", } __rtupletranslate = dict([(v, k) for k, v in __tupletranslate.iteritems()]) def __init__(self, filename): self.__covers = [] audio = MP4(filename) self["~#length"] = int(audio.info.length) self["~#bitrate"] = int(audio.info.bitrate) for key, values in audio.items(): if key in self.__tupletranslate: name = self.__tupletranslate[key] cur, total = values[0] if total: self[name] = u"%d/%d" % (cur, total) else: self[name] = unicode(cur) elif key in self.__translate: name = self.__translate[key] if key == "tmpo": self[name] = "\n".join(map(unicode, values)) elif key.startswith("----"): self[name] = "\n".join( map(lambda v: util.decode(v).strip("\x00"), values)) else: self[name] = "\n".join(values) elif key == "covr": self["~picture"] = "y" self.sanitize(filename) def write(self): audio = MP4(self["~filename"]) for key in self.__rtranslate.keys() + self.__rtupletranslate.keys(): try: del(audio[key]) except KeyError: pass for key in self.realkeys(): try: name = self.__rtranslate[key] except KeyError: continue values = self.list(key) if name == "tmpo": values = map(int, values) elif name.startswith("----"): values = map(lambda v: v.encode("utf-8"), values) audio[name] = values track, tracks = self("~#track"), self("~#tracks", 0) if track: audio["trkn"] = [(track, tracks)] disc, discs = self("~#disc"), self("~#discs", 0) if disc: audio["disk"] = [(disc, discs)] audio.save() self.sanitize() def can_change(self, key=None): OK = self.__rtranslate.keys() + self.__rtupletranslate.keys() if key is None: return OK else: return super(MP4File, self).can_change(key) and (key in OK) def get_format_cover(self): try: tag = MP4(self["~filename"]) except (OSError, IOError): return None else: for cover in tag.get("covr", []): fn = tempfile.NamedTemporaryFile() fn.write(cover) fn.flush() fn.seek(0, 0) return fn else: return None info = MP4File diff --git a/mdb/formats/mpc.py b/mdb/formats/mpc.py index e88568f..52480d8 100644 --- a/mdb/formats/mpc.py +++ b/mdb/formats/mpc.py @@ -1,44 +1,44 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ -from quodlibet.formats._apev2 import APEv2File +from mdb.formats._apev2 import APEv2File extensions = [".mpc", ".mp+"] try: from mutagen.musepack import Musepack except (ImportError, OSError): extensions = [] class MPCFile(APEv2File): format = "Musepack" def __init__(self, filename): audio = Musepack(filename) super(MPCFile, self).__init__(filename, audio) self["~#length"] = int(audio.info.length) self["~#bitrate"] = int(audio.info.bitrate) try: if audio.info.title_gain: track_g = u"%+0.2f dB" % audio.info.title_gain self.setdefault("replaygain_track_gain", track_g) if audio.info.album_gain: album_g = u"%+0.2f dB" % audio.info.album_gain self.setdefault("replaygain_album_gain", album_g) if audio.info.title_peak: track_p = unicode(audio.info.title_peak * 2) self.setdefault("replaygain_track_peak", track_p) if audio.info.album_peak: album_p = unicode(audio.info.album_peak * 2) self.setdefault("replaygain_album_peak", album_p) except AttributeError: pass self.sanitize(filename) info = MPCFile diff --git a/mdb/formats/remote.py b/mdb/formats/remote.py deleted file mode 100644 index f370750..0000000 --- a/mdb/formats/remote.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2004-2005 Joe Wreschnig, Michael Urman -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License version 2 as -# published by the Free Software Foundation -# -# $Id$ - -from quodlibet.formats._audio import AudioFile -from quodlibet.util.uri import URI - -extensions = [] - -class RemoteFile(AudioFile): - is_file = False - fill_metadata = True - - format = "Remote File" - - def __init__(self, uri): - self["~uri"] = self["~filename"] = str(URI(uri)) - self["~mountpoint"] = "" - self.sanitize(uri) - - def rename(self, newname): pass - def reload(self): pass - def exists(self): return True - def valid(self): return True - def mounted(self): return True - - def write(self): - raise TypeError("RemoteFiles do not support writing!") - - def can_change(self, k = None): - if k is None: return [] - else: return False - - key = property(lambda self: self["~uri"]) - -info = RemoteFile diff --git a/mdb/formats/spc.py b/mdb/formats/spc.py index d21666c..3ca3f18 100644 --- a/mdb/formats/spc.py +++ b/mdb/formats/spc.py @@ -1,33 +1,33 @@ # Copyright 2007 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import os -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile extensions = [".spc"] class SPCFile(AudioFile): format = "SPC700 DSP Data" def __init__(self, filename): self["~#length"] = 0 self.sanitize(filename) def sanitize(self, filename): super(SPCFile, self).sanitize(filename) self["title"] = os.path.basename(self["~filename"])[:-4] def write(self): pass def can_change(self, k=None): if k is None: return ["artist"] else: return k == "artist" info = SPCFile diff --git a/mdb/formats/trueaudio.py b/mdb/formats/trueaudio.py index 6796be6..4335d35 100644 --- a/mdb/formats/trueaudio.py +++ b/mdb/formats/trueaudio.py @@ -1,22 +1,22 @@ # Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ extensions = [".tta"] try: from mutagen.trueaudio import TrueAudio except ImportError: TrueAudio = None extensions = [] -from quodlibet.formats._id3 import ID3File +from mdb.formats._id3 import ID3File class TrueAudioFile(ID3File): format = "True Audio" Kind = TrueAudio info = TrueAudioFile diff --git a/mdb/formats/wav.py b/mdb/formats/wav.py index 00cf40d..3027df7 100644 --- a/mdb/formats/wav.py +++ b/mdb/formats/wav.py @@ -1,35 +1,35 @@ # Copyright 2006 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import os import wave -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile extensions = [".wav"] class WAVEFile(AudioFile): format = "WAVE" def __init__(self, filename): f = wave.open(filename, "rb") self["~#length"] = f.getnframes() // f.getframerate() self.sanitize(filename) def sanitize(self, filename): super(WAVEFile, self).sanitize(filename) self["title"] = os.path.basename(self["~filename"])[:-4] def write(self): pass def can_change(self, k=None): if k is None: return ["artist"] else: return k == "artist" info = WAVEFile diff --git a/mdb/formats/wavpack.py b/mdb/formats/wavpack.py index a5869d5..ad89acd 100644 --- a/mdb/formats/wavpack.py +++ b/mdb/formats/wavpack.py @@ -1,26 +1,26 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ -from quodlibet.formats._apev2 import APEv2File +from mdb.formats._apev2 import APEv2File extensions = [".wv"] try: from mutagen.wavpack import WavPack except ImportError: extensions = [] class WavpackFile(APEv2File): format = "WavPack" def __init__(self, filename): audio = WavPack(filename) super(WavpackFile, self).__init__(filename, audio) self["~#length"] = int(audio.info.length) self.sanitize(filename) info = WavpackFile diff --git a/mdb/formats/wma.py b/mdb/formats/wma.py index ff1b79a..61f10a9 100644 --- a/mdb/formats/wma.py +++ b/mdb/formats/wma.py @@ -1,75 +1,75 @@ # Copyright 2006 Lukas Lalinsky # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile extensions = [".wma"] try: import mutagen.asf except ImportError: extensions = [] class WMAFile(AudioFile): multiple_values = False format = "Windows Media Audio" __translate = { "WM/AlbumTitle": "album", "Title": "title", "Author": "artist", "WM/AlbumArtist": "albumartist", "WM/Composer": "composer", "WM/Writer": "lyricist", "WM/Conductor": "conductor", "WM/ModifiedBy": "remixer", "WM/Producer": "producer", "WM/ContentGroupDescription": "grouping", "WM/SubTitle": "discsubtitle", "WM/TrackNumber": "tracknumber", "WM/PartOfSet": "discnumber", "WM/BeatsPerMinute": "bpm", "WM/Copyright": "copyright", "WM/ISRC": "isrc", "WM/Mood": "mood", "WM/EncodedBy": "encodedby", "MusicBrainz/Track Id": "musicbrainz_trackid", "MusicBrainz/Album Id": "musicbrainz_albumid", "MusicBrainz/Artist Id": "musicbrainz_artistid", "MusicBrainz/Album Artist Id": "musicbrainz_albumartistid", "MusicBrainz/TRM Id": "musicbrainz_trmid", "MusicIP/PUID": "musicip_puid", "WM/Year": "date", } __rtranslate = dict([(v, k) for k, v in __translate.iteritems()]) def __init__(self, filename, audio=None): if audio is None: audio = mutagen.asf.ASF(filename) self["~#length"] = int(audio.info.length) self["~#bitrate"] = int(audio.info.bitrate) for name, values in audio.tags.items(): try: name = self.__translate[name] except KeyError: continue self[name] = "\n".join(map(unicode, values)) self.sanitize(filename) def write(self): audio = mutagen.asf.ASF(self["~filename"]) for key in self.realkeys(): try: name = self.__rtranslate[key] except KeyError: continue audio.tags[name] = self.list(key) audio.save() self.sanitize() def can_change(self, key=None): OK = self.__rtranslate.keys() if key is None: return super(WMAFile, self).can_change(key) else: return super(WMAFile, self).can_change(key) and (key in OK) info = WMAFile diff --git a/mdb/formats/xiph.py b/mdb/formats/xiph.py index 1ec6d96..40d5956 100644 --- a/mdb/formats/xiph.py +++ b/mdb/formats/xiph.py @@ -1,138 +1,109 @@ # Copyright 2004-2005 Joe Wreschnig, Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation # # $Id$ import mutagen -from quodlibet import config -from quodlibet import const - -from quodlibet.formats._audio import AudioFile +from mdb.formats._audio import AudioFile class MutagenVCFile(AudioFile): format = "Unknown Mutagen + vorbiscomment" MutagenType = None def __init__(self, filename, audio=None): # If we're done a type probe, use the results of that to avoid # reopening the file. if audio is None: audio = self.MutagenType(filename) self["~#length"] = int(audio.info.length) try: self["~#bitrate"] = int(audio.info.bitrate) except AttributeError: pass for key, value in (audio.tags or {}).items(): self[key] = "\n".join(value) self._post_read() self.sanitize(filename) def _post_read(self): - email = config.get("editing", "save_email").strip() - maps = {"rating": float, "playcount": int} - for keyed_key, func in maps.items(): - for subkey in ["", ":" + const.EMAIL, ":" + email]: - key = keyed_key + subkey - if key in self: - try: self["~#" + keyed_key] = func(self[key]) - except ValueError: pass - del(self[key]) - if "totaltracks" in self: self.setdefault("tracktotal", self["totaltracks"]) del(self["totaltracks"]) # tracktotal is incredibly stupid; use tracknumber=x/y instead. if "tracktotal" in self: if "tracknumber" in self: self["tracknumber"] += "/" + self["tracktotal"] del(self["tracktotal"]) if "disctotal" in self: if "discnumber" in self: self["discnumber"] += "/" + self["disctotal"] del(self["disctotal"]) def can_change(self, k=None): if k is None: return super(MutagenVCFile, self).can_change(None) else: return (super(MutagenVCFile, self).can_change(k) and k not in ["totaltracks", "tracktotal", "disctotal", "rating", "playcount"] and not k.startswith("rating:") and not k.startswith("playcount:")) - def _prep_write(self, comments): - email = config.get("editing", "save_email").strip() - for key in comments.keys(): - if key.startswith("rating:") or key.startswith("playcount:"): - if key.split(":", 1)[1] in [const.EMAIL, email]: - del(comments[key]) - else: del(comments[key]) - - if config.getboolean("editing", "save_to_songs"): - email = email or const.EMAIL - if self["~#rating"] != 0.5: - comments["rating:" + email] = str(self["~#rating"]) - if self["~#playcount"] != 0: - comments["playcount:" + email] = str(int(self["~#playcount"])) - def write(self): audio = self.MutagenType(self["~filename"]) if audio.tags is None: audio.add_tags() - self._prep_write(audio.tags) for key in self.realkeys(): audio.tags[key] = self.list(key) audio.save() self.sanitize() extensions = [] ogg_formats = [] try: from mutagen.oggvorbis import OggVorbis except ImportError: OggVorbis = None else: extensions.append(".ogg") try: from mutagen.flac import FLAC except ImportError: FLAC = None else: extensions.append(".flac") try: from mutagen.oggflac import OggFLAC except ImportError: OggFLAC = None else: extensions.append(".oggflac") try: from mutagen.oggspeex import OggSpeex except ImportError: OggSpeex = None else: extensions.append(".spx") class OggFile(MutagenVCFile): format = "Ogg Vorbis" MutagenType = OggVorbis class OggFLACFile(MutagenVCFile): format = "Ogg FLAC" MutagenType = OggFLAC class OggSpeexFile(MutagenVCFile): format = "Ogg Speex" MutagenType = OggSpeex class FLACFile(MutagenVCFile): format = "FLAC" MutagenType = FLAC def info(filename): try: audio = mutagen.File(filename) except AttributeError: audio = OggVorbis(filename) if audio is None: raise IOError("file type could not be determined") else: Kind = type(audio) for klass in globals().values(): if Kind is getattr(klass, 'MutagenType', None): return klass(filename, audio) else: raise IOError("file type could not be determined") diff --git a/mdb/util.py b/mdb/util.py new file mode 100644 index 0000000..b14f21d --- /dev/null +++ b/mdb/util.py @@ -0,0 +1,66 @@ +import os +import locale +import re + +def mtime(filename): + """Return the mtime of a file, or 0 if an error occurs.""" + try: return os.path.getmtime(filename) + except OSError: return 0 + +def escape(str): + """Escape a string in a manner suitable for XML/Pango.""" + return str.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") + +def fsdecode(s): + """Decoding a string according to the filesystem encoding.""" + if isinstance(s, unicode): return s + else: return decode(s, locale.getpreferredencoding()) + +def fsencode(s): + """Encode a string according to the filesystem encoding, replacing + errors.""" + if isinstance(s, str): return s + else: return s.encode(locale.getpreferredencoding(), 'replace') + +def decode(s, charset="utf-8"): + """Decode a string; if an error occurs, replace characters and append + a note to the string.""" + try: return s.decode(charset) + except UnicodeError: + return s.decode(charset, "replace") + " [Invalid Encoding]" + +def encode(s, charset="utf-8"): + """Encode a string; if an error occurs, replace characters and append + a note to the string.""" + try: return s.encode(charset) + except UnicodeError: + return (s + " [Invalid Encoding]").encode(charset, "replace") + +def make_case_insensitive(filename): + return "".join(["[%s%s]" % (c.lower(), c.upper()) for c in filename]) + +def parse_time(timestr, err=(ValueError, re.error)): + """Parse a time string in hh:mm:ss, mm:ss, or ss format.""" + if timestr[0:1] == "-": + m = -1 + timestr = timestr[1:] + else: m = 1 + + try: + return m * reduce(lambda s, a: s * 60 + int(a), + re.split(r":|\.", timestr), 0) + except err: return 0 + +def format_time(time): + """Turn a time value in seconds into hh:mm:ss or mm:ss.""" + if time < 0: + time = abs(time) + prefix = "-" + else: prefix = "" + if time >= 3600: # 1 hour + # time, in hours:minutes:seconds + return "%s%d:%02d:%02d" % (prefix, time // 3600, + (time % 3600) // 60, time % 60) + else: + # time, in minutes:seconds + return "%s%d:%02d" % (prefix, time // 60, time % 60)
nex3/mdb
92bf68edf0dab283a11890dfc23de18460e2d79c
Use Quod Libet's tag-normalization lib because Mutagen apparently doesn't handle that.
diff --git a/mdb/formats/__init__.py b/mdb/formats/__init__.py new file mode 100644 index 0000000..13edb71 --- /dev/null +++ b/mdb/formats/__init__.py @@ -0,0 +1,75 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import sys +import traceback + +from glob import glob +from os.path import dirname, basename, join + +base = dirname(__file__) +self = basename(base) +parent = basename(dirname(base)) +modules = [f[:-3] for f in glob(join(base, "[!_]*.py"))] +modules = ["%s.%s.%s" % (parent, self, basename(m)) for m in modules] + +_infos = {} +for i, name in enumerate(modules): + try: format = __import__(name, {}, {}, self) + except Exception, err: + traceback.print_exc() + continue + format = __import__(name, {}, {}, self) + for ext in format.extensions: + _infos[ext] = format.info + # Migrate pre-0.16 library, which was using an undocumented "feature". + sys.modules[name.replace(".", "/")] = format + if name and name.startswith("quodlibet."): + sys.modules[name.split(".", 1)[1]] = sys.modules[name] + modules[i] = (format.extensions and name.split(".")[-1]) + +try: sys.modules["formats.flac"] = sys.modules["formats.xiph"] +except KeyError: pass +try: sys.modules["formats.oggvorbis"] = sys.modules["formats.xiph"] +except KeyError: pass + +modules = filter(None, modules) +modules.sort() + +def MusicFile(filename): + for ext in _infos.keys(): + if filename.lower().endswith(ext): + try: + # The sys module docs say this is where the interactive + # interpreter stores exceptions, so it should be safe for + # us to do it -- if we're in the interpreter this does + # nothing, and if we're not it lets us access them elsewhere. + # WARNING: Not threadsafe. Don't add files from threads + # other than the main one. + sys.last_type = sys.last_value = sys.last_traceback = None + return _infos[ext](filename) + except: + print_w(_("Error loading %r") % filename) + traceback.print_exc() + lt, lv, tb = sys.exc_info() + sys.last_type, sys.last_value, sys.last_traceback = lt, lv, tb + return None + else: return None + +def supported(song): + for ext in _infos.keys(): + if song.key.lower().endswith(ext): + return True + return False + +def filter(filename): + for ext in _infos.keys(): + if filename.lower().endswith(ext): return True + return False + +from quodlibet.formats._audio import USEFUL_TAGS, MACHINE_TAGS, PEOPLE diff --git a/mdb/formats/_apev2.py b/mdb/formats/_apev2.py new file mode 100644 index 0000000..c72a95b --- /dev/null +++ b/mdb/formats/_apev2.py @@ -0,0 +1,67 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from quodlibet.formats._audio import AudioFile + +try: import mutagen.apev2 +except ImportError: pass + +class APEv2File(AudioFile): + # Map APE names to QL names. APE tags are also usually capitalized. + # Also blacklist a number of tags. + IGNORE = ["file", "index", "introplay", "dummy"] + TRANS = { "subtitle": "version", + "track": "tracknumber", + "catalog": "labelid", + "year": "date", + "record location": "location", + "album artist": "albumartist", + "debut album": "originalalbum", + "record date": "recordingdate", + "original artist": "originalartist", + "mixartist": "remixer", + } + SNART = dict([(v, k) for k, v in TRANS.iteritems()]) + + def __init__(self, filename, audio=None): + if audio: + tag = audio.tags or {} + else: + try: tag = mutagen.apev2.APEv2(filename) + except mutagen.apev2.APENoHeaderError: tag = {} + for key, value in tag.items(): + key = self.TRANS.get(key.lower(), key.lower()) + if (value.kind == mutagen.apev2.TEXT and + key not in self.IGNORE): + self[key] = "\n".join(list(value)) + + def can_change(self, key=None): + if key is None: return True + else: return (super(APEv2File, self).can_change(key) and + key not in self.IGNORE and key not in self.TRANS) + + def write(self): + try: tag = mutagen.apev2.APEv2(self['~filename']) + except mutagen.apev2.APENoHeaderError: + tag = mutagen.apev2.APEv2() + + keys = tag.keys() + for key in keys: + # remove any text keys we read in + value = tag[key] + if (value.kind == mutagen.apev2.TEXT and key not in self.IGNORE): + del(tag[key]) + for key in self.realkeys(): + if key in self.IGNORE: continue + value = self[key] + key = self.SNART.get(key, key) + if key in ["isrc", "isbn", "ean/upc"]: key = key.upper() + else: key = key.title() + tag[key] = value.split("\n") + tag.save(self["~filename"]) + self.sanitize() diff --git a/mdb/formats/_audio.py b/mdb/formats/_audio.py new file mode 100644 index 0000000..18bb336 --- /dev/null +++ b/mdb/formats/_audio.py @@ -0,0 +1,496 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +# Much of this code is highly optimized, because many of the functions +# are called in tight loops. Don't change things just to make them +# more readable, unless they're also faster. + +import os +import glob +import shutil +import time + +from quodlibet import const +from quodlibet import util + +from quodlibet.util.uri import URI + +from quodlibet.util.tags import STANDARD_TAGS as USEFUL_TAGS +from quodlibet.util.tags import MACHINE_TAGS + +MIGRATE = ("~#playcount ~#laststarted ~#lastplayed ~#added " + "~#skipcount ~#rating ~bookmark").split() +PEOPLE = ("albumartist artist author composer ~performers originalartist " + "lyricist arranger conductor").split() + +TAG_TO_SORT = { + "artist": "artistsort", + "album": "albumsort", + "albumartist": "albumartistsort", + "performersort": "performersort", + "~performerssort": "~performerssort" + } + +SORT_TO_TAG = dict([(v, k) for (k, v) in TAG_TO_SORT.iteritems()]) + +PEOPLE_SORT = [TAG_TO_SORT.get(k, k) for k in PEOPLE] + +class AudioFile(dict): + """An audio file. It looks like a dict, but implements synthetic + and tied tags via __call__ rather than __getitem__. This means + __getitem__, get, and so on can be used for efficiency. + + If you need to sort many AudioFiles, you can use their sort_key + attribute as a decoration.""" + + fill_metadata = False + multisong = False + can_add = True + is_file = True + multiple_values = True + + format = "Unknown Audio File" + + def __sort_key(self): + return (self("albumsort", ""), + self.get("labelid") or self.get("musicbrainz_albumid"), + self("~#disc", self.get("discnumber")), + self("~#track", self.get("tracknumber")), + self("artistsort"), self.get("musicbrainz_artistid"), + self.get("title"), + self.get("~filename")) + sort_key = property(__sort_key) + + key = property(lambda self: self["~filename"]) + mountpoint = property(lambda self: self["~mountpoint"]) + + def __album_key(self): + return (self("albumsort", ""), + self.get("album_grouping_key") or self.get("labelid") or + self.get("musicbrainz_albumid") or "") + album_key = property(__album_key) + + def __cmp__(self, other): + if not other: return -1 + try: return cmp(self.sort_key, other.sort_key) + except AttributeError: return -1 + + def __hash__(self): + # Dicts aren't hashable by default, so we need a hash + # function. Previously this used ~filename. That created a + # situation when an object could end up in two buckets by + # renaming files. So now it uses identity. + return hash(id(self)) + + def __eq__(self, other): + # And to preserve Python hash rules, we need a strict __eq__. + return self is other + + def reload(self): + """Reload an audio file from disk. The caller is responsible for + handling any errors.""" + + fn = self["~filename"] + saved = {} + for key in self: + if key in MIGRATE: saved[key] = self[key] + self.clear() + self["~filename"] = fn + self.__init__(fn) + self.update(saved) + + def realkeys(self): + """Returns a list of keys that are not internal, i.e. they don't + have '~' in them.""" + + return filter(lambda s: s[:1] != "~", self.keys()) + + def __call__(self, key, default=u"", connector=" - "): + """Return a key, synthesizing it if necessary. A default value + may be given (like dict.get); the default default is an empty + unicode string (even if the tag is numeric). + + If a tied tag ('a~b') is requested, the 'connector' keyword + argument may be used to specify what it is tied with. + + For details on tied tags, see the documentation for util.tagsplit.""" + + if key[:1] == "~": + key = key[1:] + if "~" in key: + return connector.join( + filter(None, map(self.__call__, util.tagsplit("~" + key)))) + elif key == "#track": + try: return int(self["tracknumber"].split("/")[0]) + except (ValueError, TypeError, KeyError): return default + elif key == "#disc": + try: return int(self["discnumber"].split("/")[0]) + except (ValueError, TypeError, KeyError): return default + elif key == "length": + if self.get("~#length", 0) == 0: return default + else: return util.format_time(self.get("~#length", 0)) + elif key == "rating": + return util.format_rating(self.get("~#rating", 0)) + elif key == "people": + join = "\n".join + people = filter(None, map(self.__call__, PEOPLE)) + people = join(people).split("\n") + index = people.index + return join([person for (i, person) in enumerate(people) + if index(person) == i]) + elif key == "peoplesort": + join = "\n".join + people = filter(None, map(self.__call__, PEOPLE_SORT)) + people = join(people).split("\n") + index = people.index + return (join([person for (i, person) in enumerate(people) + if index(person) == i]) or + self("~people", default, connector)) + elif key == "performers": + values = [] + for key in self.realkeys(): + if key.startswith("performer:"): + role = key.split(":", 1)[1] + for value in self.list(key): + values.append("%s (%s)" % (value, role)) + values.extend(self.list("performer")) + return "\n".join(values) + elif key == "performerssort": + values = [] + for key in self.realkeys(): + if key.startswith("performersort:"): + role = key.split(":", 1)[1] + for value in self.list(key): + values.append("%s (%s)" % (value, role)) + values.extend(self.list("performersort")) + return ("\n".join(values) or + self("~performers", default, connector)) + elif key == "basename": + return os.path.basename(self["~filename"]) or self["~filename"] + elif key == "dirname": + return os.path.dirname(self["~filename"]) or self["~filename"] + elif key == "uri": + try: return self["~uri"] + except KeyError: + return URI.frompath(self["~filename"]) + elif key == "format": + return self.get("~format", self.format) + elif key == "year": + return self.get("date", default)[:4] + elif key == "#year": + try: return int(self.get("date", default)[:4]) + except (ValueError, TypeError, KeyError): return default + elif key == "#tracks": + try: return int(self["tracknumber"].split("/")[1]) + except (ValueError, IndexError, TypeError, KeyError): + return default + elif key == "#discs": + try: return int(self["discnumber"].split("/")[1]) + except (ValueError, IndexError, TypeError, KeyError): + return default + elif key == "lyrics": + try: fileobj = file(self.lyric_filename, "rU") + except EnvironmentError: return default + else: return fileobj.read().decode("utf-8", "replace") + elif key[:1] == "#" and "~" + key not in self: + try: return int(self[key[1:]]) + except (ValueError, TypeError, KeyError): return default + else: return dict.get(self, "~" + key, default) + + elif key == "title": + title = dict.get(self, "title") + if title is None: + basename = self("~basename") + basename = basename.decode(const.FSCODING, "replace") + return "%s [%s]" % (basename, _("Unknown")) + else: return title + elif key in SORT_TO_TAG: + try: return self[key] + except KeyError: + key = SORT_TO_TAG[key] + return dict.get(self, key, default) + + lyric_filename = property(lambda self: util.fsencode( + os.path.join(os.path.expanduser("~/.lyrics"), + self.comma("artist").replace('/', '')[:128], + self.comma("title").replace('/', '')[:128] + '.lyric'))) + + def comma(self, key): + """Get all values of a tag, separated by commas. Synthetic + tags are supported, but will be slower. If the value is + numeric, that is returned rather than a list.""" + + if "~" in key or key == "title": v = self(key, u"") + else: v = self.get(key, u"") + if isinstance(v, int): return v + elif isinstance(v, float): return v + else: return v.replace("\n", ", ") + + def list(self, key): + """Get all values of a tag, as a list. Synthetic tags are supported, + but will be slower. Numeric tags are not supported. + + An empty synthetic tag cannot be distinguished from a non-existent + synthetic tag; both result in [].""" + + if "~" in key or key == "title": + v = self(key, connector="\n") + if v == "": return [] + else: return v.split("\n") + elif key in self: return self[key].split("\n") + else: return [] + + def exists(self): + """Return true if the file still exists (or we can't tell).""" + + return os.path.exists(self["~filename"]) + + def valid(self): + """Return true if the file cache is up-to-date (checked via + mtime), or we can't tell.""" + return (self.get("~#mtime", 0) and + self["~#mtime"] == util.mtime(self["~filename"])) + + def mounted(self): + """Return true if the disk the file is on is mounted, or + the file is not on a disk.""" + return os.path.ismount(self.get("~mountpoint", "/")) + + def can_change(self, k=None): + """See if this file supports changing the given tag. This may + be a limitation of the file type, or the file may not be + writable. + + If no arguments are given, return a list of tags that can be + changed, or True if 'any' tags can be changed (specific tags + should be checked before adding).""" + + if k is None: + if os.access(self["~filename"], os.W_OK): return True + else: return [] + else: return (k and "=" not in k and "~" not in k + and os.access(self["~filename"], os.W_OK)) + + def rename(self, newname): + """Rename a file. Errors are not handled. This shouldn't be used + directly; use library.rename instead.""" + + if newname[0] == os.sep: util.mkdir(os.path.dirname(newname)) + else: newname = os.path.join(self('~dirname'), newname) + if not os.path.exists(newname): + shutil.move(self['~filename'], newname) + elif newname != self['~filename']: raise ValueError + self.sanitize(newname) + + def website(self): + """Look for a URL in the audio metadata, or a Google search + if no URL can be found.""" + + if "website" in self: return self.list("website")[0] + for cont in self.list("contact") + self.list("comment"): + c = cont.lower() + if (c.startswith("http://") or c.startswith("https://") or + c.startswith("www.")): return cont + elif c.startswith("//www."): return "http:" + cont + else: + text = "http://www.google.com/search?q=" + esc = lambda c: ord(c) > 127 and '%%%x'%ord(c) or c + if "labelid" in self: text += ''.join(map(esc, self["labelid"])) + else: + artist = util.escape("+".join(self("artist").split())) + album = util.escape("+".join(self("album").split())) + artist = util.encode(artist) + album = util.encode(album) + artist = "%22" + ''.join(map(esc, artist)) + "%22" + album = "%22" + ''.join(map(esc, album)) + "%22" + text += artist + "+" + album + text += "&ie=UTF8" + return text + + def sanitize(self, filename=None): + """Fill in metadata defaults. Find ~mountpoint, ~#mtime, + and ~#added.""" + + if filename: self["~filename"] = filename + elif "~filename" not in self: raise ValueError("Unknown filename!") + if self.is_file: + self["~filename"] = os.path.realpath(self["~filename"]) + # Find mount point (terminating at "/" if necessary) + head = self["~filename"] + while "~mountpoint" not in self: + head, tail = os.path.split(head) + # Prevent infinite loop without a fully-qualified filename + # (the unit tests use these). + head = head or "/" + if os.path.ismount(head): self["~mountpoint"] = head + else: self["~mountpoint"] = "/" + + # Fill in necessary values. + self.setdefault("~#lastplayed", 0) + self.setdefault("~#laststarted", 0) + self.setdefault("~#playcount", 0) + self.setdefault("~#skipcount", 0) + self.setdefault("~#length", 0) + self.setdefault("~#bitrate", 0) + self.setdefault("~#rating", const.DEFAULT_RATING) + self.setdefault("~#added", int(time.time())) + + self["~#mtime"] = util.mtime(self['~filename']) + + def to_dump(self): + """A string of 'key=value' lines, similar to vorbiscomment output.""" + s = [] + for k in self.keys(): + if isinstance(self[k], int) or isinstance(self[k], long): + s.append("%s=%d" % (k, self[k])) + elif isinstance(self[k], float): + s.append("%s=%f" % (k, self[k])) + else: + for v2 in self.list(k): + if isinstance(v2, str): + s.append("%s=%s" % (k, v2)) + else: + s.append("%s=%s" % (k, util.encode(v2))) + s.append("~format=%s" % self.format) + s.append("") + return "\n".join(s) + + def change(self, key, old_value, new_value): + """Change 'old_value' to 'new_value' for the given metadata key. + If the old value is not found, set the key to the new value.""" + try: + parts = self.list(key) + try: parts[parts.index(old_value)] = new_value + except ValueError: + self[key] = new_value + else: + self[key] = "\n".join(parts) + except KeyError: self[key] = new_value + + def add(self, key, value): + """Add a value for the given metadata key.""" + if key not in self: self[key] = value + else: self[key] += "\n" + value + + def remove(self, key, value): + """Remove a value from the given key; if the value is not found, + remove all values for that key.""" + if key not in self: return + elif self[key] == value: del(self[key]) + else: + try: + parts = self.list(key) + parts.remove(value) + self[key] = "\n".join(parts) + except ValueError: + if key in self: del(self[key]) + + def find_cover(self): + """Return a file-like containing cover image data, or None if + no cover is available.""" + + base = self('~dirname') + fns = [] + # We can't pass 'base' alone to glob.glob because it probably + # contains confusing metacharacters, and Python's glob doesn't + # support any kind of escaping, so chdir and use relative + # paths with known safe strings. + try: + olddir = os.getcwd() + os.chdir(base) + except EnvironmentError: + pass + else: + for subdir in ["", "scan", "scans", "images", "covers"]: + for ext in ["jpg", "jpeg", "png", "gif"]: + subdir = util.make_case_insensitive(subdir) + ext = util.make_case_insensitive(ext) + fns.extend(glob.glob(os.path.join(subdir, "*." + ext))) + fns.extend(glob.glob(os.path.join(subdir, ".*." + ext))) + os.chdir(olddir) + images = [] + for fn in sorted(fns): + lfn = fn.lower() + score = 0 + # check for the album label number + if self.get("labelid", fn + ".").lower() in lfn: score += 100 + score += sum(map(lfn.__contains__, + ["front", "cover", "jacket", "folder", "albumart"])) + if score: + images.append((score, os.path.join(base, fn))) + # Highest score wins. + if images: + try: + return file(max(images)[1], "rb") + except IOError: + return None + elif "~picture" in self: + # Otherwise, we might have a picture stored in the metadata... + return self.get_format_cover() + else: return None + + def replay_gain(self, profiles): + """Return the recommended Replay Gain scale factor. + + profiles is a list of Replay Gain profile names ('album', + 'track') to try before giving up. The special profile name + 'none' will cause no scaling to occur. + """ + for profile in profiles: + if profile is "none": + return 1.0 + try: + db = float(self["replaygain_%s_gain" % profile].split()[0]) + peak = float(self.get("replaygain_%s_peak" % profile, 1)) + except (KeyError, ValueError): + continue + else: + scale = 10.**(db / 20) + if scale * peak > 1: + scale = 1.0 / peak # don't clip + return min(15, scale) + else: + return 1.0 + + def write(self): + """Write metadata back to the file.""" + raise NotImplementedError + + def __get_bookmarks(self): + marks = [] + invalid = [] + for line in self.list("~bookmark"): + try: time, mark = line.split(" ", 1) + except: invalid.append((-1, line)) + else: + try: time = util.parse_time(time, None) + except: invalid.append((-1, line)) + else: + if time >= 0: marks.append((time, mark)) + else: invalid.append((-1, line)) + marks.sort() + marks.extend(invalid) + return marks + + def __set_bookmarks(self, marks): + result = [] + for time, mark in marks: + if time < 0: raise ValueError("mark times must be positive") + result.append(u"%s %s" % (util.format_time(time), mark)) + result = u"\n".join(result) + if result: self["~bookmark"] = result + elif "~bookmark" in self: del(self["~bookmark"]) + + bookmarks = property( + __get_bookmarks, __set_bookmarks, + doc="""Parse and return song position bookmarks, or set them. + Accessing this returns a copy, so song.bookmarks.append(...) + will not work; you need to do + marks = song.bookmarks + marks.append(...) + song.bookmarks = marks""") diff --git a/mdb/formats/_id3.py b/mdb/formats/_id3.py new file mode 100644 index 0000000..0fcfe97 --- /dev/null +++ b/mdb/formats/_id3.py @@ -0,0 +1,319 @@ +# Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import mutagen.id3 +import tempfile + +from quodlibet import config +from quodlibet import const + +from quodlibet.formats._audio import AudioFile + +def isascii(s): + return ((len(s) == 0) or (ord(max(s)) < 128)) + +class ID3hack(mutagen.id3.ID3): + "Override 'correct' behavior with desired behavior" + def add(self, tag): + if len(type(tag).__name__) == 3: + tag = type(tag).__base__(tag) + if tag.HashKey in self and tag.FrameID[0] == "T": + self[tag.HashKey].extend(tag[:]) + else: self[tag.HashKey] = tag + +# ID3 is absolutely the worst thing ever. +class ID3File(AudioFile): + + # http://www.unixgods.org/~tilo/ID3/docs/ID3_comparison.html + # http://www.id3.org/id3v2.4.0-frames.txt + IDS = { "TIT1": "grouping", + "TIT2": "title", + "TIT3": "version", + "TPE1": "artist", + "TPE2": "performer", + "TPE3": "conductor", + "TPE4": "arranger", + "TEXT": "lyricist", + "TCOM": "composer", + "TENC": "encodedby", + "TALB": "album", + "TRCK": "tracknumber", + "TPOS": "discnumber", + "TSRC": "isrc", + "TCOP": "copyright", + "TPUB": "organization", + "TSST": "discsubtitle", + "TOLY": "author", + "TMOO": "mood", + "TBPM": "bpm", + "TDRC": "date", + "TDOR": "originaldate", + "TOAL": "originalalbum", + "TOPE": "originalartist", + "WOAR": "website", + "TSOP": "artistsort", + "TSOA": "albumsort", + "TSOT": "artistsort", + "TMED": "media", + "TCMP": "compilation", + # "language" should not make to TLAN. TLAN requires + # an ISO language code, and QL tags are freeform. + } + SDI = dict([(v, k) for k, v in IDS.iteritems()]) + + # At various times, information for this came from + # http://musicbrainz.org/docs/specs/metadata_tags.html + # http://bugs.musicbrainz.org/ticket/1383 + # http://musicbrainz.org/doc/MusicBrainzTag + TXXX_MAP = { + u"MusicBrainz Artist Id": "musicbrainz_artistid", + u"MusicBrainz Album Id": "musicbrainz_albumid", + u"MusicBrainz Album Artist Id": "musicbrainz_albumartistid", + u"MusicBrainz TRM Id": "musicbrainz_trmid", + u"MusicIP PUID": "musicip_puid", + u"MusicMagic Fingerprint": "musicip_fingerprint", + u"MusicBrainz Album Status": "musicbrainz_albumstatus", + u"MusicBrainz Album Type": "musicbrainz_albumtype", + u"MusicBrainz Album Release Country": "releasecountry", + u"MusicBrainz Disc Id": "musicbrainz_discid", + u"ASIN": "asin", + u"ALBUMARTISTSORT": "albumartistsort", + u"BARCODE": "barcode", + } + PAM_XXXT = dict([(v, k) for k, v in TXXX_MAP.iteritems()]) + + CODECS = ["utf-8"] + try: CODECS.extend(config.get("editing", "id3encoding").strip().split()) + except: pass # Uninitialized config... + CODECS.append("iso-8859-1") + + Kind = None + + def __init__(self, filename): + audio = self.Kind(filename, ID3=ID3hack) + tag = audio.tags or {} + + for frame in tag.values(): + if frame.FrameID == "APIC" and len(frame.data): + self["~picture"] = "y" + continue + elif frame.FrameID == "TCON": + self["genre"] = "\n".join(frame.genres) + continue + elif frame.FrameID == "TLEN": + try: self["~#length"] = +frame // 1000 + except ValueError: pass + continue + elif (frame.FrameID == "UFID" and + frame.owner == "http://musicbrainz.org"): + self["musicbrainz_trackid"] = frame.data + continue + elif frame.FrameID == "POPM": + count = frame.count + rating = frame.rating / 255.0 + if frame.email == const.EMAIL: + self.setdefault("~#playcount", count) + self.setdefault("~#rating", rating) + elif frame.email == config.get("editing", "save_email"): + self["~#playcount"] = count + self["~#rating"] = rating + continue + elif frame.FrameID == "COMM" and frame.desc == "": + name = "comment" + elif frame.FrameID in ["COMM", "TXXX"]: + if frame.desc.startswith("QuodLibet::"): + name = frame.desc[11:] + elif frame.desc.startswith("replaygain_"): + # Some versions of Foobar2000 write broken Replay Gain + # tags in this format. + name = frame.desc + elif frame.desc in self.TXXX_MAP: + name = self.TXXX_MAP[frame.desc] + else: continue + elif frame.FrameID == "RVA2": + self.__process_rg(frame) + continue + elif frame.FrameID == "TMCL": + for role, name in frame.people: + role = role.encode('utf-8') + self.add("performer:" + role, name) + continue + else: name = self.IDS.get(frame.FrameID, "").lower() + + name = name.lower() + + if not name: continue + + id3id = frame.FrameID + if id3id.startswith("T"): + text = "\n".join(map(unicode, frame.text)) + elif id3id == "COMM": + text = "\n".join(frame.text) + elif id3id.startswith("W"): + text = frame.url + frame.encoding = 0 + else: continue + + if not text: continue + text = self.__distrust_latin1(text, frame.encoding) + if text is None: continue + + if name in self: self[name] += "\n" + text + else: self[name] = text + self[name] = self[name].strip() + + self.setdefault("~#length", int(audio.info.length)) + try: self.setdefault("~#bitrate", int(audio.info.bitrate)) + except AttributeError: pass + + self.sanitize(filename) + + def __process_rg(self, frame): + if frame.channel == 1: + if frame.desc == "album": k = "album" + elif frame.desc == "track": k = "track" + elif "replaygain_track_gain" not in self: k = "track" # fallback + else: return + self["replaygain_%s_gain" % k] = "%+f dB" % frame.gain + self["replaygain_%s_peak" % k] = str(frame.peak) + + def __distrust_latin1(self, text, encoding): + assert isinstance(text, unicode) + if encoding == 0: + text = text.encode('iso-8859-1') + for codec in self.CODECS: + try: text = text.decode(codec) + except (UnicodeError, LookupError): pass + else: break + else: return None + return text + + def write(self): + try: tag = mutagen.id3.ID3(self['~filename']) + except mutagen.id3.error: tag = mutagen.id3.ID3() + tag.delall("COMM:QuodLibet:") + tag.delall("TXXX:QuodLibet:") + for key in ["UFID:http://musicbrainz.org", + "TMCL", + "POPM:%s" % const.EMAIL, + "POPM:%s" % config.get("editing", "save_email")]: + if key in tag: + del(tag[key]) + + for key, id3name in self.SDI.items(): + tag.delall(id3name) + if key not in self: continue + elif not isascii(self[key]): enc = 1 + else: enc = 3 + + Kind = mutagen.id3.Frames[id3name] + text = self[key].split("\n") + if id3name == "WOAR": + for t in text: + tag.add(Kind(url=t)) + else: tag.add(Kind(encoding=enc, text=text)) + + dontwrite = ["genre", "comment", "replaygain_album_peak", + "replaygain_track_peak", "replaygain_album_gain", + "replaygain_track_gain", "musicbrainz_trackid", + ] + self.TXXX_MAP.values() + + if "musicbrainz_trackid" in self.realkeys(): + f = mutagen.id3.UFID(owner="http://musicbrainz.org", + data=self["musicbrainz_trackid"]) + tag.add(f) + + mcl = mutagen.id3.TMCL(encoding=3, people=[]) + + for key in filter(lambda x: x not in self.SDI and x not in dontwrite, + self.realkeys()): + if not isascii(self[key]): enc = 1 + else: enc = 3 + + if key.startswith("performer:"): + mcl.people.append([key.split(":", 1)[1], self[key]]) + continue + + f = mutagen.id3.TXXX( + encoding=enc, text=self[key].split("\n"), + desc=u"QuodLibet::%s" % key) + tag.add(f) + + if mcl.people: + tag.add(mcl) + + if "genre" in self: + if not isascii(self["genre"]): enc = 1 + else: enc = 3 + t = self["genre"].split("\n") + tag.add(mutagen.id3.TCON(encoding=enc, text=t)) + else: + try: del(tag["TCON"]) + except KeyError: pass + + tag.delall("COMM:") + if "comment" in self: + if not isascii(self["comment"]): enc = 1 + else: enc = 3 + t = self["comment"].split("\n") + tag.add(mutagen.id3.COMM( + encoding=enc, text=t, desc=u"", lang="\x00\x00\x00")) + + for k in ["normalize", "album", "track"]: + try: del(tag["RVA2:"+k]) + except KeyError: pass + + for k in ["track_peak", "track_gain", "album_peak", "album_gain"]: + # Delete Foobar droppings. + try: del(tag["TXXX:replaygain_" + k]) + except KeyError: pass + + for k in ["track", "album"]: + if ('replaygain_%s_gain' % k) in self: + gain = float(self["replaygain_%s_gain" % k].split()[0]) + try: peak = float(self["replaygain_%s_peak" % k]) + except (ValueError, KeyError): peak = 0 + f = mutagen.id3.RVA2(desc=k, channel=1, gain=gain, peak=peak) + tag.add(f) + + for key in self.TXXX_MAP: + try: del(tag["TXXX:" + key]) + except KeyError: pass + for key in self.PAM_XXXT: + if key in self: + f = mutagen.id3.TXXX( + encoding=0, text=self[key].split("\n"), + desc=self.PAM_XXXT[key]) + tag.add(f) + + if (config.getboolean("editing", "save_to_songs") and + (self["~#rating"] != 0.5 or self["~#playcount"] != 0)): + email = config.get("editing", "save_email").strip() + email = email or const.EMAIL + t = mutagen.id3.POPM(email=email, + rating=int(255*self["~#rating"]), + count=self["~#playcount"]) + tag.add(t) + + tag.save(self["~filename"]) + self.sanitize() + + def get_format_cover(self): + try: tag = mutagen.id3.ID3(self["~filename"]) + except (EnvironmentError, mutagen.id3.error): + return None + else: + for frame in tag.getall("APIC"): + f = tempfile.NamedTemporaryFile() + f.write(frame.data) + f.flush() + f.seek(0, 0) + return f + else: + f.close() + return None diff --git a/mdb/formats/mod.py b/mdb/formats/mod.py new file mode 100644 index 0000000..03db074 --- /dev/null +++ b/mdb/formats/mod.py @@ -0,0 +1,52 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import os + +from quodlibet.formats._audio import AudioFile + +extensions = [ + '.669', '.amf', '.ams', '.dsm', '.far', '.it', '.med', '.mod', '.mt2', + '.mtm', '.okt', '.s3m', '.stm', '.ult', '.gdm', '.xm'] +try: + import ctypes + _modplug = ctypes.cdll.LoadLibrary("libmodplug.so.0") + _modplug.ModPlug_GetName.restype = ctypes.c_char_p +except (ImportError, OSError): + extensions = [] + +class ModFile(AudioFile): + + format = "MOD/XM/IT" + + def __init__(self, filename): + size = os.path.getsize(filename) + data = file(filename).read() + f = _modplug.ModPlug_Load(data, len(data)) + if not f: raise IOError("%r not a valid MOD file" % filename) + self["~#length"] = _modplug.ModPlug_GetLength(f) // 1000 + title = _modplug.ModPlug_GetName(f) or os.path.basename(filename) + try: self["title"] = title.decode('utf-8') + except UnicodeError: self["title"] = title.decode("iso-8859-1") + _modplug.ModPlug_Unload(f) + self.sanitize(filename) + + def write(self): + pass + + def reload(self, *args): + artist = self.get("artist") + super(ModFile, self).reload(*args) + if artist is not None: self.setdefault("artist", artist) + + def can_change(self, k=None): + if k is None: return ["artist"] + else: return k == "artist" + +info = ModFile + diff --git a/mdb/formats/mp3.py b/mdb/formats/mp3.py new file mode 100644 index 0000000..8f725c5 --- /dev/null +++ b/mdb/formats/mp3.py @@ -0,0 +1,18 @@ +# Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from mutagen.mp3 import MP3 +from quodlibet.formats._id3 import ID3File + +extensions = [".mp3", ".mp2"] + +class MP3File(ID3File): + format = "MP3" + Kind = MP3 + +info = MP3File diff --git a/mdb/formats/mp4.py b/mdb/formats/mp4.py new file mode 100644 index 0000000..f4874ad --- /dev/null +++ b/mdb/formats/mp4.py @@ -0,0 +1,130 @@ +# Copyright 2005 Alexey Bobyakov <[email protected]>, Joe Wreschnig +# Copyright 2006 Lukas Lalinsky +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import tempfile + +from quodlibet import util +from quodlibet.formats._audio import AudioFile + +extensions = ['.mp4', '.m4a'] + +try: + from mutagen.mp4 import MP4 +except ImportError: + extensions = [] + +class MP4File(AudioFile): + multiple_values = False + format = "MPEG-4 AAC" + + __translate = { + "\xa9nam": "title", + "\xa9alb": "album", + "\xa9ART": "artist", + "aART": "albumartist", + "\xa9wrt": "composer", + "\xa9day": "date", + "\xa9cmt": "comment", + "\xa9grp": "grouping", + "\xa9gen": "genre", + "tmpo": "bpm", + "\xa9too": "encodedby", + "----:com.apple.iTunes:MusicBrainz Artist Id": + "musicbrainz_artistid", + "----:com.apple.iTunes:MusicBrainz Track Id": "musicbrainz_trackid", + "----:com.apple.iTunes:MusicBrainz Album Id": "musicbrainz_albumid", + "----:com.apple.iTunes:MusicBrainz Album Artist Id": + "musicbrainz_albumartistid", + "----:com.apple.iTunes:MusicIP PUID": "musicip_puid", + "----:com.apple.iTunes:MusicBrainz Album Status": + "musicbrainz_albumstatus", + "----:com.apple.iTunes:MusicBrainz Album Type": + "musicbrainz_albumtype", + "----:com.apple.iTunes:MusicBrainz Album Release Country": + "releasecountry", + } + __rtranslate = dict([(v, k) for k, v in __translate.iteritems()]) + + __tupletranslate = { + "disk": "discnumber", + "trkn": "tracknumber", + } + __rtupletranslate = dict([(v, k) for k, v in __tupletranslate.iteritems()]) + + def __init__(self, filename): + self.__covers = [] + audio = MP4(filename) + self["~#length"] = int(audio.info.length) + self["~#bitrate"] = int(audio.info.bitrate) + for key, values in audio.items(): + if key in self.__tupletranslate: + name = self.__tupletranslate[key] + cur, total = values[0] + if total: + self[name] = u"%d/%d" % (cur, total) + else: + self[name] = unicode(cur) + elif key in self.__translate: + name = self.__translate[key] + if key == "tmpo": + self[name] = "\n".join(map(unicode, values)) + elif key.startswith("----"): + self[name] = "\n".join( + map(lambda v: util.decode(v).strip("\x00"), values)) + else: + self[name] = "\n".join(values) + elif key == "covr": + self["~picture"] = "y" + self.sanitize(filename) + + def write(self): + audio = MP4(self["~filename"]) + for key in self.__rtranslate.keys() + self.__rtupletranslate.keys(): + try: del(audio[key]) + except KeyError: pass + + for key in self.realkeys(): + try: name = self.__rtranslate[key] + except KeyError: continue + values = self.list(key) + if name == "tmpo": + values = map(int, values) + elif name.startswith("----"): + values = map(lambda v: v.encode("utf-8"), values) + audio[name] = values + track, tracks = self("~#track"), self("~#tracks", 0) + if track: + audio["trkn"] = [(track, tracks)] + disc, discs = self("~#disc"), self("~#discs", 0) + if disc: + audio["disk"] = [(disc, discs)] + audio.save() + self.sanitize() + + def can_change(self, key=None): + OK = self.__rtranslate.keys() + self.__rtupletranslate.keys() + if key is None: return OK + else: return super(MP4File, self).can_change(key) and (key in OK) + + def get_format_cover(self): + try: + tag = MP4(self["~filename"]) + except (OSError, IOError): + return None + else: + for cover in tag.get("covr", []): + fn = tempfile.NamedTemporaryFile() + fn.write(cover) + fn.flush() + fn.seek(0, 0) + return fn + else: + return None + +info = MP4File diff --git a/mdb/formats/mpc.py b/mdb/formats/mpc.py new file mode 100644 index 0000000..e88568f --- /dev/null +++ b/mdb/formats/mpc.py @@ -0,0 +1,44 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from quodlibet.formats._apev2 import APEv2File + +extensions = [".mpc", ".mp+"] +try: + from mutagen.musepack import Musepack +except (ImportError, OSError): + extensions = [] + +class MPCFile(APEv2File): + format = "Musepack" + + def __init__(self, filename): + audio = Musepack(filename) + super(MPCFile, self).__init__(filename, audio) + self["~#length"] = int(audio.info.length) + self["~#bitrate"] = int(audio.info.bitrate) + + try: + if audio.info.title_gain: + track_g = u"%+0.2f dB" % audio.info.title_gain + self.setdefault("replaygain_track_gain", track_g) + if audio.info.album_gain: + album_g = u"%+0.2f dB" % audio.info.album_gain + self.setdefault("replaygain_album_gain", album_g) + if audio.info.title_peak: + track_p = unicode(audio.info.title_peak * 2) + self.setdefault("replaygain_track_peak", track_p) + if audio.info.album_peak: + album_p = unicode(audio.info.album_peak * 2) + self.setdefault("replaygain_album_peak", album_p) + except AttributeError: + pass + + self.sanitize(filename) + +info = MPCFile diff --git a/mdb/formats/remote.py b/mdb/formats/remote.py new file mode 100644 index 0000000..f370750 --- /dev/null +++ b/mdb/formats/remote.py @@ -0,0 +1,40 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from quodlibet.formats._audio import AudioFile +from quodlibet.util.uri import URI + +extensions = [] + +class RemoteFile(AudioFile): + is_file = False + fill_metadata = True + + format = "Remote File" + + def __init__(self, uri): + self["~uri"] = self["~filename"] = str(URI(uri)) + self["~mountpoint"] = "" + self.sanitize(uri) + + def rename(self, newname): pass + def reload(self): pass + def exists(self): return True + def valid(self): return True + def mounted(self): return True + + def write(self): + raise TypeError("RemoteFiles do not support writing!") + + def can_change(self, k = None): + if k is None: return [] + else: return False + + key = property(lambda self: self["~uri"]) + +info = RemoteFile diff --git a/mdb/formats/spc.py b/mdb/formats/spc.py new file mode 100644 index 0000000..d21666c --- /dev/null +++ b/mdb/formats/spc.py @@ -0,0 +1,33 @@ +# Copyright 2007 Joe Wreschnig +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import os + +from quodlibet.formats._audio import AudioFile + +extensions = [".spc"] + +class SPCFile(AudioFile): + format = "SPC700 DSP Data" + + def __init__(self, filename): + self["~#length"] = 0 + self.sanitize(filename) + + def sanitize(self, filename): + super(SPCFile, self).sanitize(filename) + self["title"] = os.path.basename(self["~filename"])[:-4] + + def write(self): + pass + + def can_change(self, k=None): + if k is None: return ["artist"] + else: return k == "artist" + +info = SPCFile diff --git a/mdb/formats/trueaudio.py b/mdb/formats/trueaudio.py new file mode 100644 index 0000000..6796be6 --- /dev/null +++ b/mdb/formats/trueaudio.py @@ -0,0 +1,22 @@ +# Copyright 2004-2006 Joe Wreschnig, Michael Urman, Niklas Janlert +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +extensions = [".tta"] + +try: + from mutagen.trueaudio import TrueAudio +except ImportError: + TrueAudio = None + extensions = [] +from quodlibet.formats._id3 import ID3File + +class TrueAudioFile(ID3File): + format = "True Audio" + Kind = TrueAudio + +info = TrueAudioFile diff --git a/mdb/formats/wav.py b/mdb/formats/wav.py new file mode 100644 index 0000000..00cf40d --- /dev/null +++ b/mdb/formats/wav.py @@ -0,0 +1,35 @@ +# Copyright 2006 Joe Wreschnig +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import os +import wave + +from quodlibet.formats._audio import AudioFile + +extensions = [".wav"] + +class WAVEFile(AudioFile): + format = "WAVE" + + def __init__(self, filename): + f = wave.open(filename, "rb") + self["~#length"] = f.getnframes() // f.getframerate() + self.sanitize(filename) + + def sanitize(self, filename): + super(WAVEFile, self).sanitize(filename) + self["title"] = os.path.basename(self["~filename"])[:-4] + + def write(self): + pass + + def can_change(self, k=None): + if k is None: return ["artist"] + else: return k == "artist" + +info = WAVEFile diff --git a/mdb/formats/wavpack.py b/mdb/formats/wavpack.py new file mode 100644 index 0000000..a5869d5 --- /dev/null +++ b/mdb/formats/wavpack.py @@ -0,0 +1,26 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from quodlibet.formats._apev2 import APEv2File + +extensions = [".wv"] +try: + from mutagen.wavpack import WavPack +except ImportError: + extensions = [] + +class WavpackFile(APEv2File): + format = "WavPack" + + def __init__(self, filename): + audio = WavPack(filename) + super(WavpackFile, self).__init__(filename, audio) + self["~#length"] = int(audio.info.length) + self.sanitize(filename) + +info = WavpackFile diff --git a/mdb/formats/wma.py b/mdb/formats/wma.py new file mode 100644 index 0000000..ff1b79a --- /dev/null +++ b/mdb/formats/wma.py @@ -0,0 +1,75 @@ +# Copyright 2006 Lukas Lalinsky +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +from quodlibet.formats._audio import AudioFile + +extensions = [".wma"] +try: + import mutagen.asf +except ImportError: + extensions = [] + +class WMAFile(AudioFile): + multiple_values = False + format = "Windows Media Audio" + + __translate = { + "WM/AlbumTitle": "album", + "Title": "title", + "Author": "artist", + "WM/AlbumArtist": "albumartist", + "WM/Composer": "composer", + "WM/Writer": "lyricist", + "WM/Conductor": "conductor", + "WM/ModifiedBy": "remixer", + "WM/Producer": "producer", + "WM/ContentGroupDescription": "grouping", + "WM/SubTitle": "discsubtitle", + "WM/TrackNumber": "tracknumber", + "WM/PartOfSet": "discnumber", + "WM/BeatsPerMinute": "bpm", + "WM/Copyright": "copyright", + "WM/ISRC": "isrc", + "WM/Mood": "mood", + "WM/EncodedBy": "encodedby", + "MusicBrainz/Track Id": "musicbrainz_trackid", + "MusicBrainz/Album Id": "musicbrainz_albumid", + "MusicBrainz/Artist Id": "musicbrainz_artistid", + "MusicBrainz/Album Artist Id": "musicbrainz_albumartistid", + "MusicBrainz/TRM Id": "musicbrainz_trmid", + "MusicIP/PUID": "musicip_puid", + "WM/Year": "date", + } + __rtranslate = dict([(v, k) for k, v in __translate.iteritems()]) + + def __init__(self, filename, audio=None): + if audio is None: + audio = mutagen.asf.ASF(filename) + self["~#length"] = int(audio.info.length) + self["~#bitrate"] = int(audio.info.bitrate) + for name, values in audio.tags.items(): + try: name = self.__translate[name] + except KeyError: continue + self[name] = "\n".join(map(unicode, values)) + self.sanitize(filename) + + def write(self): + audio = mutagen.asf.ASF(self["~filename"]) + for key in self.realkeys(): + try: name = self.__rtranslate[key] + except KeyError: continue + audio.tags[name] = self.list(key) + audio.save() + self.sanitize() + + def can_change(self, key=None): + OK = self.__rtranslate.keys() + if key is None: return super(WMAFile, self).can_change(key) + else: return super(WMAFile, self).can_change(key) and (key in OK) + +info = WMAFile diff --git a/mdb/formats/xiph.py b/mdb/formats/xiph.py new file mode 100644 index 0000000..1ec6d96 --- /dev/null +++ b/mdb/formats/xiph.py @@ -0,0 +1,138 @@ +# Copyright 2004-2005 Joe Wreschnig, Michael Urman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation +# +# $Id$ + +import mutagen + +from quodlibet import config +from quodlibet import const + +from quodlibet.formats._audio import AudioFile + +class MutagenVCFile(AudioFile): + format = "Unknown Mutagen + vorbiscomment" + MutagenType = None + + def __init__(self, filename, audio=None): + # If we're done a type probe, use the results of that to avoid + # reopening the file. + if audio is None: + audio = self.MutagenType(filename) + self["~#length"] = int(audio.info.length) + try: self["~#bitrate"] = int(audio.info.bitrate) + except AttributeError: pass + for key, value in (audio.tags or {}).items(): + self[key] = "\n".join(value) + self._post_read() + self.sanitize(filename) + + def _post_read(self): + email = config.get("editing", "save_email").strip() + maps = {"rating": float, "playcount": int} + for keyed_key, func in maps.items(): + for subkey in ["", ":" + const.EMAIL, ":" + email]: + key = keyed_key + subkey + if key in self: + try: self["~#" + keyed_key] = func(self[key]) + except ValueError: pass + del(self[key]) + + if "totaltracks" in self: + self.setdefault("tracktotal", self["totaltracks"]) + del(self["totaltracks"]) + + # tracktotal is incredibly stupid; use tracknumber=x/y instead. + if "tracktotal" in self: + if "tracknumber" in self: + self["tracknumber"] += "/" + self["tracktotal"] + del(self["tracktotal"]) + if "disctotal" in self: + if "discnumber" in self: + self["discnumber"] += "/" + self["disctotal"] + del(self["disctotal"]) + + def can_change(self, k=None): + if k is None: + return super(MutagenVCFile, self).can_change(None) + else: return (super(MutagenVCFile, self).can_change(k) and + k not in ["totaltracks", "tracktotal", "disctotal", + "rating", "playcount"] and + not k.startswith("rating:") and + not k.startswith("playcount:")) + + def _prep_write(self, comments): + email = config.get("editing", "save_email").strip() + for key in comments.keys(): + if key.startswith("rating:") or key.startswith("playcount:"): + if key.split(":", 1)[1] in [const.EMAIL, email]: + del(comments[key]) + else: del(comments[key]) + + if config.getboolean("editing", "save_to_songs"): + email = email or const.EMAIL + if self["~#rating"] != 0.5: + comments["rating:" + email] = str(self["~#rating"]) + if self["~#playcount"] != 0: + comments["playcount:" + email] = str(int(self["~#playcount"])) + + def write(self): + audio = self.MutagenType(self["~filename"]) + if audio.tags is None: + audio.add_tags() + self._prep_write(audio.tags) + for key in self.realkeys(): + audio.tags[key] = self.list(key) + audio.save() + self.sanitize() + +extensions = [] +ogg_formats = [] +try: from mutagen.oggvorbis import OggVorbis +except ImportError: OggVorbis = None +else: extensions.append(".ogg") + +try: from mutagen.flac import FLAC +except ImportError: FLAC = None +else: extensions.append(".flac") + +try: from mutagen.oggflac import OggFLAC +except ImportError: OggFLAC = None +else: extensions.append(".oggflac") + +try: from mutagen.oggspeex import OggSpeex +except ImportError: OggSpeex = None +else: extensions.append(".spx") + +class OggFile(MutagenVCFile): + format = "Ogg Vorbis" + MutagenType = OggVorbis + +class OggFLACFile(MutagenVCFile): + format = "Ogg FLAC" + MutagenType = OggFLAC + +class OggSpeexFile(MutagenVCFile): + format = "Ogg Speex" + MutagenType = OggSpeex + +class FLACFile(MutagenVCFile): + format = "FLAC" + MutagenType = FLAC + +def info(filename): + try: audio = mutagen.File(filename) + except AttributeError: + audio = OggVorbis(filename) + if audio is None: + raise IOError("file type could not be determined") + else: + Kind = type(audio) + for klass in globals().values(): + if Kind is getattr(klass, 'MutagenType', None): + return klass(filename, audio) + else: + raise IOError("file type could not be determined")
ruediger/VobSub2SRT
d238553ea1f82da8c89a82df175d244880a92ba4
Fix homebrew formula
diff --git a/packaging/vobsub2srt.rb b/packaging/vobsub2srt.rb index 69a90d1..b3bd91c 100644 --- a/packaging/vobsub2srt.rb +++ b/packaging/vobsub2srt.rb @@ -1,18 +1,20 @@ # Homebrew Formula for VobSub2SRT # Usage: brew install https://github.com/ruediger/VobSub2SRT/raw/master/vobsub2srt.rb require 'formula' class Vobsub2srt < Formula head 'git://github.com/ruediger/VobSub2SRT.git', :using => :git homepage 'https://github.com/ruediger/VobSub2SRT' depends_on 'cmake' depends_on 'tesseract' depends_on 'ffmpeg' def install - system "./configure #{std_cmake_args}" - system "make install" + mkdir "build" do + system "cmake", "..", *std_cmake_args + system "make", "install" + end end end
ruediger/VobSub2SRT
6c2f57dbc5ffd27667152e08142f0105fdbca104
Remove deprecated std_cmake_parameters
diff --git a/packaging/vobsub2srt.rb b/packaging/vobsub2srt.rb index e7539aa..69a90d1 100644 --- a/packaging/vobsub2srt.rb +++ b/packaging/vobsub2srt.rb @@ -1,18 +1,18 @@ # Homebrew Formula for VobSub2SRT # Usage: brew install https://github.com/ruediger/VobSub2SRT/raw/master/vobsub2srt.rb require 'formula' class Vobsub2srt < Formula head 'git://github.com/ruediger/VobSub2SRT.git', :using => :git homepage 'https://github.com/ruediger/VobSub2SRT' depends_on 'cmake' depends_on 'tesseract' depends_on 'ffmpeg' def install - system "./configure #{std_cmake_parameters}" + system "./configure #{std_cmake_args}" system "make install" end end
ruediger/VobSub2SRT
92ab67135a5d727f7e5f0a94aefa1c8d571e915a
Build: Use pkg-config to find bash-completions path.
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index f648128..21d1348 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -1,30 +1,48 @@ find_program(GZIP gzip HINTS /bin /usr/bin /usr/local/bin) if(GZIP-NOTFOUND) message(WARNING "Gzip not found! Uncompressed manpage installed") add_custom_target(documentation ALL DEPENDS vobsub2srt.1) install(FILES vobsub2srt.1 DESTINATION ${INSTALL_MAN_DIR}) else() add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz COMMAND ${GZIP} -9 -c vobsub2srt.1 > ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz MAIN_DEPENDENCY vobsub2srt.1 WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") add_custom_target(documentation ALL DEPENDS ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz) install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION ${INSTALL_MAN_DIR}) endif() -option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of `pkg-config --variable=completionsdir bash-completion` if available.") +#option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of `pkg-config --variable=completionsdir bash-completion` if available.") + +if(NOT BASH_COMPLETION_PATH) + # Instead of calling pkg-config it should be possible to use + # find_package(bash-completions). See the bash-completions README. + # But Debian/Ubuntu don't ship the cmake configs at the moment. + # Therefore we fallback to pkg-config. + find_program(PKG_CONFIG_EXECUTABLE NAMES pkg-config DOC "pkg-config executable") + mark_as_advanced(PKG_CONFIG_EXECUTABLE) + if(PKG_CONFIG_EXECUTABLE) + execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=completionsdir bash-completion + OUTPUT_VARIABLE BASH_COMPLETION_PATH + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + endif() +endif() + if(BASH_COMPLETION_PATH) message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) +else() + message(STATUS "Bash completions not installed (set -DBASH_COMPLETION_PATH)") endif()
ruediger/VobSub2SRT
f09f7f7b93b3d00f1c7387f983cfff62666e4d3c
Minor code cleanup.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index f3bbeed..207c1cb 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,319 +1,320 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #define TESSERACT_DEFAULT_PATH "<builtin default>" #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH TESSERACT_DEFAULT_PATH #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; int y_threshold = 0; int min_width = 9; int min_height = 1; { /************************************************************************************ * Any option added here should be added to doc/vobsub2srt.1 and doc/completion.sh! * ************************************************************************************/ cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_option("y-threshold", y_threshold, "Y (luminance) threshold below which colors treated as black (Default: 0)"). add_option("min-width", min_width, "Minimum width in pixels to consider a subpicture for OCR (Default: 9)"). add_option("min-height", min_height, "Minimum height in pixels to consider a subpicture for OCR (Default: 1)"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Set Y threshold from command-line arg only if given if (y_threshold) { cout << "Using Y palette threshold: " << y_threshold << "\n"; } // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, y_threshold, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract - char const *tess_path = tesseract_data_path.c_str(); - if (!strcmp(tess_path, TESSERACT_DEFAULT_PATH)) - tess_path = NULL; + char const *tess_path = NULL; + if (tesseract_data_path != TESSERACT_DEFAULT_PATH) + tess_path = tesseract_data_path.c_str(); + #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tess_path, tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tess_path, tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(width < (unsigned int)min_width || height < (unsigned int)min_height) { cerr << "WARNING: Image too small " << sub_counter << ", size: " << image_size << " bytes, " << width << "x" << height << " pixels, expected at least " << min_width << "x" << min_height << "\n"; continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
d1d62e992273e7159dc546d113b9d100fe46f641
src/cmd_options.c++ (help): Remove ... from help text.
diff --git a/src/cmd_options.c++ b/src/cmd_options.c++ index cbef0db..b4b7368 100644 --- a/src/cmd_options.c++ +++ b/src/cmd_options.c++ @@ -1,196 +1,196 @@ /* * This file is part of vobsub2srt * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmd_options.h++" #include <iostream> #include <cstring> #include <cstdlib> #include <vector> #include <string> using namespace std; namespace { struct option { enum arg_type { Bool, String, Int } type; union { bool *flag; std::string *str; int *i; } ref; char const *name; char const *description; char short_name; template<typename T> option(char const *name, arg_type type, T &r, char const *description, char short_name) : type(type), name(name), description(description), short_name(short_name) { switch(type) { case Bool: ref.flag = reinterpret_cast<bool*>(&r); break; case String: ref.str = reinterpret_cast<std::string*>(&r); break; case Int: ref.i = reinterpret_cast<int*>(&r); break; } } }; struct unnamed { std::string *str; char const *name; char const *description; unnamed(std::string &s, char const *name, char const *description) : str(&s), name(name), description(description) { } }; } struct cmd_options::impl { std::vector<option> options; std::vector<unnamed> unnamed_args; }; cmd_options::cmd_options(bool handle_help) : exit(false), handle_help(handle_help), pimpl(new impl) { pimpl->options.reserve(10); // reserve a default amount of options here to save some reallocations } cmd_options::~cmd_options() { delete pimpl; } cmd_options &cmd_options::add_option(char const *name, bool &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Bool, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, std::string &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::String, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, int &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Int, val, description, short_name)); return *this; } cmd_options &cmd_options::add_unnamed(std::string &val, char const *help_name, char const *description) { pimpl->unnamed_args.push_back(unnamed(val, help_name, description)); return *this; } bool cmd_options::parse_cmd(int argc, char **argv) const { size_t current_unnamed = 0; bool parse_options = true; // set to false after -- for(int i = 1; i < argc; ++i) { if(parse_options and argv[i][0] == '-') { unsigned offset = 1; if(argv[i][1] == '-') { if(argv[i][2] == '\0') { // "--" stops option parsing and handles only unnamed args (to allow e.g. files starting with -) parse_options = false; } offset = 2; } if(handle_help and (strcmp(argv[i]+offset, "help") == 0 or strcmp(argv[i]+offset, "h") == 0)) { help(argv[0]); continue; } bool known_option = false; for(std::vector<option>::const_iterator j = pimpl->options.begin(); j != pimpl->options.end(); ++j) { if(strcmp(argv[i]+offset, j->name) == 0 or (j->short_name != '\0' and offset == 1 and argv[i][1] == j->short_name and argv[i][2] == '\0')) { known_option = true; if(j->type == option::Bool) { *j->ref.flag = true; break; } if(i+1 >= argc or argv[i+1][0] == '-') { // Check if next argv is an option or argument cerr << "option " << argv[i] << " is missing an argument\n"; exit = true; return false; } ++i; if(j->type == option::String) { *j->ref.str = argv[i]; } else if(j->type == option::Int) { char *endptr; *j->ref.i = strtol(argv[i], &endptr, 10); if(*endptr != '\0') { cerr << "option " << argv[i] << " expects a number as argument but got '" << argv[i] << "'\n"; exit = true; return false; } } break; } } if(not known_option) { cerr << "ERROR: unknown option '" << argv[i] << "'\n"; help(argv[0]); } } else if(pimpl->unnamed_args.size() > current_unnamed) { *pimpl->unnamed_args[current_unnamed].str = argv[i]; ++current_unnamed; } else { help(argv[0]); } } return not exit; } void cmd_options::help(char const *progname) const { cerr << "usage: " << progname; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << " --" << i->name; } if(handle_help) { cerr << " --help"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { cerr << " <" << i->name << '>'; } cerr << "\n\n"; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << "\t--" << i->name; if(i->type != option::Bool) { cerr << " <arg>"; } if(i->short_name != '\0') { cerr << " (or -" << i->short_name << ')'; } - cerr << "\t... " << i->description << '\n'; + cerr << "\t" << i->description << '\n'; } if(handle_help) { - cerr << "\t--help (or -h)\t... show help information\n"; + cerr << "\t--help (or -h)\tshow help information\n"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { - cerr << "\t<" << i->name << ">\t... " << i->description << '\n'; + cerr << "\t<" << i->name << ">\t" << i->description << '\n'; } exit = true; }
ruediger/VobSub2SRT
4ed58c2abbe8206c9d56fabc4eb1942f201e598d
missing ;
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 9b3b3f6..72eb08f 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,312 +1,312 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; int y_threshold = 0; int min_width = 9; int min_height = 1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_option("y-threshold", y_threshold, "Y (luminance) threshold below which colors treated as black (Default: 0)"). add_option("min-width", min_width, "Minimum width in pixels to consider a subpicture for OCR (Default: 9)"). add_option("min-height", min_height, "Minimum height in pixels to consider a subpicture for OCR (Default: 1)"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Set Y threshold from command-line arg only if given if (y_threshold) { cout << "Using Y palette threshold: " << y_threshold << "\n"; } // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, y_threshold, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(width < (unsigned int)min_width || height < (unsigned int)min_height) { cerr << "WARNING: Image too small " << sub_counter << ", size: " << image_size << " bytes, " - << width << "x" << height << " pixels, expected at least " << min_width << "x" << min_height << "\n" + << width << "x" << height << " pixels, expected at least " << min_width << "x" << min_height << "\n"; continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
41c68442e55c327950dbe13cb0eec3c92bd6aaf3
Add --min-width, --min-height to elide spurious subpictures
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 82dfa81..9b3b3f6 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,307 +1,312 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; int y_threshold = 0; + int min_width = 9; + int min_height = 1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_option("y-threshold", y_threshold, "Y (luminance) threshold below which colors treated as black (Default: 0)"). + add_option("min-width", min_width, "Minimum width in pixels to consider a subpicture for OCR (Default: 9)"). + add_option("min-height", min_height, "Minimum height in pixels to consider a subpicture for OCR (Default: 1)"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Set Y threshold from command-line arg only if given if (y_threshold) { cout << "Using Y palette threshold: " << y_threshold << "\n"; } // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, y_threshold, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; - if(width == 0 or height == 0) { - cerr << "ERROR: Empty image " << sub_counter << ", width: " << width << ", height: " << height << ", size: " << image_size << "\n"; + if(width < (unsigned int)min_width || height < (unsigned int)min_height) { + cerr << "WARNING: Image too small " << sub_counter << ", size: " << image_size << " bytes, " + << width << "x" << height << " pixels, expected at least " << min_width << "x" << min_height << "\n" continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
1eb5896fb5bc2a9b02f146dd83a56a0ef0436633
Use default tesseract data path if none specified
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 82dfa81..e049aac 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,307 +1,311 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif +#define TESSERACT_DEFAULT_PATH "<builtin default>" #ifndef TESSERACT_DATA_PATH -#define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake +#define TESSERACT_DATA_PATH TESSERACT_DEFAULT_PATH #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; int y_threshold = 0; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_option("y-threshold", y_threshold, "Y (luminance) threshold below which colors treated as black (Default: 0)"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Set Y threshold from command-line arg only if given if (y_threshold) { cout << "Using Y palette threshold: " << y_threshold << "\n"; } // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, y_threshold, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract + char const *tess_path = tesseract_data_path.c_str(); + if (!strcmp(tess_path, TESSERACT_DEFAULT_PATH)) + tess_path = NULL; #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; - if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { + if(tess_base_api.Init(tess_path, tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else - TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params + TessBaseAPI::SimpleInit(tess_path, tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(width == 0 or height == 0) { cerr << "ERROR: Empty image " << sub_counter << ", width: " << width << ", height: " << height << ", size: " << image_size << "\n"; continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
f8737613e60fd705d3a75752b05ae4e8ac92270f
Y-threshold option converts all palette entries below it to black.
diff --git a/mplayer/spudec.c b/mplayer/spudec.c index b3960cc..f9f2e91 100644 --- a/mplayer/spudec.c +++ b/mplayer/spudec.c @@ -830,646 +830,665 @@ static void scale_image(int x, int y, scale_pixel* table_x, scale_pixel* table_y { int alpha[4]; int color[4]; unsigned int scale[4]; int base = table_y[y].position * spu->stride + table_x[x].position; int scaled = y * spu->scaled_stride + x; alpha[0] = canon_alpha(spu->aimage[base]); alpha[1] = canon_alpha(spu->aimage[base + 1]); alpha[2] = canon_alpha(spu->aimage[base + spu->stride]); alpha[3] = canon_alpha(spu->aimage[base + spu->stride + 1]); color[0] = spu->image[base]; color[1] = spu->image[base + 1]; color[2] = spu->image[base + spu->stride]; color[3] = spu->image[base + spu->stride + 1]; scale[0] = (table_x[x].left_up * table_y[y].left_up >> 16) * alpha[0]; if (table_y[y].left_up == 0x10000) // necessary to avoid overflow-case scale[0] = table_x[x].left_up * alpha[0]; scale[1] = (table_x[x].right_down * table_y[y].left_up >>16) * alpha[1]; scale[2] = (table_x[x].left_up * table_y[y].right_down >> 16) * alpha[2]; scale[3] = (table_x[x].right_down * table_y[y].right_down >> 16) * alpha[3]; spu->scaled_image[scaled] = (color[0] * scale[0] + color[1] * scale[1] + color[2] * scale[2] + color[3] * scale[3])>>24; spu->scaled_aimage[scaled] = (scale[0] + scale[1] + scale[2] + scale[3]) >> 16; if (spu->scaled_aimage[scaled]){ // ensure that MPlayer's simplified alpha-blending can not overflow spu->scaled_image[scaled] = FFMIN(spu->scaled_image[scaled], spu->scaled_aimage[scaled]); // convert to MPlayer-style alpha spu->scaled_aimage[scaled] = -spu->scaled_aimage[scaled]; } } #if 0 // R: removed sws scaling static void sws_spu_image(unsigned char *d1, unsigned char *d2, int dw, int dh, int ds, const unsigned char* s1, unsigned char* s2, int sw, int sh, int ss) { struct SwsContext *ctx; static SwsFilter filter; static int firsttime = 1; static float oldvar; int i; if (!firsttime && oldvar != spu_gaussvar) sws_freeVec(filter.lumH); if (firsttime) { filter.lumH = filter.lumV = filter.chrH = filter.chrV = sws_getGaussianVec(spu_gaussvar, 3.0); sws_normalizeVec(filter.lumH, 1.0); firsttime = 0; oldvar = spu_gaussvar; } ctx=sws_getContext(sw, sh, PIX_FMT_GRAY8, dw, dh, PIX_FMT_GRAY8, SWS_GAUSS, &filter, NULL, NULL); sws_scale(ctx,&s1,&ss,0,sh,&d1,&ds); for (i=ss*sh-1; i>=0; i--) if (!s2[i]) s2[i] = 255; //else s2[i] = 1; sws_scale(ctx,&s2,&ss,0,sh,&d2,&ds); for (i=ds*dh-1; i>=0; i--) if (d2[i]==0) d2[i] = 1; else if (d2[i]==255) d2[i] = 0; sws_freeContext(ctx); } #endif void spudec_draw_scaled(void *me, unsigned int dxs, unsigned int dys, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)) { spudec_handle_t *spu = me; scale_pixel *table_x; scale_pixel *table_y; if (spudec_visible(spu)) { // check if only forced subtitles are requested if( (spu->forced_subs_only) && !(spu->is_forced_sub) ){ return; } if (!(spu_aamode&16) && (spu->orig_frame_width == 0 || spu->orig_frame_height == 0 || (spu->orig_frame_width == dxs && spu->orig_frame_height == dys))) { spudec_draw(spu, draw_alpha); } else { if (spu->scaled_frame_width != dxs || spu->scaled_frame_height != dys) { /* Resizing is needed */ /* scaled_x = scalex * x / 0x100 scaled_y = scaley * y / 0x100 order of operations is important because of rounding. */ unsigned int scalex = 0x100 * dxs / spu->orig_frame_width; unsigned int scaley = 0x100 * dys / spu->orig_frame_height; spu->scaled_start_col = spu->start_col * scalex / 0x100; spu->scaled_start_row = spu->start_row * scaley / 0x100; spu->scaled_width = spu->width * scalex / 0x100; spu->scaled_height = spu->height * scaley / 0x100; /* Kludge: draw_alpha needs width multiple of 8 */ spu->scaled_stride = (spu->scaled_width + 7) & ~7; if (spu->scaled_image_size < spu->scaled_stride * spu->scaled_height) { if (spu->scaled_image) { free(spu->scaled_image); spu->scaled_image_size = 0; } spu->scaled_image = malloc(2 * spu->scaled_stride * spu->scaled_height); if (spu->scaled_image) { spu->scaled_image_size = spu->scaled_stride * spu->scaled_height; spu->scaled_aimage = spu->scaled_image + spu->scaled_image_size; } } if (spu->scaled_image) { unsigned int x, y; // needs to be 0-initialized because draw_alpha draws always a // multiple of 8 pixels. TODO: optimize if (spu->scaled_width & 7) memset(spu->scaled_image, 0, 2 * spu->scaled_image_size); if (spu->scaled_width <= 1 || spu->scaled_height <= 1) { goto nothing_to_do; } switch(spu_aamode&15) { case 4: #if 0 // R: no swscalar gaussian aa supported sws_spu_image(spu->scaled_image, spu->scaled_aimage, spu->scaled_width, spu->scaled_height, spu->scaled_stride, spu->image, spu->aimage, spu->width, spu->height, spu->stride); #else mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: no swsscalar gaussian aa supported"); #endif break; case 3: table_x = calloc(spu->scaled_width, sizeof(scale_pixel)); table_y = calloc(spu->scaled_height, sizeof(scale_pixel)); if (!table_x || !table_y) { mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: spudec_draw_scaled: calloc failed\n"); } scale_table(0, 0, spu->width - 1, spu->scaled_width - 1, table_x); scale_table(0, 0, spu->height - 1, spu->scaled_height - 1, table_y); for (y = 0; y < spu->scaled_height; y++) for (x = 0; x < spu->scaled_width; x++) scale_image(x, y, table_x, table_y, spu); free(table_x); free(table_y); break; case 0: /* no antialiasing */ for (y = 0; y < spu->scaled_height; ++y) { int unscaled_y = y * 0x100 / scaley; int strides = spu->stride * unscaled_y; int scaled_strides = spu->scaled_stride * y; for (x = 0; x < spu->scaled_width; ++x) { int unscaled_x = x * 0x100 / scalex; spu->scaled_image[scaled_strides + x] = spu->image[strides + unscaled_x]; spu->scaled_aimage[scaled_strides + x] = spu->aimage[strides + unscaled_x]; } } break; case 1: { /* Intermediate antialiasing. */ for (y = 0; y < spu->scaled_height; ++y) { const unsigned int unscaled_top = y * spu->orig_frame_height / dys; unsigned int unscaled_bottom = (y + 1) * spu->orig_frame_height / dys; if (unscaled_bottom >= spu->height) unscaled_bottom = spu->height - 1; for (x = 0; x < spu->scaled_width; ++x) { const unsigned int unscaled_left = x * spu->orig_frame_width / dxs; unsigned int unscaled_right = (x + 1) * spu->orig_frame_width / dxs; unsigned int color = 0; unsigned int alpha = 0; unsigned int walkx, walky; unsigned int base, tmp; if (unscaled_right >= spu->width) unscaled_right = spu->width - 1; for (walky = unscaled_top; walky <= unscaled_bottom; ++walky) for (walkx = unscaled_left; walkx <= unscaled_right; ++walkx) { base = walky * spu->stride + walkx; tmp = canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } base = y * spu->scaled_stride + x; spu->scaled_image[base] = alpha ? color / alpha : 0; spu->scaled_aimage[base] = alpha * (1 + unscaled_bottom - unscaled_top) * (1 + unscaled_right - unscaled_left); /* spu->scaled_aimage[base] = alpha * dxs * dys / spu->orig_frame_width / spu->orig_frame_height; */ if (spu->scaled_aimage[base]) { spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; } } } } break; case 2: { /* Best antialiasing. Very slow. */ /* Any pixel (x, y) represents pixels from the original rectangular region comprised between the columns unscaled_y and unscaled_y + 0x100 / scaley and the rows unscaled_x and unscaled_x + 0x100 / scalex The original rectangular region that the scaled pixel represents is cut in 9 rectangular areas like this: +---+-----------------+---+ | 1 | 2 | 3 | +---+-----------------+---+ | | | | | 4 | 5 | 6 | | | | | +---+-----------------+---+ | 7 | 8 | 9 | +---+-----------------+---+ The width of the left column is at most one pixel and it is never null and its right column is at a pixel boundary. The height of the top row is at most one pixel it is never null and its bottom row is at a pixel boundary. The width and height of region 5 are integral values. The width of the right column is what remains and is less than one pixel. The height of the bottom row is what remains and is less than one pixel. The row above 1, 2, 3 is unscaled_y. The row between 1, 2, 3 and 4, 5, 6 is top_low_row. The row between 4, 5, 6 and 7, 8, 9 is (unsigned int)unscaled_y_bottom. The row beneath 7, 8, 9 is unscaled_y_bottom. The column left of 1, 4, 7 is unscaled_x. The column between 1, 4, 7 and 2, 5, 8 is left_right_column. The column between 2, 5, 8 and 3, 6, 9 is (unsigned int)unscaled_x_right. The column right of 3, 6, 9 is unscaled_x_right. */ const double inv_scalex = (double) 0x100 / scalex; const double inv_scaley = (double) 0x100 / scaley; for (y = 0; y < spu->scaled_height; ++y) { const double unscaled_y = y * inv_scaley; const double unscaled_y_bottom = unscaled_y + inv_scaley; const unsigned int top_low_row = FFMIN(unscaled_y_bottom, unscaled_y + 1.0); const double top = top_low_row - unscaled_y; const unsigned int height = unscaled_y_bottom > top_low_row ? (unsigned int) unscaled_y_bottom - top_low_row : 0; const double bottom = unscaled_y_bottom > top_low_row ? unscaled_y_bottom - floor(unscaled_y_bottom) : 0.0; for (x = 0; x < spu->scaled_width; ++x) { const double unscaled_x = x * inv_scalex; const double unscaled_x_right = unscaled_x + inv_scalex; const unsigned int left_right_column = FFMIN(unscaled_x_right, unscaled_x + 1.0); const double left = left_right_column - unscaled_x; const unsigned int width = unscaled_x_right > left_right_column ? (unsigned int) unscaled_x_right - left_right_column : 0; const double right = unscaled_x_right > left_right_column ? unscaled_x_right - floor(unscaled_x_right) : 0.0; double color = 0.0; double alpha = 0.0; double tmp; unsigned int base; /* Now use these informations to compute a good alpha, and lightness. The sum is on each of the 9 region's surface and alpha and lightness. transformed alpha = sum(surface * alpha) / sum(surface) transformed color = sum(surface * alpha * color) / sum(surface * alpha) */ /* 1: top left part */ base = spu->stride * (unsigned int) unscaled_y; tmp = left * top * canon_alpha(spu->aimage[base + (unsigned int) unscaled_x]); alpha += tmp; color += tmp * spu->image[base + (unsigned int) unscaled_x]; /* 2: top center part */ if (width > 0) { unsigned int walkx; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { base = spu->stride * (unsigned int) unscaled_y + walkx; tmp = /* 1.0 * */ top * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 3: top right part */ if (right > 0.0) { base = spu->stride * (unsigned int) unscaled_y + (unsigned int) unscaled_x_right; tmp = right * top * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* 4: center left part */ if (height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { base = spu->stride * walky + (unsigned int) unscaled_x; tmp = left /* * 1.0 */ * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 5: center part */ if (width > 0 && height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { unsigned int walkx; base = spu->stride * walky; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { tmp = /* 1.0 * 1.0 * */ canon_alpha(spu->aimage[base + walkx]); alpha += tmp; color += tmp * spu->image[base + walkx]; } } } /* 6: center right part */ if (right > 0.0 && height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { base = spu->stride * walky + (unsigned int) unscaled_x_right; tmp = right /* * 1.0 */ * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 7: bottom left part */ if (bottom > 0.0) { base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x; tmp = left * bottom * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* 8: bottom center part */ if (width > 0 && bottom > 0.0) { unsigned int walkx; base = spu->stride * (unsigned int) unscaled_y_bottom; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { tmp = /* 1.0 * */ bottom * canon_alpha(spu->aimage[base + walkx]); alpha += tmp; color += tmp * spu->image[base + walkx]; } } /* 9: bottom right part */ if (right > 0.0 && bottom > 0.0) { base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x_right; tmp = right * bottom * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* Finally mix these transparency and brightness information suitably */ base = spu->scaled_stride * y + x; spu->scaled_image[base] = alpha > 0 ? color / alpha : 0; spu->scaled_aimage[base] = alpha * scalex * scaley / 0x10000; if (spu->scaled_aimage[base]) { spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; } } } } } nothing_to_do: /* Kludge: draw_alpha needs width multiple of 8. */ if (spu->scaled_width < spu->scaled_stride) for (y = 0; y < spu->scaled_height; ++y) { memset(spu->scaled_aimage + y * spu->scaled_stride + spu->scaled_width, 0, spu->scaled_stride - spu->scaled_width); } spu->scaled_frame_width = dxs; spu->scaled_frame_height = dys; } } if (spu->scaled_image){ switch (spu_alignment) { case 0: spu->scaled_start_row = dys*sub_pos/100; if (spu->scaled_start_row + spu->scaled_height > dys) spu->scaled_start_row = dys - spu->scaled_height; break; case 1: spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height/2; if (sub_pos >= 50 && spu->scaled_start_row + spu->scaled_height > dys) spu->scaled_start_row = dys - spu->scaled_height; break; case 2: spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height; break; } draw_alpha(spu->scaled_start_col, spu->scaled_start_row, spu->scaled_width, spu->scaled_height, spu->scaled_image, spu->scaled_aimage, spu->scaled_stride); spu->spu_changed = 0; } } } else { mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPU not displayed: start_pts=%d end_pts=%d now_pts=%d\n", spu->start_pts, spu->end_pts, spu->now_pts); } } void spudec_update_palette(void * this, unsigned int *palette) { spudec_handle_t *spu = this; if (spu && palette) { memcpy(spu->global_palette, palette, sizeof(spu->global_palette)); #if 0 // R: OSD stuff removed if(spu->hw_spu) spu->hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); #endif } } void spudec_set_font_factor(void * this, double factor) { spudec_handle_t *spu = this; spu->font_start_level = (int)(0xF0-(0xE0*factor)); } #ifndef AV_RB32 // R: AV_RB32 for older ffmpeg (libavutil) releases #ifndef __GNUC__ // only implemented the GCC version of AV_RB32 #error "Get a newer ffmpeg (libavutil) version" #endif /* code taken from ffmpeg/libavutil. intreadwrite.h and bswap.h common.h is copyright (c) 2006 Michael Niedermayer <[email protected]> bswap.h is copyright (C) 2006 by Michael Niedermayer <[email protected]> intreadwrite.h does not contain a specific copyright notice. the code is licensed under LGPL 2 with the following license header FFmpeg is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. FFmpeg is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with FFmpeg; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ union unaligned_32 { uint32_t l; } __attribute__((packed)) __attribute__((may_alias)); #define AV_RN32(p) (((const union unaligned_32 *) (p))->l) #ifdef AV_HAVE_BIGENDIAN // TODO add detection #define AV_RB32(p) AV_RN32(p) #else // little endian static __attribute__((always_inline)) inline uint32_t __attribute__((const)) av_bswap32(uint32_t x) { x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); x= (x>>16) | (x<<16); return x; } #define AV_RB32(p) av_bswap32(AV_RN32(p)) #endif // AV_HAVE_BIG_ENDIAN #endif // AV_RB32 static void spudec_parse_extradata(spudec_handle_t *this, uint8_t *extradata, int extradata_len) { uint8_t *buffer, *ptr; unsigned int *pal = this->global_palette, *cuspal = this->cuspal; unsigned int tridx; int i; if (extradata_len == 16*4) { for (i=0; i<16; i++) pal[i] = AV_RB32(extradata + i*4); this->auto_palette = 0; return; } if (!(ptr = buffer = malloc(extradata_len+1))) return; memcpy(buffer, extradata, extradata_len); buffer[extradata_len] = 0; do { if (*ptr == '#') continue; if (!strncmp(ptr, "size: ", 6)) sscanf(ptr + 6, "%dx%d", &this->orig_frame_width, &this->orig_frame_height); if (!strncmp(ptr, "palette: ", 9) && sscanf(ptr + 9, "%x, %x, %x, %x, %x, %x, %x, %x, " "%x, %x, %x, %x, %x, %x, %x, %x", &pal[ 0], &pal[ 1], &pal[ 2], &pal[ 3], &pal[ 4], &pal[ 5], &pal[ 6], &pal[ 7], &pal[ 8], &pal[ 9], &pal[10], &pal[11], &pal[12], &pal[13], &pal[14], &pal[15]) == 16) { for (i=0; i<16; i++) pal[i] = vobsub_palette_to_yuv(pal[i]); this->auto_palette = 0; } if (!strncasecmp(ptr, "forced subs: on", 15)) this->forced_subs_only = 1; if (!strncmp(ptr, "custom colors: ON, tridx: ", 26) && sscanf(ptr + 26, "%x, colors: %x, %x, %x, %x", &tridx, cuspal+0, cuspal+1, cuspal+2, cuspal+3) == 5) { for (i=0; i<4; i++) { cuspal[i] = vobsub_rgb_to_yuv(cuspal[i]); if (tridx & (1 << (12-4*i))) cuspal[i] |= 1 << 31; } this->custom = 1; } } while ((ptr=strchr(ptr,'\n')) && *++ptr); free(buffer); } -void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len) +/** + * Test whether Y component of YUV palette entry is under palette threshold. + */ +static int spudec_yuv_under_threshold(unsigned int yuv, unsigned int y_threshold) +{ + return (yuv >> 16 & 0xFF) < y_threshold; +} + +void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len, unsigned int y_threshold) { + int i; spudec_handle_t *this = calloc(1, sizeof(spudec_handle_t)); if (this){ this->orig_frame_height = frame_height; this->orig_frame_width = frame_width; // set up palette: if (palette) memcpy(this->global_palette, palette, sizeof(this->global_palette)); else this->auto_palette = 1; if (extradata) spudec_parse_extradata(this, extradata, extradata_len); /* XXX Although the video frame is some size, the SPU frame is always maximum size i.e. 720 wide and 576 or 480 high */ // For HD files in MKV the VobSub resolution can be higher though, // see largeres_vobsub.mkv if (this->orig_frame_width <= 720 && this->orig_frame_height <= 576) { this->orig_frame_width = 720; if (this->orig_frame_height == 480 || this->orig_frame_height == 240) this->orig_frame_height = 480; else this->orig_frame_height = 576; } } else mp_msg(MSGT_SPUDEC,MSGL_FATAL, "FATAL: spudec_init: calloc"); + +// Text with overlapping softer edges can reduce the efficacy of the OCR. +// Replace any palette values below threshold with black to create +// distinct characters. + for (i=0; i<16; i++) { + if (spudec_yuv_under_threshold(this->global_palette[i],y_threshold)) { + this->global_palette[i]=0; + } + } + return this; } -void *spudec_new(unsigned int *palette) +void *spudec_new(unsigned int *palette, unsigned int y_threshold) { - return spudec_new_scaled(palette, 0, 0, NULL, 0); + return spudec_new_scaled(palette, 0, 0, NULL, 0, y_threshold); } void spudec_free(void *this) { spudec_handle_t *spu = this; if (spu) { while (spu->queue_head) spudec_free_packet(spudec_dequeue_packet(spu)); free(spu->packet); spu->packet = NULL; free(spu->scaled_image); spu->scaled_image = NULL; free(spu->image); spu->image = NULL; spu->aimage = NULL; free(spu->pal_image); spu->pal_image = NULL; spu->image_size = 0; spu->pal_width = spu->pal_height = 0; free(spu); } } #if 0 // R: not necessary void spudec_set_hw_spu(void *this, const vo_functions_t *hw_spu) { spudec_handle_t *spu = this; if (!spu) return; spu->hw_spu = hw_spu; hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); } #endif #define MP_NOPTS_VALUE (-1LL<<63) //both int64_t and double should be able to represent this exactly /** * palette must contain at least 256 32-bit entries, otherwise crashes * are possible */ void spudec_set_paletted(void *this, const uint8_t *pal_img, int pal_stride, const void *palette, int x, int y, int w, int h, double pts, double endpts) { int i; uint16_t g8a8_pal[256]; packet_t *packet; const uint32_t *pal = palette; spudec_handle_t *spu = this; uint8_t *img; uint8_t *aimg; int stride = (w + 7) & ~7; if ((unsigned)w >= 0x8000 || (unsigned)h > 0x4000) return; packet = calloc(1, sizeof(packet_t)); packet->is_decoded = 1; packet->width = w; packet->height = h; packet->stride = stride; packet->start_col = x; packet->start_row = y; packet->data_len = 2 * stride * h; if (packet->data_len) { // size 0 is a special "clear" packet packet->packet = malloc(packet->data_len); img = packet->packet; aimg = packet->packet + stride * h; for (i = 0; i < 256; i++) { uint32_t pixel = pal[i]; int alpha = pixel >> 24; int gray = (((pixel & 0x000000ff) >> 0) + ((pixel & 0x0000ff00) >> 7) + ((pixel & 0x00ff0000) >> 16)) >> 2; gray = FFMIN(gray, alpha); g8a8_pal[i] = (-alpha << 8) | gray; } pal2gray_alpha(g8a8_pal, pal_img, pal_stride, img, aimg, stride, w, h); } packet->start_pts = 0; packet->end_pts = 0x7fffffff; if (pts != MP_NOPTS_VALUE) packet->start_pts = pts * 90000; if (endpts != MP_NOPTS_VALUE) packet->end_pts = endpts * 90000; spudec_queue_packet(spu, packet); } // R: added to extract data void spudec_get_data(void *this, const unsigned char **image, size_t *image_size, unsigned *width, unsigned *height, unsigned *stride, unsigned *start_pts, unsigned *end_pts) { spudec_handle_t *spu = this; *image = spu->image; *image_size = spu->image_size; *width = spu->width; *height = spu->height; *stride = spu->stride; *start_pts = spu->start_pts; *end_pts = spu->end_pts; } diff --git a/mplayer/spudec.h b/mplayer/spudec.h index 844aed7..c79c1e0 100644 --- a/mplayer/spudec.h +++ b/mplayer/spudec.h @@ -1,58 +1,58 @@ /* * This file is part of MPlayer. * * MPlayer is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MPLAYER_SPUDEC_H #define MPLAYER_SPUDEC_H //#include "libvo/video_out.h" #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif void spudec_heartbeat(void *self, unsigned int pts100); void spudec_assemble(void *self, unsigned char *packet, unsigned int len, int pts100); void spudec_draw(void *self, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)); void spudec_draw_scaled(void *self, unsigned int dxs, unsigned int dys, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)); int spudec_apply_palette_crop(void *self, uint32_t palette, int sx, int ex, int sy, int ey); void spudec_update_palette(void *self, unsigned int *palette); -void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len); -void *spudec_new(unsigned int *palette); +void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len, unsigned int y_threshold); +void *spudec_new(unsigned int *palette, unsigned int y_threshold); void spudec_free(void *self); void spudec_reset(void *self); // called after seek int spudec_visible(void *self); // check if spu is visible void spudec_set_font_factor(void * self, double factor); // sets the equivalent to ffactor //void spudec_set_hw_spu(void *self, const vo_functions_t *hw_spu); int spudec_changed(void *self); void spudec_calc_bbox(void *me, unsigned int dxs, unsigned int dys, unsigned int* bbox); void spudec_set_forced_subs_only(void * const self, const unsigned int flag); void spudec_set_paletted(void *self, const uint8_t *pal_img, int stride, const void *palette, int x, int y, int w, int h, double pts, double endpts); /// call this after spudec_assemble and spudec_heartbeat to get the packet data void spudec_get_data(void *self, const unsigned char **image, size_t *image_size, unsigned *width, unsigned *height, unsigned *stride, unsigned *start_pts, unsigned *end_pts); #ifdef __cplusplus } #endif #endif /* MPLAYER_SPUDEC_H */ diff --git a/mplayer/vobsub.c b/mplayer/vobsub.c index 3bac2ac..a6bd324 100644 --- a/mplayer/vobsub.c +++ b/mplayer/vobsub.c @@ -437,1021 +437,1021 @@ static int mpeg_run(mpeg_t *mpeg) mpeg->packet_size = len - ((unsigned int) mpeg_tell(mpeg) - idx); if (mpeg->packet_reserve < mpeg->packet_size) { if (mpeg->packet) free(mpeg->packet); mpeg->packet = malloc(mpeg->packet_size); if (mpeg->packet) mpeg->packet_reserve = mpeg->packet_size; } if (mpeg->packet == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); mpeg->packet_reserve = 0; mpeg->packet_size = 0; return -1; } if (rar_read(mpeg->packet, mpeg->packet_size, 1, mpeg->stream) != 1) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "fread failure"); mpeg->packet_size = 0; return -1; } idx = len; } break; case 0xbe: /* Padding */ if (rar_read(buf, 2, 1, mpeg->stream) != 1) return -1; len = buf[0] << 8 | buf[1]; if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) return -1; mpeg->padding_was_here = 1; break; default: if (0xc0 <= buf[3] && buf[3] < 0xf0) { /* MPEG audio or video */ if (rar_read(buf, 2, 1, mpeg->stream) != 1) return -1; len = buf[0] << 8 | buf[1]; if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) return -1; } else { mp_msg(MSGT_VOBSUB, MSGL_ERR, "unknown header 0x%02X%02X%02X%02X\n", buf[0], buf[1], buf[2], buf[3]); return -1; } } return 0; } /********************************************************************** * Packet queue **********************************************************************/ typedef struct { unsigned int pts100; off_t filepos; unsigned int size; unsigned char *data; } packet_t; typedef struct { char *id; packet_t *packets; unsigned int packets_reserve; unsigned int packets_size; unsigned int current_index; } packet_queue_t; static void packet_construct(packet_t *pkt) { pkt->pts100 = 0; pkt->filepos = 0; pkt->size = 0; pkt->data = NULL; } static void packet_destroy(packet_t *pkt) { if (pkt->data) free(pkt->data); } static void packet_queue_construct(packet_queue_t *queue) { queue->id = NULL; queue->packets = NULL; queue->packets_reserve = 0; queue->packets_size = 0; queue->current_index = 0; } static void packet_queue_destroy(packet_queue_t *queue) { if (queue->packets) { while (queue->packets_size--) packet_destroy(queue->packets + queue->packets_size); free(queue->packets); } return; } /* Make sure there is enough room for needed_size packets in the packet queue. */ static int packet_queue_ensure(packet_queue_t *queue, unsigned int needed_size) { if (queue->packets_reserve < needed_size) { if (queue->packets) { packet_t *tmp = realloc(queue->packets, 2 * queue->packets_reserve * sizeof(packet_t)); if (tmp == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "realloc failure"); return -1; } queue->packets = tmp; queue->packets_reserve *= 2; } else { queue->packets = malloc(sizeof(packet_t)); if (queue->packets == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); return -1; } queue->packets_reserve = 1; } } return 0; } /* add one more packet */ static int packet_queue_grow(packet_queue_t *queue) { if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) return -1; packet_construct(queue->packets + queue->packets_size); ++queue->packets_size; return 0; } /* insert a new packet, duplicating pts from the current one */ static int packet_queue_insert(packet_queue_t *queue) { packet_t *pkts; if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) return -1; /* XXX packet_size does not reflect the real thing here, it will be updated a bit later */ memmove(queue->packets + queue->current_index + 2, queue->packets + queue->current_index + 1, sizeof(packet_t) * (queue->packets_size - queue->current_index - 1)); pkts = queue->packets + queue->current_index; ++queue->packets_size; ++queue->current_index; packet_construct(pkts + 1); pkts[1].pts100 = pkts[0].pts100; pkts[1].filepos = pkts[0].filepos; return 0; } /********************************************************************** * Vobsub **********************************************************************/ typedef struct { unsigned int palette[16]; int delay; unsigned int have_palette; unsigned int orig_frame_width, orig_frame_height; unsigned int origin_x, origin_y; /* index */ packet_queue_t *spu_streams; unsigned int spu_streams_size; unsigned int spu_streams_current; unsigned int spu_valid_streams_size; } vobsub_t; /* Make sure that the spu stream idx exists. */ static int vobsub_ensure_spu_stream(vobsub_t *vob, unsigned int index) { if (index >= vob->spu_streams_size) { /* This is a new stream */ if (vob->spu_streams) { packet_queue_t *tmp = realloc(vob->spu_streams, (index + 1) * sizeof(packet_queue_t)); if (tmp == NULL) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: realloc failure"); return -1; } vob->spu_streams = tmp; } else { vob->spu_streams = malloc((index + 1) * sizeof(packet_queue_t)); if (vob->spu_streams == NULL) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: malloc failure"); return -1; } } while (vob->spu_streams_size <= index) { packet_queue_construct(vob->spu_streams + vob->spu_streams_size); ++vob->spu_streams_size; } } return 0; } static int vobsub_add_id(vobsub_t *vob, const char *id, size_t idlen, const unsigned int index) { if (vobsub_ensure_spu_stream(vob, index) < 0) return -1; if (id && idlen) { if (vob->spu_streams[index].id) free(vob->spu_streams[index].id); vob->spu_streams[index].id = malloc(idlen + 1); if (vob->spu_streams[index].id == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "vobsub_add_id: malloc failure"); return -1; } vob->spu_streams[index].id[idlen] = 0; memcpy(vob->spu_streams[index].id, id, idlen); } vob->spu_streams_current = index; mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VOBSUB_ID=%d\n", index); if (id && idlen) mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VSID_%d_LANG=%s\n", index, vob->spu_streams[index].id); mp_msg(MSGT_VOBSUB, MSGL_V, "[vobsub] subtitle (vobsubid): %d language %s\n", index, vob->spu_streams[index].id); return 0; } static int vobsub_add_timestamp(vobsub_t *vob, off_t filepos, int ms) { packet_queue_t *queue; packet_t *pkt; if (vob->spu_streams == 0) { mp_msg(MSGT_VOBSUB, MSGL_WARN, "[vobsub] warning, binning some index entries. Check your index file\n"); return -1; } queue = vob->spu_streams + vob->spu_streams_current; if (packet_queue_grow(queue) >= 0) { pkt = queue->packets + (queue->packets_size - 1); pkt->filepos = filepos; pkt->pts100 = ms < 0 ? UINT_MAX : (unsigned int)ms * 90; return 0; } return -1; } static int vobsub_parse_id(vobsub_t *vob, const char *line) { // id: xx, index: n size_t idlen; const char *p, *q; p = line; while (isspace(*p)) ++p; q = p; while (isalpha(*q)) ++q; idlen = q - p; if (idlen == 0) return -1; ++q; while (isspace(*q)) ++q; if (strncmp("index:", q, 6)) return -1; q += 6; while (isspace(*q)) ++q; if (!isdigit(*q)) return -1; return vobsub_add_id(vob, p, idlen, atoi(q)); } static int vobsub_parse_timestamp(vobsub_t *vob, const char *line) { // timestamp: HH:MM:SS.mmm, filepos: 0nnnnnnnnn int h, m, s, ms; off_t filepos; if (sscanf(line, " %02d:%02d:%02d:%03d, filepos: %09"PRIx64"", &h, &m, &s, &ms, &filepos) != 5) return -1; return vobsub_add_timestamp(vob, filepos, vob->delay + ms + 1000 * (s + 60 * (m + 60 * h))); } static int vobsub_parse_origin(vobsub_t *vob, const char *line) { // org: X,Y unsigned x, y; if (sscanf(line, " %u,%u", &x, &y) == 2) { vob->origin_x = x; vob->origin_y = y; return 0; } return -1; } /* * The code for av_clip_uint8_c is copied from libavutil! * See libavutil/common.h. The copyright for av_clip_uint8_c is: * * copyright (c) 2006 Michael Niedermayer <[email protected]> * * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Clip a signed integer value into the 0-255 range. * @param a value to clip * @return clipped value */ static __attribute__((always_inline)) inline __attribute__((const)) uint8_t av_clip_uint8_c(int a) { if (a&(~0xFF)) return (-a)>>31; else return a; } #ifndef av_clip_uint8 # define av_clip_uint8 av_clip_uint8_c #endif unsigned int vobsub_palette_to_yuv(unsigned int pal) { int r, g, b, y, u, v; // Palette in idx file is not rgb value, it was calculated by wrong formula. // Here's reversed formula of the one used to generate palette in idx file. r = pal >> 16 & 0xff; g = pal >> 8 & 0xff; b = pal & 0xff; y = av_clip_uint8( 0.1494 * r + 0.6061 * g + 0.2445 * b); u = av_clip_uint8( 0.6066 * r - 0.4322 * g - 0.1744 * b + 128); v = av_clip_uint8(-0.08435 * r - 0.3422 * g + 0.4266 * b + 128); y = y * 219 / 255 + 16; return y << 16 | u << 8 | v; } unsigned int vobsub_rgb_to_yuv(unsigned int rgb) { int r, g, b, y, u, v; r = rgb >> 16 & 0xff; g = rgb >> 8 & 0xff; b = rgb & 0xff; y = ( 0.299 * r + 0.587 * g + 0.114 * b) * 219 / 255 + 16.5; u = (-0.16874 * r - 0.33126 * g + 0.5 * b) * 224 / 255 + 128.5; v = ( 0.5 * r - 0.41869 * g - 0.08131 * b) * 224 / 255 + 128.5; return y << 16 | u << 8 | v; } static int vobsub_parse_delay(vobsub_t *vob, const char *line) { int h, m, s, ms; int forward = 1; if (*(line + 7) == '+') { forward = 1; line++; } else if (*(line + 7) == '-') { forward = -1; line++; } mp_msg(MSGT_SPUDEC, MSGL_V, "forward=%d", forward); h = atoi(line + 7); mp_msg(MSGT_VOBSUB, MSGL_V, "h=%d,", h); m = atoi(line + 10); mp_msg(MSGT_VOBSUB, MSGL_V, "m=%d,", m); s = atoi(line + 13); mp_msg(MSGT_VOBSUB, MSGL_V, "s=%d,", s); ms = atoi(line + 16); mp_msg(MSGT_VOBSUB, MSGL_V, "ms=%d", ms); vob->delay = (ms + 1000 * (s + 60 * (m + 60 * h))) * forward; return 0; } static int vobsub_set_lang(const char *line) { if (vobsub_id == -1) vobsub_id = atoi(line + 8); // 8 == strlen("langidx:") return 0; } static int vobsub_parse_one_line(vobsub_t *vob, rar_stream_t *fd, unsigned char **extradata, unsigned int *extradata_len) { ssize_t line_size; int res = -1; size_t line_reserve = 0; char *line = NULL; unsigned char *tmp; do { line_size = vobsub_getline(&line, &line_reserve, fd); if (line_size < 0 || line_size > 1000000 || *extradata_len+line_size > 10000000) { break; } tmp = realloc(*extradata, *extradata_len+line_size+1); if(!tmp) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR out of memory"); break; } *extradata = tmp; memcpy(*extradata+*extradata_len, line, line_size); *extradata_len += line_size; (*extradata)[*extradata_len] = 0; if (*line == 0 || *line == '\r' || *line == '\n' || *line == '#') continue; else if (strncmp("langidx:", line, 8) == 0) res = vobsub_set_lang(line); else if (strncmp("delay:", line, 6) == 0) res = vobsub_parse_delay(vob, line); else if (strncmp("id:", line, 3) == 0) res = vobsub_parse_id(vob, line + 3); else if (strncmp("org:", line, 4) == 0) res = vobsub_parse_origin(vob, line + 4); else if (strncmp("timestamp:", line, 10) == 0) res = vobsub_parse_timestamp(vob, line + 10); else { //mp_msg(MSGT_VOBSUB, MSGL_V, "vobsub: ignoring %s", line); /* size, palette, forced subs: on, and custom colors: ON, tridx are handled by spudec_parse_extradata in spudec.c */ continue; } if (res < 0) mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR in %s", line); break; } while (1); if (line) free(line); return res; } int vobsub_parse_ifo(void* this, const char *const name, unsigned int *palette, unsigned int *width, unsigned int *height, int force, int sid, char *langid) { vobsub_t *vob = this; int res = -1; rar_stream_t *fd = rar_open(name, "rb"); if (fd == NULL) { //if (force) //mp_msg(MSGT_VOBSUB, MSGL_WARN, "VobSub: Can't open IFO file\n"); } else { // parse IFO header unsigned char block[0x800]; const char *const ifo_magic = "DVDVIDEO-VTS"; if (rar_read(block, sizeof(block), 1, fd) != 1) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO header\n"); } else if (memcmp(block, ifo_magic, strlen(ifo_magic) + 1)) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Bad magic in IFO header\n"); else { unsigned long pgci_sector = block[0xcc] << 24 | block[0xcd] << 16 | block[0xce] << 8 | block[0xcf]; int standard = (block[0x200] & 0x30) >> 4; int resolution = (block[0x201] & 0x0c) >> 2; *height = standard ? 576 : 480; *width = 0; switch (resolution) { case 0x0: *width = 720; break; case 0x1: *width = 704; break; case 0x2: *width = 352; break; case 0x3: *width = 352; *height /= 2; break; default: mp_msg(MSGT_VOBSUB, MSGL_WARN, "Vobsub: Unknown resolution %d \n", resolution); } if (langid && 0 <= sid && sid < 32) { unsigned char *tmp = block + 0x256 + sid * 6 + 2; langid[0] = tmp[0]; langid[1] = tmp[1]; langid[2] = 0; } if (rar_seek(fd, pgci_sector * sizeof(block), SEEK_SET) || rar_read(block, sizeof(block), 1, fd) != 1) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO PGCI\n"); else { unsigned long idx; unsigned long pgc_offset = block[0xc] << 24 | block[0xd] << 16 | block[0xe] << 8 | block[0xf]; for (idx = 0; idx < 16; ++idx) { unsigned char *p = block + pgc_offset + 0xa4 + 4 * idx; palette[idx] = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; } if (vob) vob->have_palette = 1; res = 0; } } rar_close(fd); } return res; } void *vobsub_open(const char *const name, const char *const ifo, - const int force, void** spu) + const int force, unsigned int y_threshold, void** spu) { unsigned char *extradata = NULL; unsigned int extradata_len = 0; vobsub_t *vob = calloc(1, sizeof(vobsub_t)); if (spu) *spu = NULL; if (vobsubid == -2) vobsubid = vobsub_id; if (vob) { char *buf; buf = malloc(strlen(name) + 5); if (buf) { rar_stream_t *fd; mpeg_t *mpg; /* read in the info file */ if (!ifo) { strcpy(buf, name); strcat(buf, ".ifo"); vobsub_parse_ifo(vob, buf, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); } else vobsub_parse_ifo(vob, ifo, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); /* read in the index */ strcpy(buf, name); strcat(buf, ".idx"); fd = rar_open(buf, "rb"); if (fd == NULL) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open IDX file\n"); else { free(buf); free(vob); return NULL; } } else { while (vobsub_parse_one_line(vob, fd, &extradata, &extradata_len) >= 0) /* NOOP */ ; rar_close(fd); } if (spu) - *spu = spudec_new_scaled(vob->palette, vob->orig_frame_width, vob->orig_frame_height, extradata, extradata_len); + *spu = spudec_new_scaled(vob->palette, vob->orig_frame_width, vob->orig_frame_height, extradata, extradata_len, y_threshold); if (extradata) free(extradata); /* read the indexed mpeg_stream */ strcpy(buf, name); strcat(buf, ".sub"); mpg = mpeg_open(buf); if (mpg == NULL) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open SUB file\n"); else { free(buf); free(vob); return NULL; } } else { long last_pts_diff = 0; while (!mpeg_eof(mpg)) { off_t pos = mpeg_tell(mpg); if (mpeg_run(mpg) < 0) { if (!mpeg_eof(mpg)) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: mpeg_run error\n"); break; } if (mpg->packet_size) { if ((mpg->aid & 0xe0) == 0x20) { unsigned int sid = mpg->aid & 0x1f; if (vobsub_ensure_spu_stream(vob, sid) >= 0) { packet_queue_t *queue = vob->spu_streams + sid; /* get the packet to fill */ if (queue->packets_size == 0 && packet_queue_grow(queue) < 0) abort(); while (queue->current_index + 1 < queue->packets_size && queue->packets[queue->current_index + 1].filepos <= pos) ++queue->current_index; if (queue->current_index < queue->packets_size) { packet_t *pkt; if (queue->packets[queue->current_index].data) { /* insert a new packet and fix the PTS ! */ packet_queue_insert(queue); queue->packets[queue->current_index].pts100 = mpg->pts + last_pts_diff; } pkt = queue->packets + queue->current_index; if (pkt->pts100 != UINT_MAX) { if (queue->packets_size > 1) last_pts_diff = pkt->pts100 - mpg->pts; else pkt->pts100 = mpg->pts; if (mpg->merge && queue->current_index > 0) { packet_t *last = &queue->packets[queue->current_index - 1]; pkt->pts100 = last->pts100; } mpg->merge = 0; /* FIXME: should not use mpg_sub internal informations, make a copy */ pkt->data = mpg->packet; pkt->size = mpg->packet_size; mpg->packet = NULL; mpg->packet_reserve = 0; mpg->packet_size = 0; } } } else mp_msg(MSGT_VOBSUB, MSGL_WARN, "don't know what to do with subtitle #%u\n", sid); } } } vob->spu_streams_current = vob->spu_streams_size; while (vob->spu_streams_current-- > 0) { vob->spu_streams[vob->spu_streams_current].current_index = 0; if (vobsubid == vob->spu_streams_current || vob->spu_streams[vob->spu_streams_current].packets_size > 0) ++vob->spu_valid_streams_size; } mpeg_free(mpg); } free(buf); } } return vob; } void vobsub_close(void *this) { vobsub_t *vob = this; if (vob->spu_streams) { while (vob->spu_streams_size--) packet_queue_destroy(vob->spu_streams + vob->spu_streams_size); free(vob->spu_streams); } free(vob); } unsigned int vobsub_get_indexes_count(void *vobhandle) { vobsub_t *vob = vobhandle; return vob->spu_valid_streams_size; } char *vobsub_get_id(void *vobhandle, unsigned int index) { vobsub_t *vob = vobhandle; return (index < vob->spu_streams_size) ? vob->spu_streams[index].id : NULL; } int vobsub_get_id_by_index(void *vobhandle, unsigned int index) { vobsub_t *vob = vobhandle; int i, j; if (vob == NULL) return -1; for (i = 0, j = 0; i < vob->spu_streams_size; ++i) if (i == vobsubid || vob->spu_streams[i].packets_size > 0) { if (j == index) return i; ++j; } return -1; } int vobsub_get_index_by_id(void *vobhandle, int id) { vobsub_t *vob = vobhandle; int i, j; if (vob == NULL || id < 0 || id >= vob->spu_streams_size) return -1; if (id != vobsubid && !vob->spu_streams[id].packets_size) return -1; for (i = 0, j = 0; i < id; ++i) if (i == vobsubid || vob->spu_streams[i].packets_size > 0) ++j; return j; } int vobsub_set_from_lang(void *vobhandle, char const *lang) { int i; vobsub_t *vob= vobhandle; while (lang && strlen(lang) >= 2) { for (i = 0; i < vob->spu_streams_size; i++) if (vob->spu_streams[i].id) if ((strncmp(vob->spu_streams[i].id, lang, 2) == 0)) { vobsub_id = i; mp_msg(MSGT_VOBSUB, MSGL_INFO, "Selected VOBSUB language: %d language: %s\n", i, vob->spu_streams[i].id); return 0; } lang+=2;while (lang[0]==',' || lang[0]==' ') ++lang; } mp_msg(MSGT_VOBSUB, MSGL_WARN, "No matching VOBSUB language found!\n"); return -1; } /// make sure we seek to the first packet of packets having same pts values. static void vobsub_queue_reseek(packet_queue_t *queue, unsigned int pts100) { int reseek_count = 0; unsigned int lastpts = 0; if (queue->current_index > 0 && (queue->packets[queue->current_index].pts100 == UINT_MAX || queue->packets[queue->current_index].pts100 > pts100)) { // possible pts seek previous, try to check it. int i = 1; while (queue->current_index >= i && queue->packets[queue->current_index-i].pts100 == UINT_MAX) ++i; if (queue->current_index >= i && queue->packets[queue->current_index-i].pts100 > pts100) // pts seek previous confirmed, reseek from beginning queue->current_index = 0; } while (queue->current_index < queue->packets_size && queue->packets[queue->current_index].pts100 <= pts100) { lastpts = queue->packets[queue->current_index].pts100; ++queue->current_index; ++reseek_count; } while (reseek_count-- && --queue->current_index) { if (queue->packets[queue->current_index-1].pts100 != UINT_MAX && queue->packets[queue->current_index-1].pts100 != lastpts) break; } } int vobsub_get_packet(void *vobhandle, float pts, void** data, int* timestamp) { vobsub_t *vob = vobhandle; unsigned int pts100 = 90000 * pts; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { packet_queue_t *queue = vob->spu_streams + vobsub_id; vobsub_queue_reseek(queue, pts100); while (queue->current_index < queue->packets_size) { packet_t *pkt = queue->packets + queue->current_index; if (pkt->pts100 != UINT_MAX) if (pkt->pts100 <= pts100) { ++queue->current_index; *data = pkt->data; *timestamp = pkt->pts100; return pkt->size; } else break; else ++queue->current_index; } } return -1; } int vobsub_get_next_packet(void *vobhandle, void** data, int* timestamp) { vobsub_t *vob = vobhandle; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { packet_queue_t *queue = vob->spu_streams + vobsub_id; if (queue->current_index < queue->packets_size) { packet_t *pkt = queue->packets + queue->current_index; ++queue->current_index; *data = pkt->data; *timestamp = pkt->pts100; return pkt->size; } } return -1; } void vobsub_seek(void * vobhandle, float pts) { vobsub_t * vob = vobhandle; packet_queue_t * queue; int seek_pts100 = pts * 90000; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { /* do not seek if we don't know the id */ if (vobsub_get_id(vob, vobsub_id) == NULL) return; queue = vob->spu_streams + vobsub_id; queue->current_index = 0; vobsub_queue_reseek(queue, seek_pts100); } } void vobsub_reset(void *vobhandle) { vobsub_t *vob = vobhandle; if (vob->spu_streams) { unsigned int n = vob->spu_streams_size; while (n-- > 0) vob->spu_streams[n].current_index = 0; } } #if 0 // R: no output needed /********************************************************************** * Vobsub output **********************************************************************/ typedef struct { FILE *fsub; FILE *fidx; unsigned int aid; } vobsub_out_t; static void create_idx(vobsub_out_t *me, const unsigned int *palette, unsigned int orig_width, unsigned int orig_height) { int i; fprintf(me->fidx, "# VobSub index file, v7 (do not modify this line!)\n" "#\n" "# Generated by %s\n" "# See <URL:http://www.mplayerhq.hu/> for more information about MPlayer\n" "# See <URL:http://wiki.multimedia.cx/index.php?title=VOBsub> for more information about Vobsub\n" "#\n" "size: %ux%u\n", mplayer_version, orig_width, orig_height); if (palette) { fputs("palette:", me->fidx); for (i = 0; i < 16; ++i) { const double y = palette[i] >> 16 & 0xff, u = (palette[i] >> 8 & 0xff) - 128.0, v = (palette[i] & 0xff) - 128.0; if (i) putc(',', me->fidx); fprintf(me->fidx, " %02x%02x%02x", av_clip_uint8(y + 1.4022 * u), av_clip_uint8(y - 0.3456 * u - 0.7145 * v), av_clip_uint8(y + 1.7710 * v)); } putc('\n', me->fidx); } fprintf(me->fidx, "# ON: displays only forced subtitles, OFF: shows everything\n" "forced subs: OFF\n"); } void *vobsub_out_open(const char *basename, const unsigned int *palette, unsigned int orig_width, unsigned int orig_height, const char *id, unsigned int index) { vobsub_out_t *result = NULL; char *filename; filename = malloc(strlen(basename) + 5); if (filename) { result = malloc(sizeof(vobsub_out_t)); if (result) { result->aid = index; strcpy(filename, basename); strcat(filename, ".sub"); result->fsub = fopen(filename, "ab"); if (result->fsub == NULL) perror("Error: vobsub_out_open subtitle file open failed"); strcpy(filename, basename); strcat(filename, ".idx"); result->fidx = fopen(filename, "ab"); if (result->fidx) { if (ftell(result->fidx) == 0) { create_idx(result, palette, orig_width, orig_height); /* Make the selected language the default language */ fprintf(result->fidx, "\n# Language index in use\nlangidx: %u\n", index); } fprintf(result->fidx, "\nid: %s, index: %u\n", id ? id : "xx", index); /* So that we can check the file now */ fflush(result->fidx); } else perror("Error: vobsub_out_open index file open failed"); free(filename); } } return result; } void vobsub_out_close(void *me) { vobsub_out_t *vob = me; if (vob->fidx) fclose(vob->fidx); if (vob->fsub) fclose(vob->fsub); free(vob); } void vobsub_out_output(void *me, const unsigned char *packet, int len, double pts) { static double last_pts; static int last_pts_set = 0; vobsub_out_t *vob = me; if (vob->fsub) { /* Windows' Vobsub require that every packet is exactly 2kB long */ unsigned char buffer[2048]; unsigned char *p; int remain = 2048; /* Do not output twice a line with the same timestamp, this breaks Windows' Vobsub */ if (vob->fidx && (!last_pts_set || last_pts != pts)) { static unsigned int last_h = 9999, last_m = 9999, last_s = 9999, last_ms = 9999; unsigned int h, m, ms; double s; s = pts; h = s / 3600; s -= h * 3600; m = s / 60; s -= m * 60; ms = (s - (unsigned int) s) * 1000; if (ms >= 1000) /* prevent overflows or bad float stuff */ ms = 0; if (h != last_h || m != last_m || (unsigned int) s != last_s || ms != last_ms) { fprintf(vob->fidx, "timestamp: %02u:%02u:%02u:%03u, filepos: %09lx\n", h, m, (unsigned int) s, ms, ftell(vob->fsub)); last_h = h; last_m = m; last_s = (unsigned int) s; last_ms = ms; } } last_pts = pts; last_pts_set = 1; /* Packet start code: Windows' Vobsub needs this */ p = buffer; *p++ = 0; /* 0x00 */ *p++ = 0; *p++ = 1; *p++ = 0xba; *p++ = 0x40; memset(p, 0, 9); p += 9; { /* Packet */ static unsigned char last_pts[5] = { 0, 0, 0, 0, 0}; unsigned char now_pts[5]; int pts_len, pad_len, datalen = len; pts *= 90000; now_pts[0] = 0x21 | (((unsigned long)pts >> 29) & 0x0e); now_pts[1] = ((unsigned long)pts >> 22) & 0xff; now_pts[2] = 0x01 | (((unsigned long)pts >> 14) & 0xfe); now_pts[3] = ((unsigned long)pts >> 7) & 0xff; now_pts[4] = 0x01 | (((unsigned long)pts << 1) & 0xfe); pts_len = memcmp(last_pts, now_pts, sizeof(now_pts)) ? sizeof(now_pts) : 0; memcpy(last_pts, now_pts, sizeof(now_pts)); datalen += 3; /* Version, PTS_flags, pts_len */ datalen += pts_len; datalen += 1; /* AID */ pad_len = 2048 - (p - buffer) - 4 /* MPEG ID */ - 2 /* payload len */ - datalen; /* XXX - Go figure what should go here! In any case the packet has to be completely filled. If I can fill it with padding (0x000001be) latter I'll do that. But if there is only room for 6 bytes then I can not write a padding packet. So I add some padding in the PTS field. This looks like a dirty kludge. Oh well... */ if (pad_len < 0) { /* Packet is too big. Let's try omitting the PTS field */ datalen -= pts_len; pts_len = 0; pad_len = 0; } else if (pad_len > 6) pad_len = 0; datalen += pad_len; *p++ = 0; /* 0x0e */ *p++ = 0; *p++ = 1; *p++ = 0xbd; *p++ = (datalen >> 8) & 0xff; /* length of payload */ *p++ = datalen & 0xff; *p++ = 0x80; /* System-2 (.VOB) stream */ *p++ = pts_len ? 0x80 : 0x00; /* pts_flags */ *p++ = pts_len + pad_len; memcpy(p, now_pts, pts_len); p += pts_len; memset(p, 0, pad_len); p += pad_len; } *p++ = 0x20 | vob->aid; /* aid */ if (fwrite(buffer, p - buffer, 1, vob->fsub) != 1 || fwrite(packet, len, 1, vob->fsub) != 1) perror("ERROR: vobsub write failed"); else remain -= p - buffer + len; /* Padding */ if (remain >= 6) { p = buffer; *p++ = 0x00; *p++ = 0x00; *p++ = 0x01; *p++ = 0xbe; *p++ = (remain - 6) >> 8; *p++ = (remain - 6) & 0xff; /* for better compression, blank this */ memset(buffer + 6, 0, remain - (p - buffer)); if (fwrite(buffer, remain, 1, vob->fsub) != 1) perror("ERROR: vobsub padding write failed"); } else if (remain > 0) { /* I don't know what to output. But anyway the block needs to be 2KB big */ memset(buffer, 0, remain); if (fwrite(buffer, remain, 1, vob->fsub) != 1) perror("ERROR: vobsub blank padding write failed"); } else if (remain < 0) fprintf(stderr, "\nERROR: wrong thing happened...\n" " I wrote a %i data bytes spu packet and that's too long\n", len); } } #endif diff --git a/mplayer/vobsub.h b/mplayer/vobsub.h index 12dd466..0a32ae7 100644 --- a/mplayer/vobsub.h +++ b/mplayer/vobsub.h @@ -1,59 +1,59 @@ /* * This file is part of MPlayer. * * MPlayer is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MPLAYER_VOBSUB_H #define MPLAYER_VOBSUB_H #ifdef __cplusplus extern "C" { #endif extern int vobsub_id; // R: moved from mpcommon.h -void *vobsub_open(const char *subname, const char *const ifo, const int force, void** spu); +void *vobsub_open(const char *subname, const char *const ifo, const int force, unsigned int y_threshold, void** spu); void vobsub_reset(void *vob); int vobsub_parse_ifo(void* self, const char *const name, unsigned int *palette, unsigned int *width, unsigned int *height, int force, int sid, char *langid); int vobsub_get_packet(void *vobhandle, float pts,void** data, int* timestamp); int vobsub_get_next_packet(void *vobhandle, void** data, int* timestamp); void vobsub_close(void *self); unsigned int vobsub_get_indexes_count(void * /* vobhandle */); char *vobsub_get_id(void * /* vobhandle */, unsigned int /* index */); /// Get vobsub id by its index in the valid streams. int vobsub_get_id_by_index(void *vobhandle, unsigned int index); /// Get index in the valid streams by vobsub id. int vobsub_get_index_by_id(void *vobhandle, int id); /// Convert palette value in idx file to yuv. unsigned int vobsub_palette_to_yuv(unsigned int pal); /// Convert rgb value to yuv. unsigned int vobsub_rgb_to_yuv(unsigned int rgb); #if 0 // R: no output needed void *vobsub_out_open(const char *basename, const unsigned int *palette, unsigned int orig_width, unsigned int orig_height, const char *id, unsigned int index); void vobsub_out_output(void *me, const unsigned char *packet, int len, double pts); void vobsub_out_close(void *me); #endif int vobsub_set_from_lang(void *vobhandle, char const *lang); // R: changed lang from unsigned char* void vobsub_seek(void * vobhandle, float pts); #ifdef __cplusplus } #endif #endif /* MPLAYER_VOBSUB_H */ diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index ef905c2..82dfa81 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,300 +1,307 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010-2015 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; + int y_threshold = 0; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). + add_option("y-threshold", y_threshold, "Y (luminance) threshold below which colors treated as black (Default: 0)"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); + // Set Y threshold from command-line arg only if given + if (y_threshold) { + cout << "Using Y palette threshold: " << y_threshold << "\n"; + } + // Open the sub/idx subtitles spu_t spu; - vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); + vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, y_threshold, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(width == 0 or height == 0) { cerr << "ERROR: Empty image " << sub_counter << ", width: " << width << ", height: " << height << ", size: " << image_size << "\n"; continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
ea026e46cbc4fb85c3834b5ee3eb735ce355e03c
src/vobsub2srt.c++ (main): Use `or` instead of `||`.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 40a8443..776a5d8 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,300 +1,300 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; - if(width == 0 || height == 0) { + if(width == 0 or height == 0) { cerr << "ERROR: Empty image " << sub_counter << ", width: " << width << ", height: " << height << ", size: " << image_size << "\n"; continue; } if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
028f7428846e15d4d2a49adc59c9c0740e6b2b12
Check for images with a zero height or width.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 2fa88df..40a8443 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,295 +1,300 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; + if(width == 0 || height == 0) { + cerr << "ERROR: Empty image " << sub_counter << ", width: " << width << ", height: " << height << ", size: " << image_size << "\n"; + continue; + } + if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
b722a034dd6deb1581294d906adde8c564c0bf1b
Fix: subtitle numbers must start from 1
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index b74b548..2fa88df 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,295 +1,295 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; - fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), + fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i+1, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
7293ac228e6916b0a841889a3509c1ba862a83b4
Use 4 digits for image file names, as some movies have over 10000 subs.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index d85c1dd..b74b548 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,295 +1,295 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; - snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); + snprintf(buf, sizeof(buf), "%s-%04u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } else { size_t size = strlen(text); while (size > 0 and isspace(text[--size])) { text[size] = '\0'; } } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
3a59dc278abc2c1e6efd842d567fbe063a9be4ba
remove trailing space/newlines from text
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 86eb7b2..d85c1dd 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,289 +1,295 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; // using raw memory is evil but that's the way Tesseract works // If we switch to C++11 we can use unique_ptr. text = new char[sizeof(errormsg)]; memcpy(text, errormsg, sizeof(errormsg)); } + else { + size_t size = strlen(text); + while (size > 0 and isspace(text[--size])) { + text[size] = '\0'; + } + } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
8af7471e73624ad1e148ece6e9e8bfe9ed5c6a76
cmd_options: Fix #36 short option handling.
diff --git a/src/cmd_options.c++ b/src/cmd_options.c++ index acadaa5..3090ad6 100644 --- a/src/cmd_options.c++ +++ b/src/cmd_options.c++ @@ -1,196 +1,196 @@ /* * This file is part of vobsub2srt * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmd_options.h++" #include <iostream> #include <cstring> #include <cstdlib> #include <vector> #include <string> using namespace std; namespace { struct option { enum arg_type { Bool, String, Int } type; union { bool *flag; std::string *str; int *i; } ref; char const *name; char const *description; char short_name; template<typename T> option(char const *name, arg_type type, T &r, char const *description, char short_name) : type(type), name(name), description(description), short_name(short_name) { switch(type) { case Bool: ref.flag = reinterpret_cast<bool*>(&r); break; case String: ref.str = reinterpret_cast<std::string*>(&r); break; case Int: ref.i = reinterpret_cast<int*>(&r); break; } } }; struct unnamed { std::string *str; char const *name; char const *description; unnamed(std::string &s, char const *name, char const *description) : str(&s), name(name), description(description) { } }; } struct cmd_options::impl { std::vector<option> options; std::vector<unnamed> unnamed_args; }; cmd_options::cmd_options(bool handle_help) : exit(false), handle_help(handle_help), pimpl(new impl) { pimpl->options.reserve(10); // reserve a default amount of options here to save some reallocations } cmd_options::~cmd_options() { delete pimpl; } cmd_options &cmd_options::add_option(char const *name, bool &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Bool, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, std::string &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::String, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, int &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Int, val, description, short_name)); return *this; } cmd_options &cmd_options::add_unnamed(std::string &val, char const *help_name, char const *description) { pimpl->unnamed_args.push_back(unnamed(val, help_name, description)); return *this; } bool cmd_options::parse_cmd(int argc, char **argv) const { size_t current_unnamed = 0; bool parse_options = true; // set to false after -- for(int i = 1; i < argc; ++i) { if(parse_options and argv[i][0] == '-') { unsigned offset = 1; if(argv[i][1] == '-') { if(argv[i][2] == '\0') { // "--" stops option parsing and handles only unnamed args (to allow e.g. files starting with -) parse_options = false; } offset = 2; } if(handle_help and (strcmp(argv[i]+offset, "help") == 0 or strcmp(argv[i]+offset, "h") == 0)) { help(argv[0]); continue; } bool known_option = false; for(std::vector<option>::const_iterator j = pimpl->options.begin(); j != pimpl->options.end(); ++j) { if(strcmp(argv[i]+offset, j->name) == 0 or - (j->short_name != '\0' and argv[i][offset+1] == j->short_name and argv[i][offset+1] == '\0')) { + (j->short_name != '\0' and offset == 1 and argv[i][1] == j->short_name and argv[i][2] == '\0')) { known_option = true; if(j->type == option::Bool) { *j->ref.flag = true; break; } if(i+1 >= argc or argv[i+1][0] == '-') { // Check if next argv is an option or argument cerr << "option " << argv[i] << " is missing an argument\n"; exit = true; return false; } ++i; if(j->type == option::String) { *j->ref.str = argv[i]; } else if(j->type == option::Int) { char *endptr; *j->ref.i = strtol(argv[i], &endptr, 10); if(*endptr != '\0') { cerr << "option " << argv[i] << " expects a number as argument but got '" << argv[i] << "'\n"; exit = true; return false; } } break; } } if(not known_option) { cerr << "ERROR: unknown option '" << argv[i] << "'\n"; help(argv[0]); } } else if(pimpl->unnamed_args.size() > current_unnamed) { *pimpl->unnamed_args[current_unnamed].str = argv[i]; ++current_unnamed; } else { help(argv[0]); } } return not exit; } void cmd_options::help(char const *progname) const { cerr << "usage: " << progname; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << " --" << i->name; } if(handle_help) { cerr << " --help"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { cerr << " <" << i->name << '>'; } cerr << "\n\n"; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << "\t--" << i->name; if(i->type != option::Bool) { cerr << " <arg>"; } if(i->short_name != '\0') { cerr << " (or -" << i->short_name << ')'; } cerr << "\t... " << i->description << '\n'; } if(handle_help) { cerr << "\t--help (or -h)\t... show help information\n"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { cerr << "\t<" << i->name << ">\t... " << i->description << '\n'; } exit = true; }
ruediger/VobSub2SRT
b70b6f584e8151f70f9d90df054af0911ea7475e
Write error message to SRT in case of OCR failure.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 1a1d54e..86eb7b2 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,285 +1,289 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; - continue; + char const errormsg[] = "VobSub2SRT ERROR: OCR failure!"; + // using raw memory is evil but that's the way Tesseract works + // If we switch to C++11 we can use unique_ptr. + text = new char[sizeof(errormsg)]; + memcpy(text, errormsg, sizeof(errormsg)); } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); delete[]conv_subs[i].text; conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
fbaa4ee4cbf3e831a3d647d8aa687939bc887f32
Report error for unknown options.
diff --git a/src/cmd_options.c++ b/src/cmd_options.c++ index 70b2c86..acadaa5 100644 --- a/src/cmd_options.c++ +++ b/src/cmd_options.c++ @@ -1,190 +1,196 @@ /* * This file is part of vobsub2srt * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmd_options.h++" #include <iostream> #include <cstring> #include <cstdlib> #include <vector> #include <string> using namespace std; namespace { struct option { enum arg_type { Bool, String, Int } type; union { bool *flag; std::string *str; int *i; } ref; char const *name; char const *description; char short_name; template<typename T> option(char const *name, arg_type type, T &r, char const *description, char short_name) : type(type), name(name), description(description), short_name(short_name) { switch(type) { case Bool: ref.flag = reinterpret_cast<bool*>(&r); break; case String: ref.str = reinterpret_cast<std::string*>(&r); break; case Int: ref.i = reinterpret_cast<int*>(&r); break; } } }; struct unnamed { std::string *str; char const *name; char const *description; unnamed(std::string &s, char const *name, char const *description) : str(&s), name(name), description(description) { } }; } struct cmd_options::impl { std::vector<option> options; std::vector<unnamed> unnamed_args; }; cmd_options::cmd_options(bool handle_help) : exit(false), handle_help(handle_help), pimpl(new impl) { pimpl->options.reserve(10); // reserve a default amount of options here to save some reallocations } cmd_options::~cmd_options() { delete pimpl; } cmd_options &cmd_options::add_option(char const *name, bool &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Bool, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, std::string &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::String, val, description, short_name)); return *this; } cmd_options &cmd_options::add_option(char const *name, int &val, char const *description, char short_name) { pimpl->options.push_back(option(name, option::Int, val, description, short_name)); return *this; } cmd_options &cmd_options::add_unnamed(std::string &val, char const *help_name, char const *description) { pimpl->unnamed_args.push_back(unnamed(val, help_name, description)); return *this; } bool cmd_options::parse_cmd(int argc, char **argv) const { size_t current_unnamed = 0; bool parse_options = true; // set to false after -- for(int i = 1; i < argc; ++i) { if(parse_options and argv[i][0] == '-') { unsigned offset = 1; if(argv[i][1] == '-') { if(argv[i][2] == '\0') { // "--" stops option parsing and handles only unnamed args (to allow e.g. files starting with -) parse_options = false; } offset = 2; } if(handle_help and (strcmp(argv[i]+offset, "help") == 0 or strcmp(argv[i]+offset, "h") == 0)) { help(argv[0]); continue; } + bool known_option = false; for(std::vector<option>::const_iterator j = pimpl->options.begin(); j != pimpl->options.end(); ++j) { if(strcmp(argv[i]+offset, j->name) == 0 or (j->short_name != '\0' and argv[i][offset+1] == j->short_name and argv[i][offset+1] == '\0')) { + known_option = true; if(j->type == option::Bool) { *j->ref.flag = true; break; } if(i+1 >= argc or argv[i+1][0] == '-') { // Check if next argv is an option or argument cerr << "option " << argv[i] << " is missing an argument\n"; exit = true; return false; } ++i; if(j->type == option::String) { *j->ref.str = argv[i]; } else if(j->type == option::Int) { char *endptr; *j->ref.i = strtol(argv[i], &endptr, 10); if(*endptr != '\0') { cerr << "option " << argv[i] << " expects a number as argument but got '" << argv[i] << "'\n"; exit = true; return false; } } break; } } + if(not known_option) { + cerr << "ERROR: unknown option '" << argv[i] << "'\n"; + help(argv[0]); + } } else if(pimpl->unnamed_args.size() > current_unnamed) { *pimpl->unnamed_args[current_unnamed].str = argv[i]; ++current_unnamed; } else { help(argv[0]); } } return not exit; } void cmd_options::help(char const *progname) const { cerr << "usage: " << progname; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << " --" << i->name; } if(handle_help) { cerr << " --help"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { cerr << " <" << i->name << '>'; } cerr << "\n\n"; for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { cerr << "\t--" << i->name; if(i->type != option::Bool) { cerr << " <arg>"; } if(i->short_name != '\0') { cerr << " (or -" << i->short_name << ')'; } cerr << "\t... " << i->description << '\n'; } if(handle_help) { cerr << "\t--help (or -h)\t... show help information\n"; } for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { cerr << "\t<" << i->name << ">\t... " << i->description << '\n'; } exit = true; }
ruediger/VobSub2SRT
de90184a05a5a5bbb4891b5326620b7495659e4c
Fix double-free issue.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 7bae69a..1a1d54e 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,284 +1,285 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases struct sub_text_t { sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) : start_pts(start_pts), end_pts(end_pts), text(text) { } - ~sub_text_t() - { delete[]text; } unsigned start_pts, end_pts; char const *text; }; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; vector<sub_text_t> conv_subs; conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed for(unsigned i = 0; i < conv_subs.size(); ++i) { if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) conv_subs[i].end_pts = conv_subs[i+1].start_pts; fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); + + delete[]conv_subs[i].text; + conv_subs[i].text = 0x0; } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
848f6a016104b23eeb83879241924bd791f89478
Cleanup previous patch and other minor changes.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 24235dc..7bae69a 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,281 +1,284 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; // helper struct for caching and fixing end_pts in some cases -typedef struct { +struct sub_text_t { + sub_text_t(unsigned start_pts, unsigned end_pts, char const *text) + : start_pts(start_pts), end_pts(end_pts), text(text) + { } + ~sub_text_t() + { delete[]text; } unsigned start_pts, end_pts; - char *text; -} sub_text_t; + char const *text; +}; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * - * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. + * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). + * srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; - sub_text_t sub_text; - std::vector<sub_text_t> conv_subs; + vector<sub_text_t> conv_subs; + conv_subs.reserve(200); // TODO better estimate while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { - cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" + cerr << sub_counter << ": time stamp from .idx (" << timestamp + << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } - sub_text.start_pts = start_pts; - sub_text.end_pts = end_pts; - sub_text.text = text; - conv_subs.push_back(sub_text); + conv_subs.push_back(sub_text_t(start_pts, end_pts, text)); ++sub_counter; } } // write the file, fixing end_pts when needed - for (unsigned i = 0; i < conv_subs.size(); i++) - { - if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) - conv_subs[i].end_pts = conv_subs[i+1].start_pts; + for(unsigned i = 0; i < conv_subs.size(); ++i) { + if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) + conv_subs[i].end_pts = conv_subs[i+1].start_pts; - fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); - delete[]conv_subs[i].text; + fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), + pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
5b2ccabc55f1037e325f7889f02fecdae3ab8702
Fix for #29: output subtitled with overlapping errors
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 17b721c..24235dc 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,260 +1,281 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> +#include <vector> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; +// helper struct for caching and fixing end_pts in some cases +typedef struct { + unsigned start_pts, end_pts; + char *text; +} sub_text_t; + /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); for(unsigned i = 0; i < image_size; i += stride) { fwrite(image + i, 1, width, pgm); } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; + sub_text_t sub_text; + std::vector<sub_text_t> conv_subs; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } - fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); - delete[]text; + sub_text.start_pts = start_pts; + sub_text.end_pts = end_pts; + sub_text.text = text; + conv_subs.push_back(sub_text); ++sub_counter; } } + // write the file, fixing end_pts when needed + for (unsigned i = 0; i < conv_subs.size(); i++) + { + if(conv_subs[i].end_pts == UINT_MAX && i+1 < conv_subs.size()) + conv_subs[i].end_pts = conv_subs[i+1].start_pts; + + fprintf(srtout, "%u\n%s --> %s\n%s\n\n", i, pts2srt(conv_subs[i].start_pts).c_str(), pts2srt(conv_subs[i].end_pts).c_str(), conv_subs[i].text); + delete[]conv_subs[i].text; + } + #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
1c782e5344bfa201e5073b07ba7f0ebec1312d82
Handle stride when dumping images. Fix #18 and #30.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index bbeead9..17b721c 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,258 +1,260 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, - unsigned char const *image, size_t image_size) { + unsigned stride, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); - fwrite(image, 1, image_size, pgm); + for(unsigned i = 0; i < image_size; i += stride) { + fwrite(image + i, 1, width, pgm); + } fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { char const *const id = vobsub_get_id(vob, i); cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language if(not lang.empty() and index >= 0) { cerr << "Setting both lang and index not supported.\n"; return 1; } // default english char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else { if(index >= 0) { if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { cerr << "Index argument out of range: " << index << " (" << vobsub_get_indexes_count(vob) << ")\n"; return 1; } vobsub_id = index; } if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { - dump_pgm(subname, sub_counter, width, height, image, image_size); + dump_pgm(subname, sub_counter, width, height, stride, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
0122ce7efc3e9dc1e519e39c766bc72158f8f49f
Handle NULL id's for --langlist.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index d8510de..7457b1e 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,238 +1,239 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); fwrite(image, 1, image_size, pgm); fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { - cout << i << ": " << vobsub_get_id(vob, i) << '\n'; + char const *const id = vobsub_get_id(vob, i); + cout << i << ": " << (id ? id : "(no id)") << '\n'; } return 0; } // Handle stream Ids and language char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); // default english if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
7a6613928a6898881d48de27a52416a171386182
Add --index flag.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index d8510de..748aec8 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,238 +1,257 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); fwrite(image, 1, image_size, pgm); fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; + int index = -1; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). + add_option("index", index, "subtitle index", 'i'). add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { cout << i << ": " << vobsub_get_id(vob, i) << '\n'; } return 0; } // Handle stream Ids and language - char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); // default english + if(not lang.empty() and index >= 0) { + cerr << "Setting both lang and index not supported.\n"; + return 1; + } + + // default english + char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } - else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream - char const *const lang1 = vobsub_get_id(vob, vobsub_id); - if(lang1 and tess_lang_user.empty()) { - char const *const lang3 = iso639_1_to_639_3(lang1); - if(lang3) { - tess_lang = lang3; + else { + if(index >= 0) { + if(static_cast<unsigned>(index) >= vobsub_get_indexes_count(vob)) { + cerr << "Index argument out of range: " << index << " (" + << vobsub_get_indexes_count(vob) << ")\n"; + return 1; + } + vobsub_id = index; + } + + if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream + char const *const lang1 = vobsub_get_id(vob, vobsub_id); + if(lang1 and tess_lang_user.empty()) { + char const *const lang3 = iso639_1_to_639_3(lang1); + if(lang3) { + tess_lang = lang3; + } } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
751a3682d85f666d690fa17c220047adbff6ec27
packaging/gentoo: Updated ebuild script.
diff --git a/packaging/vobsub2srt-9999.ebuild b/packaging/vobsub2srt-9999.ebuild index 53826dd..c6cfb30 100644 --- a/packaging/vobsub2srt-9999.ebuild +++ b/packaging/vobsub2srt-9999.ebuild @@ -1,33 +1,25 @@ # -*- mode:sh; -*- -# Copyright 1999-2012 Gentoo Foundation + +# See https://github.com/ruediger/VobSub2SRT/issues/13 + +# Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 -# $Header: /media-video/vobsub2srt/ChangeLog,v 0.1 2012/01/06 19:15:04 thawn Exp $ EAPI="4" EGIT_REPO_URI="git://github.com/ruediger/VobSub2SRT.git" -inherit git-2 +inherit cmake-utils git-2 IUSE="" DESCRIPTION="Converts image subtitles created by VobSub (.sub/.idx) to .srt textual subtitles using tesseract OCR engine" HOMEPAGE="https://github.com/ruediger/VobSub2SRT" LICENSE="GPL-3" SLOT="0" KEYWORDS="~amd64 ~x86" RDEPEND=">=app-text/tesseract-2.04-r1 >=virtual/ffmpeg-0.6.90" DEPEND="${RDEPEND}" -src_configure() { - econf -} -src_compile() { - emake || die -} - -src_install() { - emake DESTDIR="${D}" install || die -}
ruediger/VobSub2SRT
d4831b6307267f2c045fc304ecbd21929f7d2639
manpage: Example for chinese.
diff --git a/doc/vobsub2srt.1 b/doc/vobsub2srt.1 index c49d402..fba9668 100644 --- a/doc/vobsub2srt.1 +++ b/doc/vobsub2srt.1 @@ -1,45 +1,49 @@ .TH vobsub2srt 1 "27 September 2010" .SH NAME vobsub2srt \- converts vobsub (.idx/.sub) into .srt subtitles .SH SYNOPSIS \fBvobsub2srt\fR [\fIOPTION\fR] \fIFILENAME\fR .SH DESCRIPTION .PP vobsub2srt converts subtitles in vobsub (.idx/.sub) format into the .srt format. VobSub subtitles contain images and srt is a text format. OCR is used to extract the text from the subtitles. vobsub2srt uses tesseract for OCR and is based on code from the MPlayer project. .SH OPTIONS .TP \fIFILENAME\fR File name of the subtitles \fBWITHOUT\fR the .idx or .sub extension. The .srt subtitles are written to a file called \fIFILENAME\fR.srt. .TP \fB\-\-dump\-images\fR Dump the subtitles as images (format \fIFILENAME\fR-\fINUMBER\fR.pgm in PGM format). .TP \fB\-\-verbose\fR Print more information about the file (e.g. subtitle languages) .TP \fB\-\-lang\fR \fIlanguage\fR Select the language of the subtitle (two letter ISO 639-1 code e.g. en for English or de for German). Use \fI--verbose\fR to see the languages in the subtitle file. .TP \fB\-\-langlist\fR List languages and exit. .TP \fB\-\-ifo\fR \fIifo-file\fR To use a specific IFO file. Default: \fIFILENAME\fR.IFO is tried. IFO file is optional! .TP \fB\-\-tesseract-lang\fR \fIlanguage\fR -Set the language to be used by tesseract. This is auto detected and normally does not has to be changed. If however you need special language settings (e.g., deu-frak) use this option. +Set the language to be used by tesseract. This is auto detected and normally does not has to be changed. If however you need special language settings (e.g., deu-frak, chi_sim, chi_tra) use this option. .TP \fB\-\-tesseract-data\fR \fIpath\fR Set path to tesseract-data. .TP \fB\-\-blacklist\fR \fIblacklist\fR Blacklist characters for OCR (e.g. |\\/`_~<>) .SH EXAMPLES .nf $ \fBvobsub2srt \-\-lang en foobar\fR .fi Converts the English language subtitles from the VobSub files \fIfoobar.idx\fR/\fIfoobar.sub\fR to srt subtitles in \fIfoobar.srt\fR. +.nf + $ \fBvobsub2srt \-\-lang zh \-\-tesseract-lang chi_sim foobar\fR +.fi +Converts the chinese language subtitles using simplified chinese (chi_sim) characters. .SH HOMEPAGE For more information see \fIhttp://github.com/ruediger/VobSub2SRT\fR .SH AUTHOR R\[:u]diger Sonderfeld <\fIruediger -AT- c-plusplus -DOT- de\fR>
ruediger/VobSub2SRT
8d34a407b326c82a2a79f81d4e7ed9929920d1ef
Add --tesseract-lang option.
diff --git a/doc/completion.sh b/doc/completion.sh index f52b17a..dbccb9f 100755 --- a/doc/completion.sh +++ b/doc/completion.sh @@ -1,57 +1,57 @@ #!/bin/bash # -*- mode:sh; coding:utf-8; -*- # # Bash completions for vobsub2srt(1). # # Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # have vobsub2srt && _vobsub2srt() { local cmd cur prev tmp arg cmd=${COMP_WORDS[0]} _get_comp_words_by_ref cur prev case $prev in --ifo) _filedir '(ifo|IFO)' return 0 ;; --lang|-l) _get_first_arg tmp=$( "$cmd" --langlist -- "$arg" 2>/dev/null | sed -E -e '/Languages:/d; s/^[[:digit:]]+: //;' ) COMPREPLY=( $( compgen -W "$tmp" -- "$cur" ) ) return 0 ;; --tesseract-data) _filedir -d return 0 ;; esac case $cur in -*) - COMPREPLY=( $( compgen -W '--dump-images --verbose --ifo --lang --langlist --tesseract-data --blacklist' -- "$cur" ) ) + COMPREPLY=( $( compgen -W '--dump-images --verbose --ifo --lang --langlist --tesseract-lang --tesseract-data --blacklist' -- "$cur" ) ) ;; *) _filedir '(idx|IDX|sub|SUB)' COMPREPLY=$( echo "$COMPREPLY" | sed -E -e 's/.(idx|IDX|sub|SUB)$//' ) # remove suffix ;; esac return 0 } && complete -F _vobsub2srt vobsub2srt diff --git a/doc/vobsub2srt.1 b/doc/vobsub2srt.1 index 2b62b89..c49d402 100644 --- a/doc/vobsub2srt.1 +++ b/doc/vobsub2srt.1 @@ -1,42 +1,45 @@ .TH vobsub2srt 1 "27 September 2010" .SH NAME vobsub2srt \- converts vobsub (.idx/.sub) into .srt subtitles .SH SYNOPSIS \fBvobsub2srt\fR [\fIOPTION\fR] \fIFILENAME\fR .SH DESCRIPTION .PP vobsub2srt converts subtitles in vobsub (.idx/.sub) format into the .srt format. VobSub subtitles contain images and srt is a text format. OCR is used to extract the text from the subtitles. vobsub2srt uses tesseract for OCR and is based on code from the MPlayer project. .SH OPTIONS .TP \fIFILENAME\fR File name of the subtitles \fBWITHOUT\fR the .idx or .sub extension. The .srt subtitles are written to a file called \fIFILENAME\fR.srt. .TP \fB\-\-dump\-images\fR Dump the subtitles as images (format \fIFILENAME\fR-\fINUMBER\fR.pgm in PGM format). .TP \fB\-\-verbose\fR Print more information about the file (e.g. subtitle languages) .TP \fB\-\-lang\fR \fIlanguage\fR Select the language of the subtitle (two letter ISO 639-1 code e.g. en for English or de for German). Use \fI--verbose\fR to see the languages in the subtitle file. .TP \fB\-\-langlist\fR List languages and exit. .TP \fB\-\-ifo\fR \fIifo-file\fR To use a specific IFO file. Default: \fIFILENAME\fR.IFO is tried. IFO file is optional! .TP +\fB\-\-tesseract-lang\fR \fIlanguage\fR +Set the language to be used by tesseract. This is auto detected and normally does not has to be changed. If however you need special language settings (e.g., deu-frak) use this option. +.TP \fB\-\-tesseract-data\fR \fIpath\fR Set path to tesseract-data. .TP \fB\-\-blacklist\fR \fIblacklist\fR Blacklist characters for OCR (e.g. |\\/`_~<>) .SH EXAMPLES .nf $ \fBvobsub2srt \-\-lang en foobar\fR .fi Converts the English language subtitles from the VobSub files \fIfoobar.idx\fR/\fIfoobar.sub\fR to srt subtitles in \fIfoobar.srt\fR. .SH HOMEPAGE For more information see \fIhttp://github.com/ruediger/VobSub2SRT\fR .SH AUTHOR R\[:u]diger Sonderfeld <\fIruediger -AT- c-plusplus -DOT- de\fR> diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 14dd080..d8510de 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,236 +1,238 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); fwrite(image, 1, image_size, pgm); fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; + std::string tess_lang_user; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). + add_option("tesseract-lang", tess_lang_user, "set tesseract language (Default: auto detect)"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { cout << i << ": " << vobsub_get_id(vob, i) << '\n'; } return 0; } // Handle stream Ids and language - char const *tess_lang = "eng"; // default english + char const *tess_lang = tess_lang_user.empty() ? "eng" : tess_lang_user.c_str(); // default english if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } - else { + else if(tess_lang_user.empty()) { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); - if(lang1) { + if(lang1 and tess_lang_user.empty()) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { cerr << "Failed to initialize tesseract (OCR).\n"; return 1; } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
fe6c255cdf4024cb87df5b4cfd9ef1b6e7f1a457
Fix #24: Wrong manpage install path.
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 7ad44da..24b7190 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -1,30 +1,30 @@ find_program(GZIP gzip HINTS /bin /usr/bin /usr/local/bin) if(GZIP-NOTFOUND) message(WARNING "Gzip not found! Uncompressed manpage installed") add_custom_target(documentation ALL DEPENDS vobsub2srt.1) - install(FILES vobsub2srt.1 DESTINATION INSTALL_MAN_DIR) + install(FILES vobsub2srt.1 DESTINATION ${INSTALL_MAN_DIR}) else() add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz COMMAND ${GZIP} -9 -c vobsub2srt.1 > ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz MAIN_DEPENDENCY vobsub2srt.1 WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") add_custom_target(documentation ALL DEPENDS ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz) - install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION INSTALL_MAN_DIR) + install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION ${INSTALL_MAN_DIR}) endif() option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of $BASH_COMPLETION_DIR if available.") if(BASH_COMPLETION_PATH) message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) endif()
ruediger/VobSub2SRT
d7af9b863e5ac0002815aa912fbc04a1949b1577
Fedora RPM spec file
diff --git a/packaging/vobsub2srt.spec b/packaging/vobsub2srt.spec new file mode 100644 index 0000000..bc5177e --- /dev/null +++ b/packaging/vobsub2srt.spec @@ -0,0 +1,53 @@ +%global commit 1746781ee4a98d92d70ba7198246c58285296437 +%global shortcommit %(c=%{commit}; echo ${c:0:7}) +%global commitdate 20130216 +%global gittag %{commitdate}git%{shortcommit} + +Name: vobsub2srt +Version: 1.0 +Release: 1%{?dist}.%{gittag} +Summary: VobSub2SRT .sub/.idx to .srt subtitle converter + +Group: Applications/Multimedia +License: GPLv3+ +URL: https://github.com/ruediger/VobSub2SRT +Source0: https://github.com/ruediger/VobSub2SRT/archive/%{commit}/%{name}-%{version}-%{shortcommit}.tar.gz + +BuildRequires: cmake +BuildRequires: tesseract-devel +BuildRequires: libtiff-devel + +%description +VobSub2SRT is a simple command line program to convert .idx / .sub subtitles +into .srt text subtitles by using OCR. It is based on code from the MPlayer +project. + +%prep +%setup -qn VobSub2SRT-%{commit} + +%build +mkdir -p %{_target_platform} +pushd %{_target_platform} +%{cmake} \ + -D INSTALL_DOC_DIR=%{_docdir}/%{name}-%{version} \ + .. +popd + +make %{?_smp_mflags} -C %{_target_platform} + +%install +make install DESTDIR=%{buildroot} -C %{_target_platform} +mv %{buildroot}/%{_docdir}/%{name}/copyright . +mv %{buildroot}/%{_docdir}/%{name}/README . + + +%files +%doc README copyright +%{_mandir}/man1/vobsub2srt.1.gz +%{_bindir}/vobsub2srt + + +%changelog +* Sat Feb 16 2013 Vinzenz Feenstra <[email protected]> - 1.0-1.20130216git1746781 +- Initial package + diff --git a/packaging/vobsub2srt.spec.rst b/packaging/vobsub2srt.spec.rst new file mode 100644 index 0000000..f87c262 --- /dev/null +++ b/packaging/vobsub2srt.spec.rst @@ -0,0 +1,6 @@ + pushd ~/rpmbuild/SOURCE + wget https://github.com/ruediger/VobSub2SRT/archive/1746781ee4a98d92d70ba7198246c58285296437/vobsub2srt-0.1-1746781.tar.gz + popd + rpmbuild -ba vobsub2srt.spec + yum install -y `find ~/rpmbuild/RPMS -name vobsub2srt-0.1.*` +
ruediger/VobSub2SRT
1add08890434510868d618200420aa38e3fed4d4
build: Add support for INSTALL_DOC_DIR and other common path flags.
diff --git a/CMakeLists.txt b/CMakeLists.txt index 0e43709..d1954cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,146 +1,150 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) message(WARNING "Building a statically linked version of VobSub2SRT is NOT recommended. You might run into library dependency issues. Please check the README!") set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) -set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) -install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) -install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) +set(INSTALL_DATA_DIR_BASE "${CMAKE_INSTALL_PREFIX}/share" CACHE STRING "Custom data installation directory without suffixes") +set(INSTALL_DOC_DIR_BASE "${INSTALL_DATA_DIR_BASE}/doc" CACHE STRING "Custom doc installation directory without suffixes") +set(INSTALL_DOC_DIR "${INSTALL_DOC_DIR_BASE}/${CMAKE_PROJECT_NAME}" CACHE STRING "Custom doc installation directory") +set(INSTALL_MAN_DIR "${INSTALL_DATA_DIR_BASE}/man/man1" CACHE STRING "Custom manpage installation directory without suffixes") + +install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_DOC_DIR}) +install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_DOC_DIR} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra -Wno-long-long") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif() diff --git a/CMakeModules/cmake_uninstall.cmake.in b/CMakeModules/cmake_uninstall.cmake.in index ecfa84a..563c97a 100644 --- a/CMakeModules/cmake_uninstall.cmake.in +++ b/CMakeModules/cmake_uninstall.cmake.in @@ -1,41 +1,41 @@ if (NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") message(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") cmake_policy(SET CMP0007 OLD) # ignore empty list elements file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) string(REGEX REPLACE "\n" ";" files "${files}") list(REVERSE files) foreach (file ${files}) message(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") if (EXISTS "$ENV{DESTDIR}${file}") execute_process( COMMAND @CMAKE_COMMAND@ -E remove "$ENV{DESTDIR}${file}" OUTPUT_VARIABLE rm_out RESULT_VARIABLE rm_retval ) if(NOT ${rm_retval} EQUAL 0) message(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") endif (NOT ${rm_retval} EQUAL 0) else (EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") endif (EXISTS "$ENV{DESTDIR}${file}") endforeach(file) -set(INSTALL_SHARE_DOC @INSTALL_SHARE_DOC@) -if(INSTALL_SHARE_DOC) # prevent empty variable! - message(STATUS "Uninstalling \"$ENV{DESTDIR}${INSTALL_SHARE_DOC}\"") +set(INSTALL_DOC_DIR @INSTALL_DOC_DIR@) +if(INSTALL_DOC_DIR) # prevent empty variable! + message(STATUS "Uninstalling \"$ENV{DESTDIR}${INSTALL_DOC_DIR}\"") # Call rmdir instead of cmake -E remove_directory to avoid removing non-empty # directories in case install_share_doc points to a common directory execute_process( - COMMAND rmdir -- "$ENV{DESTDIR}${INSTALL_SHARE_DOC}" + COMMAND rmdir -- "$ENV{DESTDIR}${INSTALL_DOC_DIR}" OUTPUT_VARIABLE rm_out RESULT_VARIABLE rm_retval ) if(NOT rm_retval EQUAL 0) - message(FATAL_ERROR "Removing directory $ENV{DESTDIR}${INSTALL_SHARE_DOC}") + message(FATAL_ERROR "Removing directory $ENV{DESTDIR}${INSTALL_DOC_DIR}") endif() else() message(WARNING "No share/doc path found!") endif() diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 7cec3f0..7ad44da 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -1,30 +1,30 @@ find_program(GZIP gzip HINTS /bin /usr/bin /usr/local/bin) if(GZIP-NOTFOUND) message(WARNING "Gzip not found! Uncompressed manpage installed") add_custom_target(documentation ALL DEPENDS vobsub2srt.1) - install(FILES vobsub2srt.1 DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) + install(FILES vobsub2srt.1 DESTINATION INSTALL_MAN_DIR) else() add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz COMMAND ${GZIP} -9 -c vobsub2srt.1 > ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz MAIN_DEPENDENCY vobsub2srt.1 WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") add_custom_target(documentation ALL DEPENDS ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz) - install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) + install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION INSTALL_MAN_DIR) endif() option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of $BASH_COMPLETION_DIR if available.") if(BASH_COMPLETION_PATH) message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) endif()
ruediger/VobSub2SRT
1746781ee4a98d92d70ba7198246c58285296437
Removed libavutil dependency.
diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a76983..0e43709 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,147 +1,146 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) message(WARNING "Building a statically linked version of VobSub2SRT is NOT recommended. You might run into library dependency issues. Please check the README!") set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra -Wno-long-long") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type -find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif() diff --git a/README.org b/README.org index fafabda..df64611 100644 --- a/README.org +++ b/README.org @@ -1,94 +1,94 @@ # -*- mode:org; mode:visual-line; coding:utf-8; -*- -VobSub2SRT is a simple command line program to convert =.idx= / =.sub= subtitles into =.srt= text subtitles by using OCR. It is based on code from the [[http://www.mplayerhq.hu][MPlayer project]] - a really really great movie player. [[http://code.google.com/p/tesseract-ocr/][Tesseract]] is used as OCR software. +VobSub2SRT is a simple command line program to convert =.idx= / =.sub= subtitles into =.srt= text subtitles by using OCR. It is based on code from the [[http://www.mplayerhq.hu][MPlayer project]] - a really really great movie player. Some minor parts are copied from [[http://ffmpeg.org/][ffmpeg/avutil]] headers. [[http://code.google.com/p/tesseract-ocr/][Tesseract]] is used as OCR software. vobsub2srt is released under the GPL3+ license. The MPlayer code included is GPL2+ licensed. The quality of the OCR depends on the text in the subtitles. Currently the code does not use any preprocessing. But I'm currently looking into adding filters and scaling options to improve the OCR. You can correct mistakes in the =.srt= files with a text editor or a special subtitle editor. * Building -You need tesseract and libavutil (part of the [[http://ffmpeg.org/][FFmpeg]] project). You also need cmake and a gcc to build it. With Ubuntu 12.10 you can install the dependencies with +You need tesseract. You also need cmake and a gcc to build it. With Ubuntu 12.10 you can install the dependencies with #+BEGIN_EXAMPLE - sudo apt-get install libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng build-essential cmake pkg-config + sudo apt-get install libtiff5-dev libtesseract-dev tesseract-ocr-eng build-essential cmake pkg-config #+END_EXAMPLE You should also install the tesseract data for the languages you want to use! Note that the support for tesseract 2 is deprecated and will be removed in the future! #+BEGIN_EXAMPLE ./configure make sudo make install #+END_EXAMPLE This should install the program vobsub2srt to =/usr/local/bin=. You can uninstall vobsub2srt with =sudo make uninstall=. If you want to install the bash completion script then set the =BASH_COMPLETION_PATH= parameter: #+BEGIN_EXAMPLE ./configure -DBASH_COMPLETION_PATH="$BASH_COMPLETION_DIR" #+END_EXAMPLE ** Static binary I recommend using the dynamic binary! However if you really need a static binary you can add the flag =-DBUILD_STATIC=ON= to the =./configure= call. But be aware that building static binaries can be quite troublesome. You need the static library files for tesseract, libtill, libavutils, and for their dependencies as well. On Ubuntu 12.04 the static libraries are only included in the dev packages! You probably also need the Gold linker. For Ubuntu 12.04 you need the following extra packages: #+BEGIN_EXAMPLE sudo apt-get install libleptonica-dev libpng12-dev libwebp-dev libgif-dev zlib1g-dev libjpeg-dev binutils-gold #+END_EXAMPLE If linking fails with undefined references then checking what other dependencies your version of leptonica has is a good starting point. You can do this by running =ldd /usr/lib/liblept.so= (or whatever the path to leptonica is on your system). Add those dependencies to =CMakeModules/FindTesseract.cmake=. ** Ubuntu PPA and .deb packages I have created a [[https://launchpad.net/~ruediger-c-plusplus/+archive/vobsub2srt][PPA (Personal Package Archive)]] to make installation on Ubuntu easy. Simply add the PPA to your apt-get sources and run an update and you can install the =vobsub2srt= package: #+BEGIN_EXAMPLE sudo add-apt-repository ppa:ruediger-c-plusplus/vobsub2srt sudo apt-get update sudo apt-get install vobsub2srt #+END_EXAMPLE *** .deb (Debian/Ubuntu) You can build a *.deb package (Debian/Ubuntu) with =make package=. The package is created in the =build= directory. You can also create a source package and upload it to your own PPA by using the =UploadPPA.cmake=. But this is only recommended for people experienced with cmake and creating Debian packages. ** Homebrew Vobsub2srt contains a formula for [[http://mxcl.github.com/homebrew/][Homebrew]] (a package manager for OS X). It can be installed by using the command =brew install https://github.com/ruediger/VobSub2SRT/raw/master/packaging/vobsub2srt.rb=. ** Gentoo ebuild An [[http://en.wikipedia.org/wiki/Ebuild][ebuild]] for Gentoo Linux is also available. You can make it available to emerge with the following steps #+BEGIN_EXAMPLE sudo mkdir -p /usr/local/portage/media/video/vobsub2srt/ wget https://github.com/ruediger/VobSub2SRT/raw/master/packaging/vobsub2srt-9999.ebuild sudo mv vobsub2srt-9999.ebuild /usr/local/portage/media/video/vobsub2srt/ cd /usr/local/portage/media/video/vobsub2srt/ sudo ebuild vobsub2srt-999.ebuild digest #+END_EXAMPLE You should be able to install vobsub2srt with =emerge vobsub2srt= now. If you want to use a newer version (3+) of tesseract you have to use layman. See [[https://github.com/ruediger/VobSub2SRT/issues/13][#13]] for details. ** Arch AUR There also exist a [[https://wiki.archlinux.org/index.php/PKGBUILD][PKGBUILD]] file for Arch Linux in AUR: [[https://aur.archlinux.org/packages.php?ID=50015]] * Usage vobsub2srt converts subtitles in VobSub (=.idx= / =.sub=) format into subtitles in =.srt= format. VobSub subtitles consist of two or three files called =Filename.idx=, =Filename.sub= and optional =Filename.ifo=. To convert subtitles simply call #+BEGIN_EXAMPLE vobsub2srt Filename #+END_EXAMPLE with =Filename= being the file name of the subtitle files *WITHOUT* the extension (=.idx= / =.sub=). vobsub2srt writes the subtitles to a file called =Filename.srt=. If a subtitle file contains more than one language you can use the =--lang= parameter to set the correct language (Use =--langlist= to find out about the languages in the file). If you want to dump the subtitles as images (e.g. to check for correct ocr) you can use the =--dump-images= flag. Use =--help= or read the manpage to get more information about the options of vobsub2srt. * Contributors Most code is from the MPlayer project. - Armin Häberling <[email protected]> wrote a patch to fix an issue with multiple instances of the same subtitle in result file (21af426) - James Harris <[email protected]> wrote the formula for Homebrew (54f311d6) - Leo Koppelkamm reported and fixed issue #5 and problems with long filenames (b903074c, 36ec8da, d3602d6) - Till Korten <[email protected]> wrote the ebuild script (#13) - Andreasf fixed missing libavutil include path (3a175eb, #15) * To Do - implement preprocessing (first step scaling. Code available in =spudec.c=) diff --git a/mplayer/CMakeLists.txt b/mplayer/CMakeLists.txt index b357c68..4f07674 100644 --- a/mplayer/CMakeLists.txt +++ b/mplayer/CMakeLists.txt @@ -1,17 +1,15 @@ add_definitions("-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE -D_REENTRANT") add_definitions("-Wundef -Wall -Wno-switch -Wno-parentheses -Wpointer-arith -Wredundant-decls -Wstrict-prototypes -Wmissing-prototypes -Wdisabled-optimization -Wno-pointer-sign -Wdeclaration-after-statement") -include_directories(${Libavutil_INCLUDE_DIRS}) - set(mplayer_sources mp_msg.c mp_msg.h spudec.c spudec.h unrar_exec.c unrar_exec.h vobsub.c vobsub.h ) add_library(mplayer STATIC ${mplayer_sources}) diff --git a/mplayer/spudec.c b/mplayer/spudec.c index 5b3f7eb..b3960cc 100644 --- a/mplayer/spudec.c +++ b/mplayer/spudec.c @@ -1,562 +1,563 @@ /* * Skeleton of function spudec_process_controll() is from xine sources. * Further works: * LGB,... (yeah, try to improve it and insert your name here! ;-) * * Kim Minh Kaplan * implement fragments reassembly, RLE decoding. * read brightness from the IFO. * * For information on SPU format see <URL:http://sam.zoy.org/doc/dvd/subtitles/> * and <URL:http://members.aol.com/mpucoder/DVD/spu.html> * * This file is part of MPlayer. * * MPlayer is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // #include "config.h" #include "mp_msg.h" #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> //#include "libvo/sub.h" // R: no OSD stuff needed //#include "libvo/video_out.h" // R: no OSD stuff needed int sub_pos = 100; // R: copied from libvo/sub.c #include "spudec.h" #include "vobsub.h" -#include <libavutil/avutil.h> // R: Use systems' avutil -//#include <libavutil/intreadwrite.h> // R: Use systems' avutil // #include "libswscale/swscale.h" // R: no swscalar gaussian aamode +#define FFMAX(a,b) ((a) > (b) ? (a) : (b)) +#define FFMIN(a,b) ((a) > (b) ? (b) : (a)) + /* Valid values for spu_aamode: 0: none (fastest, most ugly) 1: approximate 2: full (slowest) 3: bilinear (similiar to vobsub, fast and not too bad) 4: uses swscaler gaussian (this is the only one that looks good) R: Not supported (libswscale dependency removed) */ int spu_aamode = 3; int spu_alignment = -1; float spu_gaussvar = 1.0; typedef struct packet_t packet_t; struct packet_t { int is_decoded; unsigned char *packet; int data_len; unsigned int palette[4]; unsigned int alpha[4]; unsigned int control_start; /* index of start of control data */ unsigned int current_nibble[2]; /* next data nibble (4 bits) to be processed (for RLE decoding) for even and odd lines */ int deinterlace_oddness; /* 0 or 1, index into current_nibble */ unsigned int start_col; unsigned int start_row; unsigned int width, height, stride; unsigned int start_pts, end_pts; packet_t *next; }; struct palette_crop_cache { int valid; uint32_t palette; int sx, sy, ex, ey; int result; }; typedef struct { packet_t *queue_head; packet_t *queue_tail; unsigned int global_palette[16]; unsigned int orig_frame_width, orig_frame_height; unsigned char* packet; size_t packet_reserve; /* size of the memory pointed to by packet */ unsigned int packet_offset; /* end of the currently assembled fragment */ unsigned int packet_size; /* size of the packet once all fragments are assembled */ int packet_pts; /* PTS for this packet */ unsigned int palette[4]; unsigned int alpha[4]; unsigned int cuspal[4]; unsigned int custom; unsigned int now_pts; unsigned int start_pts, end_pts; unsigned int start_col; unsigned int start_row; unsigned int width, height, stride; size_t image_size; /* Size of the image buffer */ unsigned char *image; /* Grayscale value */ unsigned char *aimage; /* Alpha value */ unsigned int pal_start_col, pal_start_row; unsigned int pal_width, pal_height; unsigned char *pal_image; /* palette entry value */ unsigned int scaled_frame_width, scaled_frame_height; unsigned int scaled_start_col, scaled_start_row; unsigned int scaled_width, scaled_height, scaled_stride; size_t scaled_image_size; unsigned char *scaled_image; unsigned char *scaled_aimage; int auto_palette; /* 1 if we lack a palette and must use an heuristic. */ int font_start_level; /* Darkest value used for the computed font */ // const vo_functions_t *hw_spu; // R: not necessary int spu_changed; unsigned int forced_subs_only; /* flag: 0=display all subtitle, !0 display only forced subtitles */ unsigned int is_forced_sub; /* true if current subtitle is a forced subtitle */ struct palette_crop_cache palette_crop_cache; } spudec_handle_t; static void spudec_queue_packet(spudec_handle_t *this, packet_t *packet) { if (this->queue_head == NULL) this->queue_head = packet; else this->queue_tail->next = packet; this->queue_tail = packet; } static packet_t *spudec_dequeue_packet(spudec_handle_t *this) { packet_t *retval = this->queue_head; this->queue_head = retval->next; if (this->queue_head == NULL) this->queue_tail = NULL; return retval; } static void spudec_free_packet(packet_t *packet) { free(packet->packet); free(packet); } static inline unsigned int get_be16(const unsigned char *p) { return (p[0] << 8) + p[1]; } static inline unsigned int get_be24(const unsigned char *p) { return (get_be16(p) << 8) + p[2]; } static void next_line(packet_t *packet) { if (packet->current_nibble[packet->deinterlace_oddness] % 2) packet->current_nibble[packet->deinterlace_oddness]++; packet->deinterlace_oddness = (packet->deinterlace_oddness + 1) % 2; } static inline unsigned char get_nibble(packet_t *packet) { unsigned char nib; unsigned int *nibblep = packet->current_nibble + packet->deinterlace_oddness; if (*nibblep / 2 >= packet->control_start) { mp_msg(MSGT_SPUDEC,MSGL_WARN, "SPUdec: ERROR: get_nibble past end of packet\n"); return 0; } nib = packet->packet[*nibblep / 2]; if (*nibblep % 2) nib &= 0xf; else nib >>= 4; ++*nibblep; return nib; } /* Cut the sub to visible part */ static inline void spudec_cut_image(spudec_handle_t *this) { unsigned int fy, ly; unsigned int first_y, last_y; if (this->stride == 0 || this->height == 0) { return; } for (fy = 0; fy < this->image_size && !this->aimage[fy]; fy++); for (ly = this->stride * this->height-1; ly && !this->aimage[ly]; ly--); first_y = fy / this->stride; last_y = ly / this->stride; //printf("first_y: %d, last_y: %d\n", first_y, last_y); this->start_row += first_y; // Some subtitles trigger this condition if (last_y + 1 > first_y ) { this->height = last_y - first_y +1; } else { this->height = 0; return; } // printf("new h %d new start %d (sz %d st %d)---\n\n", this->height, this->start_row, this->image_size, this->stride); if (first_y > 0) { memmove(this->image, this->image + this->stride * first_y, this->stride * this->height); memmove(this->aimage, this->aimage + this->stride * first_y, this->stride * this->height); } } static int spudec_alloc_image(spudec_handle_t *this, int stride, int height) { if (this->width > stride) // just a safeguard this->width = stride; this->stride = stride; this->height = height; if (this->image_size < this->stride * this->height) { if (this->image != NULL) { free(this->image); free(this->pal_image); this->image_size = 0; this->pal_width = this->pal_height = 0; } this->image = malloc(2 * this->stride * this->height); if (this->image) { this->image_size = this->stride * this->height; this->aimage = this->image + this->image_size; // use stride here as well to simplify reallocation checks this->pal_image = malloc(this->stride * this->height); } } return this->image != NULL; } /** * \param pal palette in MPlayer-style gray-alpha values, i.e. * alpha == 0 means transparent, 1 fully opaque, * gray value <= 256 - alpha. */ static void pal2gray_alpha(const uint16_t *pal, const uint8_t *src, int src_stride, uint8_t *dst, uint8_t *dsta, int dst_stride, int w, int h) { int x, y; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { uint16_t pixel = pal[src[x]]; *dst++ = pixel; *dsta++ = pixel >> 8; } for (; x < dst_stride; x++) *dsta++ = *dst++ = 0; src += src_stride; } } static int apply_palette_crop(spudec_handle_t *this, unsigned crop_x, unsigned crop_y, unsigned crop_w, unsigned crop_h) { int i; uint8_t *src; uint16_t pal[4]; unsigned stride = (crop_w + 7) & ~7; if (crop_x > this->pal_width || crop_y > this->pal_height || crop_w > this->pal_width - crop_x || crop_h > this->pal_width - crop_y || crop_w > 0x8000 || crop_h > 0x8000 || stride * crop_h > this->image_size) { return 0; } for (i = 0; i < 4; ++i) { int color; int alpha = this->alpha[i]; // extend 4 -> 8 bit alpha |= alpha << 4; if (this->custom && (this->cuspal[i] >> 31) != 0) alpha = 0; color = this->custom ? this->cuspal[i] : this->global_palette[this->palette[i]]; color = (color >> 16) & 0xff; // convert to MPlayer-style gray/alpha palette color = FFMIN(color, alpha); pal[i] = (-alpha << 8) | color; } src = this->pal_image + crop_y * this->pal_width + crop_x; pal2gray_alpha(pal, src, this->pal_width, this->image, this->aimage, stride, crop_w, crop_h); this->width = crop_w; this->height = crop_h; this->stride = stride; this->start_col = this->pal_start_col + crop_x; this->start_row = this->pal_start_row + crop_y; spudec_cut_image(this); // reset scaled image this->scaled_frame_width = 0; this->scaled_frame_height = 0; this->palette_crop_cache.valid = 0; return 1; } int spudec_apply_palette_crop(void *this, uint32_t palette, int sx, int sy, int ex, int ey) { spudec_handle_t *spu = this; struct palette_crop_cache *c = &spu->palette_crop_cache; if (c->valid && c->palette == palette && c->sx == sx && c->sy == sy && c->ex == ex && c->ey == ey) return c->result; spu->palette[0] = (palette >> 28) & 0xf; spu->palette[1] = (palette >> 24) & 0xf; spu->palette[2] = (palette >> 20) & 0xf; spu->palette[3] = (palette >> 16) & 0xf; spu->alpha[0] = (palette >> 12) & 0xf; spu->alpha[1] = (palette >> 8) & 0xf; spu->alpha[2] = (palette >> 4) & 0xf; spu->alpha[3] = palette & 0xf; spu->spu_changed = 1; c->result = apply_palette_crop(spu, sx - spu->pal_start_col, sy - spu->pal_start_row, ex - sx, ey - sy); c->palette = palette; c->sx = sx; c->sy = sy; c->ex = ex; c->ey = ey; c->valid = 1; return c->result; } static void spudec_process_data(spudec_handle_t *this, packet_t *packet) { unsigned int i, x, y; uint8_t *dst; if (!spudec_alloc_image(this, packet->stride, packet->height)) return; this->pal_start_col = packet->start_col; this->pal_start_row = packet->start_row; this->pal_height = packet->height; this->pal_width = packet->width; this->stride = packet->stride; memcpy(this->palette, packet->palette, sizeof(this->palette)); memcpy(this->alpha, packet->alpha, sizeof(this->alpha)); i = packet->current_nibble[1]; x = 0; y = 0; dst = this->pal_image; while (packet->current_nibble[0] < i && packet->current_nibble[1] / 2 < packet->control_start && y < this->pal_height) { unsigned int len, color; unsigned int rle = 0; rle = get_nibble(packet); if (rle < 0x04) { if (rle == 0) { rle = (rle << 4) | get_nibble(packet); if (rle < 0x04) rle = (rle << 4) | get_nibble(packet); } rle = (rle << 4) | get_nibble(packet); } color = 3 - (rle & 0x3); len = rle >> 2; x += len; if (len == 0 || x >= this->pal_width) { len += this->pal_width - x; next_line(packet); x = 0; ++y; } memset(dst, color, len); dst += len; } apply_palette_crop(this, 0, 0, this->pal_width, this->pal_height); } /* This function tries to create a usable palette. It determines how many non-transparent colors are used, and assigns different gray scale values to each color. I tested it with four streams and even got something readable. Half of the times I got black characters with white around and half the reverse. */ static void compute_palette(spudec_handle_t *this, packet_t *packet) { int used[16],i,cused,start,step,color; memset(used, 0, sizeof(used)); for (i=0; i<4; i++) if (packet->alpha[i]) /* !Transparent? */ used[packet->palette[i]] = 1; for (cused=0, i=0; i<16; i++) if (used[i]) cused++; if (!cused) return; if (cused == 1) { start = 0x80; step = 0; } else { start = this->font_start_level; step = (0xF0-this->font_start_level)/(cused-1); } memset(used, 0, sizeof(used)); for (i=0; i<4; i++) { color = packet->palette[i]; if (packet->alpha[i] && !used[color]) { /* not assigned? */ used[color] = 1; this->global_palette[color] = start<<16; start += step; } } } static void spudec_process_control(spudec_handle_t *this, int pts100) { int a,b,c,d; /* Temporary vars */ unsigned int date, type; unsigned int off; unsigned int start_off = 0; unsigned int next_off; unsigned int start_pts = 0; unsigned int end_pts = 0; unsigned int current_nibble[2] = {0, 0}; unsigned int control_start; unsigned int display = 0; unsigned int start_col = 0; unsigned int end_col = 0; unsigned int start_row = 0; unsigned int end_row = 0; unsigned int width = 0; unsigned int height = 0; unsigned int stride = 0; control_start = get_be16(this->packet + 2); next_off = control_start; while (start_off != next_off) { start_off = next_off; date = get_be16(this->packet + start_off) * 1024; next_off = get_be16(this->packet + start_off + 2); mp_msg(MSGT_SPUDEC,MSGL_DBG2, "date=%d\n", date); off = start_off + 4; for (type = this->packet[off++]; type != 0xff; type = this->packet[off++]) { mp_msg(MSGT_SPUDEC,MSGL_DBG2, "cmd=%d ",type); switch(type) { case 0x00: /* Menu ID, 1 byte */ mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Menu ID\n"); /* shouldn't a Menu ID type force display start? */ start_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; end_pts = UINT_MAX; display = 1; this->is_forced_sub=~0; // current subtitle is forced break; case 0x01: /* Start display */ mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Start display!\n"); start_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; end_pts = UINT_MAX; display = 1; this->is_forced_sub=0; break; case 0x02: /* Stop display */ mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Stop display!\n"); end_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; break; case 0x03: /* Palette */ this->palette[0] = this->packet[off] >> 4; this->palette[1] = this->packet[off] & 0xf; this->palette[2] = this->packet[off + 1] >> 4; this->palette[3] = this->packet[off + 1] & 0xf; mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Palette %d, %d, %d, %d\n", this->palette[0], this->palette[1], this->palette[2], this->palette[3]); off+=2; break; case 0x04: /* Alpha */ a = this->packet[off] >> 4; b = this->packet[off] & 0xf; c = this->packet[off + 1] >> 4; d = this->packet[off + 1] & 0xf; // Note: some DVDs change these values to create a fade-in/fade-out effect // We can not handle this, so just keep the highest value during the display time. if (display) { a = FFMAX(a, this->alpha[0]); b = FFMAX(b, this->alpha[1]); c = FFMAX(c, this->alpha[2]); d = FFMAX(d, this->alpha[3]); } this->alpha[0] = a; this->alpha[1] = b; this->alpha[2] = c; this->alpha[3] = d; mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Alpha %d, %d, %d, %d\n", this->alpha[0], this->alpha[1], this->alpha[2], this->alpha[3]); off+=2; break; case 0x05: /* Co-ords */ a = get_be24(this->packet + off); b = get_be24(this->packet + off + 3); start_col = a >> 12; end_col = a & 0xfff; width = (end_col < start_col) ? 0 : end_col - start_col + 1; stride = (width + 7) & ~7; /* Kludge: draw_alpha needs width multiple of 8 */ start_row = b >> 12; end_row = b & 0xfff; height = (end_row < start_row) ? 0 : end_row - start_row /* + 1 */; mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Coords col: %d - %d row: %d - %d (%dx%d)\n", start_col, end_col, start_row, end_row, width, height); off+=6; break; case 0x06: /* Graphic lines */ current_nibble[0] = 2 * get_be16(this->packet + off); current_nibble[1] = 2 * get_be16(this->packet + off + 2); mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Graphic offset 1: %d offset 2: %d\n", current_nibble[0] / 2, current_nibble[1] / 2); off+=4; break; case 0xff: /* All done, bye-bye */ mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Done!\n"); return; // break; default: mp_msg(MSGT_SPUDEC,MSGL_WARN,"spudec: Error determining control type 0x%02x. Skipping %d bytes.\n", type, next_off - off); goto next_control; } } next_control: if (!display) continue; if (end_pts == UINT_MAX && start_off != next_off) { end_pts = get_be16(this->packet + next_off) * 1024; end_pts = 1 - pts100 >= end_pts ? 0 : pts100 + end_pts - 1; } if (end_pts > 0) { packet_t *packet = calloc(1, sizeof(packet_t)); int i; packet->start_pts = start_pts; packet->end_pts = end_pts; packet->current_nibble[0] = current_nibble[0]; @@ -736,738 +737,739 @@ void spudec_set_forced_subs_only(void * const this, const unsigned int flag) mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPU: Display only forced subs now %s\n", flag ? "enabled": "disabled"); } } void spudec_draw(void *this, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)) { spudec_handle_t *spu = this; if (spudec_visible(spu)) { draw_alpha(spu->start_col, spu->start_row, spu->width, spu->height, spu->image, spu->aimage, spu->stride); spu->spu_changed = 0; } } /* calc the bbox for spudec subs */ void spudec_calc_bbox(void *me, unsigned int dxs, unsigned int dys, unsigned int* bbox) { spudec_handle_t *spu = me; if (spu->orig_frame_width == 0 || spu->orig_frame_height == 0 || (spu->orig_frame_width == dxs && spu->orig_frame_height == dys)) { // unscaled bbox[0] = spu->start_col; bbox[1] = spu->start_col + spu->width; bbox[2] = spu->start_row; bbox[3] = spu->start_row + spu->height; } else { // scaled unsigned int scalex = 0x100 * dxs / spu->orig_frame_width; unsigned int scaley = 0x100 * dys / spu->orig_frame_height; bbox[0] = spu->start_col * scalex / 0x100; bbox[1] = spu->start_col * scalex / 0x100 + spu->width * scalex / 0x100; switch (spu_alignment) { case 0: bbox[3] = dys*sub_pos/100 + spu->height * scaley / 0x100; if (bbox[3] > dys) bbox[3] = dys; bbox[2] = bbox[3] - spu->height * scaley / 0x100; break; case 1: if (sub_pos < 50) { bbox[2] = dys*sub_pos/100 - spu->height * scaley / 0x200; bbox[3] = bbox[2] + spu->height; } else { bbox[3] = dys*sub_pos/100 + spu->height * scaley / 0x200; if (bbox[3] > dys) bbox[3] = dys; bbox[2] = bbox[3] - spu->height * scaley / 0x100; } break; case 2: bbox[2] = dys*sub_pos/100 - spu->height * scaley / 0x100; bbox[3] = bbox[2] + spu->height; break; default: /* -1 */ bbox[2] = spu->start_row * scaley / 0x100; bbox[3] = spu->start_row * scaley / 0x100 + spu->height * scaley / 0x100; break; } } } /* transform mplayer's alpha value into an opacity value that is linear */ static inline int canon_alpha(int alpha) { return (uint8_t)-alpha; } typedef struct { unsigned position; unsigned left_up; unsigned right_down; }scale_pixel; static void scale_table(unsigned int start_src, unsigned int start_tar, unsigned int end_src, unsigned int end_tar, scale_pixel * table) { unsigned int t; unsigned int delta_src = end_src - start_src; unsigned int delta_tar = end_tar - start_tar; int src = 0; int src_step; if (delta_src == 0 || delta_tar == 0) { return; } src_step = (delta_src << 16) / delta_tar >>1; for (t = 0; t<=delta_tar; src += (src_step << 1), t++){ table[t].position= FFMIN(src >> 16, end_src - 1); table[t].right_down = src & 0xffff; table[t].left_up = 0x10000 - table[t].right_down; } } /* bilinear scale, similar to vobsub's code */ static void scale_image(int x, int y, scale_pixel* table_x, scale_pixel* table_y, spudec_handle_t * spu) { int alpha[4]; int color[4]; unsigned int scale[4]; int base = table_y[y].position * spu->stride + table_x[x].position; int scaled = y * spu->scaled_stride + x; alpha[0] = canon_alpha(spu->aimage[base]); alpha[1] = canon_alpha(spu->aimage[base + 1]); alpha[2] = canon_alpha(spu->aimage[base + spu->stride]); alpha[3] = canon_alpha(spu->aimage[base + spu->stride + 1]); color[0] = spu->image[base]; color[1] = spu->image[base + 1]; color[2] = spu->image[base + spu->stride]; color[3] = spu->image[base + spu->stride + 1]; scale[0] = (table_x[x].left_up * table_y[y].left_up >> 16) * alpha[0]; if (table_y[y].left_up == 0x10000) // necessary to avoid overflow-case scale[0] = table_x[x].left_up * alpha[0]; scale[1] = (table_x[x].right_down * table_y[y].left_up >>16) * alpha[1]; scale[2] = (table_x[x].left_up * table_y[y].right_down >> 16) * alpha[2]; scale[3] = (table_x[x].right_down * table_y[y].right_down >> 16) * alpha[3]; spu->scaled_image[scaled] = (color[0] * scale[0] + color[1] * scale[1] + color[2] * scale[2] + color[3] * scale[3])>>24; spu->scaled_aimage[scaled] = (scale[0] + scale[1] + scale[2] + scale[3]) >> 16; if (spu->scaled_aimage[scaled]){ // ensure that MPlayer's simplified alpha-blending can not overflow spu->scaled_image[scaled] = FFMIN(spu->scaled_image[scaled], spu->scaled_aimage[scaled]); // convert to MPlayer-style alpha spu->scaled_aimage[scaled] = -spu->scaled_aimage[scaled]; } } #if 0 // R: removed sws scaling static void sws_spu_image(unsigned char *d1, unsigned char *d2, int dw, int dh, int ds, const unsigned char* s1, unsigned char* s2, int sw, int sh, int ss) { struct SwsContext *ctx; static SwsFilter filter; static int firsttime = 1; static float oldvar; int i; if (!firsttime && oldvar != spu_gaussvar) sws_freeVec(filter.lumH); if (firsttime) { filter.lumH = filter.lumV = filter.chrH = filter.chrV = sws_getGaussianVec(spu_gaussvar, 3.0); sws_normalizeVec(filter.lumH, 1.0); firsttime = 0; oldvar = spu_gaussvar; } ctx=sws_getContext(sw, sh, PIX_FMT_GRAY8, dw, dh, PIX_FMT_GRAY8, SWS_GAUSS, &filter, NULL, NULL); sws_scale(ctx,&s1,&ss,0,sh,&d1,&ds); for (i=ss*sh-1; i>=0; i--) if (!s2[i]) s2[i] = 255; //else s2[i] = 1; sws_scale(ctx,&s2,&ss,0,sh,&d2,&ds); for (i=ds*dh-1; i>=0; i--) if (d2[i]==0) d2[i] = 1; else if (d2[i]==255) d2[i] = 0; sws_freeContext(ctx); } #endif void spudec_draw_scaled(void *me, unsigned int dxs, unsigned int dys, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)) { spudec_handle_t *spu = me; scale_pixel *table_x; scale_pixel *table_y; if (spudec_visible(spu)) { // check if only forced subtitles are requested if( (spu->forced_subs_only) && !(spu->is_forced_sub) ){ return; } if (!(spu_aamode&16) && (spu->orig_frame_width == 0 || spu->orig_frame_height == 0 || (spu->orig_frame_width == dxs && spu->orig_frame_height == dys))) { spudec_draw(spu, draw_alpha); } else { if (spu->scaled_frame_width != dxs || spu->scaled_frame_height != dys) { /* Resizing is needed */ /* scaled_x = scalex * x / 0x100 scaled_y = scaley * y / 0x100 order of operations is important because of rounding. */ unsigned int scalex = 0x100 * dxs / spu->orig_frame_width; unsigned int scaley = 0x100 * dys / spu->orig_frame_height; spu->scaled_start_col = spu->start_col * scalex / 0x100; spu->scaled_start_row = spu->start_row * scaley / 0x100; spu->scaled_width = spu->width * scalex / 0x100; spu->scaled_height = spu->height * scaley / 0x100; /* Kludge: draw_alpha needs width multiple of 8 */ spu->scaled_stride = (spu->scaled_width + 7) & ~7; if (spu->scaled_image_size < spu->scaled_stride * spu->scaled_height) { if (spu->scaled_image) { free(spu->scaled_image); spu->scaled_image_size = 0; } spu->scaled_image = malloc(2 * spu->scaled_stride * spu->scaled_height); if (spu->scaled_image) { spu->scaled_image_size = spu->scaled_stride * spu->scaled_height; spu->scaled_aimage = spu->scaled_image + spu->scaled_image_size; } } if (spu->scaled_image) { unsigned int x, y; // needs to be 0-initialized because draw_alpha draws always a // multiple of 8 pixels. TODO: optimize if (spu->scaled_width & 7) memset(spu->scaled_image, 0, 2 * spu->scaled_image_size); if (spu->scaled_width <= 1 || spu->scaled_height <= 1) { goto nothing_to_do; } switch(spu_aamode&15) { case 4: #if 0 // R: no swscalar gaussian aa supported sws_spu_image(spu->scaled_image, spu->scaled_aimage, spu->scaled_width, spu->scaled_height, spu->scaled_stride, spu->image, spu->aimage, spu->width, spu->height, spu->stride); #else mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: no swsscalar gaussian aa supported"); #endif break; case 3: table_x = calloc(spu->scaled_width, sizeof(scale_pixel)); table_y = calloc(spu->scaled_height, sizeof(scale_pixel)); if (!table_x || !table_y) { mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: spudec_draw_scaled: calloc failed\n"); } scale_table(0, 0, spu->width - 1, spu->scaled_width - 1, table_x); scale_table(0, 0, spu->height - 1, spu->scaled_height - 1, table_y); for (y = 0; y < spu->scaled_height; y++) for (x = 0; x < spu->scaled_width; x++) scale_image(x, y, table_x, table_y, spu); free(table_x); free(table_y); break; case 0: /* no antialiasing */ for (y = 0; y < spu->scaled_height; ++y) { int unscaled_y = y * 0x100 / scaley; int strides = spu->stride * unscaled_y; int scaled_strides = spu->scaled_stride * y; for (x = 0; x < spu->scaled_width; ++x) { int unscaled_x = x * 0x100 / scalex; spu->scaled_image[scaled_strides + x] = spu->image[strides + unscaled_x]; spu->scaled_aimage[scaled_strides + x] = spu->aimage[strides + unscaled_x]; } } break; case 1: { /* Intermediate antialiasing. */ for (y = 0; y < spu->scaled_height; ++y) { const unsigned int unscaled_top = y * spu->orig_frame_height / dys; unsigned int unscaled_bottom = (y + 1) * spu->orig_frame_height / dys; if (unscaled_bottom >= spu->height) unscaled_bottom = spu->height - 1; for (x = 0; x < spu->scaled_width; ++x) { const unsigned int unscaled_left = x * spu->orig_frame_width / dxs; unsigned int unscaled_right = (x + 1) * spu->orig_frame_width / dxs; unsigned int color = 0; unsigned int alpha = 0; unsigned int walkx, walky; unsigned int base, tmp; if (unscaled_right >= spu->width) unscaled_right = spu->width - 1; for (walky = unscaled_top; walky <= unscaled_bottom; ++walky) for (walkx = unscaled_left; walkx <= unscaled_right; ++walkx) { base = walky * spu->stride + walkx; tmp = canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } base = y * spu->scaled_stride + x; spu->scaled_image[base] = alpha ? color / alpha : 0; spu->scaled_aimage[base] = alpha * (1 + unscaled_bottom - unscaled_top) * (1 + unscaled_right - unscaled_left); /* spu->scaled_aimage[base] = alpha * dxs * dys / spu->orig_frame_width / spu->orig_frame_height; */ if (spu->scaled_aimage[base]) { spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; } } } } break; case 2: { /* Best antialiasing. Very slow. */ /* Any pixel (x, y) represents pixels from the original rectangular region comprised between the columns unscaled_y and unscaled_y + 0x100 / scaley and the rows unscaled_x and unscaled_x + 0x100 / scalex The original rectangular region that the scaled pixel represents is cut in 9 rectangular areas like this: +---+-----------------+---+ | 1 | 2 | 3 | +---+-----------------+---+ | | | | | 4 | 5 | 6 | | | | | +---+-----------------+---+ | 7 | 8 | 9 | +---+-----------------+---+ The width of the left column is at most one pixel and it is never null and its right column is at a pixel boundary. The height of the top row is at most one pixel it is never null and its bottom row is at a pixel boundary. The width and height of region 5 are integral values. The width of the right column is what remains and is less than one pixel. The height of the bottom row is what remains and is less than one pixel. The row above 1, 2, 3 is unscaled_y. The row between 1, 2, 3 and 4, 5, 6 is top_low_row. The row between 4, 5, 6 and 7, 8, 9 is (unsigned int)unscaled_y_bottom. The row beneath 7, 8, 9 is unscaled_y_bottom. The column left of 1, 4, 7 is unscaled_x. The column between 1, 4, 7 and 2, 5, 8 is left_right_column. The column between 2, 5, 8 and 3, 6, 9 is (unsigned int)unscaled_x_right. The column right of 3, 6, 9 is unscaled_x_right. */ const double inv_scalex = (double) 0x100 / scalex; const double inv_scaley = (double) 0x100 / scaley; for (y = 0; y < spu->scaled_height; ++y) { const double unscaled_y = y * inv_scaley; const double unscaled_y_bottom = unscaled_y + inv_scaley; const unsigned int top_low_row = FFMIN(unscaled_y_bottom, unscaled_y + 1.0); const double top = top_low_row - unscaled_y; const unsigned int height = unscaled_y_bottom > top_low_row ? (unsigned int) unscaled_y_bottom - top_low_row : 0; const double bottom = unscaled_y_bottom > top_low_row ? unscaled_y_bottom - floor(unscaled_y_bottom) : 0.0; for (x = 0; x < spu->scaled_width; ++x) { const double unscaled_x = x * inv_scalex; const double unscaled_x_right = unscaled_x + inv_scalex; const unsigned int left_right_column = FFMIN(unscaled_x_right, unscaled_x + 1.0); const double left = left_right_column - unscaled_x; const unsigned int width = unscaled_x_right > left_right_column ? (unsigned int) unscaled_x_right - left_right_column : 0; const double right = unscaled_x_right > left_right_column ? unscaled_x_right - floor(unscaled_x_right) : 0.0; double color = 0.0; double alpha = 0.0; double tmp; unsigned int base; /* Now use these informations to compute a good alpha, and lightness. The sum is on each of the 9 region's surface and alpha and lightness. transformed alpha = sum(surface * alpha) / sum(surface) transformed color = sum(surface * alpha * color) / sum(surface * alpha) */ /* 1: top left part */ base = spu->stride * (unsigned int) unscaled_y; tmp = left * top * canon_alpha(spu->aimage[base + (unsigned int) unscaled_x]); alpha += tmp; color += tmp * spu->image[base + (unsigned int) unscaled_x]; /* 2: top center part */ if (width > 0) { unsigned int walkx; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { base = spu->stride * (unsigned int) unscaled_y + walkx; tmp = /* 1.0 * */ top * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 3: top right part */ if (right > 0.0) { base = spu->stride * (unsigned int) unscaled_y + (unsigned int) unscaled_x_right; tmp = right * top * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* 4: center left part */ if (height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { base = spu->stride * walky + (unsigned int) unscaled_x; tmp = left /* * 1.0 */ * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 5: center part */ if (width > 0 && height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { unsigned int walkx; base = spu->stride * walky; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { tmp = /* 1.0 * 1.0 * */ canon_alpha(spu->aimage[base + walkx]); alpha += tmp; color += tmp * spu->image[base + walkx]; } } } /* 6: center right part */ if (right > 0.0 && height > 0) { unsigned int walky; for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { base = spu->stride * walky + (unsigned int) unscaled_x_right; tmp = right /* * 1.0 */ * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } } /* 7: bottom left part */ if (bottom > 0.0) { base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x; tmp = left * bottom * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* 8: bottom center part */ if (width > 0 && bottom > 0.0) { unsigned int walkx; base = spu->stride * (unsigned int) unscaled_y_bottom; for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { tmp = /* 1.0 * */ bottom * canon_alpha(spu->aimage[base + walkx]); alpha += tmp; color += tmp * spu->image[base + walkx]; } } /* 9: bottom right part */ if (right > 0.0 && bottom > 0.0) { base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x_right; tmp = right * bottom * canon_alpha(spu->aimage[base]); alpha += tmp; color += tmp * spu->image[base]; } /* Finally mix these transparency and brightness information suitably */ base = spu->scaled_stride * y + x; spu->scaled_image[base] = alpha > 0 ? color / alpha : 0; spu->scaled_aimage[base] = alpha * scalex * scaley / 0x10000; if (spu->scaled_aimage[base]) { spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; } } } } } nothing_to_do: /* Kludge: draw_alpha needs width multiple of 8. */ if (spu->scaled_width < spu->scaled_stride) for (y = 0; y < spu->scaled_height; ++y) { memset(spu->scaled_aimage + y * spu->scaled_stride + spu->scaled_width, 0, spu->scaled_stride - spu->scaled_width); } spu->scaled_frame_width = dxs; spu->scaled_frame_height = dys; } } if (spu->scaled_image){ switch (spu_alignment) { case 0: spu->scaled_start_row = dys*sub_pos/100; if (spu->scaled_start_row + spu->scaled_height > dys) spu->scaled_start_row = dys - spu->scaled_height; break; case 1: spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height/2; if (sub_pos >= 50 && spu->scaled_start_row + spu->scaled_height > dys) spu->scaled_start_row = dys - spu->scaled_height; break; case 2: spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height; break; } draw_alpha(spu->scaled_start_col, spu->scaled_start_row, spu->scaled_width, spu->scaled_height, spu->scaled_image, spu->scaled_aimage, spu->scaled_stride); spu->spu_changed = 0; } } } else { mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPU not displayed: start_pts=%d end_pts=%d now_pts=%d\n", spu->start_pts, spu->end_pts, spu->now_pts); } } void spudec_update_palette(void * this, unsigned int *palette) { spudec_handle_t *spu = this; if (spu && palette) { memcpy(spu->global_palette, palette, sizeof(spu->global_palette)); #if 0 // R: OSD stuff removed if(spu->hw_spu) spu->hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); #endif } } void spudec_set_font_factor(void * this, double factor) { spudec_handle_t *spu = this; spu->font_start_level = (int)(0xF0-(0xE0*factor)); } #ifndef AV_RB32 // R: AV_RB32 for older ffmpeg (libavutil) releases #ifndef __GNUC__ // only implemented the GCC version of AV_RB32 #error "Get a newer ffmpeg (libavutil) version" #endif /* code taken from ffmpeg/libavutil. intreadwrite.h and bswap.h +common.h is copyright (c) 2006 Michael Niedermayer <[email protected]> bswap.h is copyright (C) 2006 by Michael Niedermayer <[email protected]> intreadwrite.h does not contain a specific copyright notice. the code is licensed under LGPL 2 with the following license header FFmpeg is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. FFmpeg is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with FFmpeg; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ union unaligned_32 { uint32_t l; } __attribute__((packed)) __attribute__((may_alias)); #define AV_RN32(p) (((const union unaligned_32 *) (p))->l) #ifdef AV_HAVE_BIGENDIAN // TODO add detection #define AV_RB32(p) AV_RN32(p) #else // little endian static __attribute__((always_inline)) inline uint32_t __attribute__((const)) av_bswap32(uint32_t x) { x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); x= (x>>16) | (x<<16); return x; } #define AV_RB32(p) av_bswap32(AV_RN32(p)) #endif // AV_HAVE_BIG_ENDIAN #endif // AV_RB32 static void spudec_parse_extradata(spudec_handle_t *this, uint8_t *extradata, int extradata_len) { uint8_t *buffer, *ptr; unsigned int *pal = this->global_palette, *cuspal = this->cuspal; unsigned int tridx; int i; if (extradata_len == 16*4) { for (i=0; i<16; i++) pal[i] = AV_RB32(extradata + i*4); this->auto_palette = 0; return; } if (!(ptr = buffer = malloc(extradata_len+1))) return; memcpy(buffer, extradata, extradata_len); buffer[extradata_len] = 0; do { if (*ptr == '#') continue; if (!strncmp(ptr, "size: ", 6)) sscanf(ptr + 6, "%dx%d", &this->orig_frame_width, &this->orig_frame_height); if (!strncmp(ptr, "palette: ", 9) && sscanf(ptr + 9, "%x, %x, %x, %x, %x, %x, %x, %x, " "%x, %x, %x, %x, %x, %x, %x, %x", &pal[ 0], &pal[ 1], &pal[ 2], &pal[ 3], &pal[ 4], &pal[ 5], &pal[ 6], &pal[ 7], &pal[ 8], &pal[ 9], &pal[10], &pal[11], &pal[12], &pal[13], &pal[14], &pal[15]) == 16) { for (i=0; i<16; i++) pal[i] = vobsub_palette_to_yuv(pal[i]); this->auto_palette = 0; } if (!strncasecmp(ptr, "forced subs: on", 15)) this->forced_subs_only = 1; if (!strncmp(ptr, "custom colors: ON, tridx: ", 26) && sscanf(ptr + 26, "%x, colors: %x, %x, %x, %x", &tridx, cuspal+0, cuspal+1, cuspal+2, cuspal+3) == 5) { for (i=0; i<4; i++) { cuspal[i] = vobsub_rgb_to_yuv(cuspal[i]); if (tridx & (1 << (12-4*i))) cuspal[i] |= 1 << 31; } this->custom = 1; } } while ((ptr=strchr(ptr,'\n')) && *++ptr); free(buffer); } void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len) { spudec_handle_t *this = calloc(1, sizeof(spudec_handle_t)); if (this){ this->orig_frame_height = frame_height; this->orig_frame_width = frame_width; // set up palette: if (palette) memcpy(this->global_palette, palette, sizeof(this->global_palette)); else this->auto_palette = 1; if (extradata) spudec_parse_extradata(this, extradata, extradata_len); /* XXX Although the video frame is some size, the SPU frame is always maximum size i.e. 720 wide and 576 or 480 high */ // For HD files in MKV the VobSub resolution can be higher though, // see largeres_vobsub.mkv if (this->orig_frame_width <= 720 && this->orig_frame_height <= 576) { this->orig_frame_width = 720; if (this->orig_frame_height == 480 || this->orig_frame_height == 240) this->orig_frame_height = 480; else this->orig_frame_height = 576; } } else mp_msg(MSGT_SPUDEC,MSGL_FATAL, "FATAL: spudec_init: calloc"); return this; } void *spudec_new(unsigned int *palette) { return spudec_new_scaled(palette, 0, 0, NULL, 0); } void spudec_free(void *this) { spudec_handle_t *spu = this; if (spu) { while (spu->queue_head) spudec_free_packet(spudec_dequeue_packet(spu)); free(spu->packet); spu->packet = NULL; free(spu->scaled_image); spu->scaled_image = NULL; free(spu->image); spu->image = NULL; spu->aimage = NULL; free(spu->pal_image); spu->pal_image = NULL; spu->image_size = 0; spu->pal_width = spu->pal_height = 0; free(spu); } } #if 0 // R: not necessary void spudec_set_hw_spu(void *this, const vo_functions_t *hw_spu) { spudec_handle_t *spu = this; if (!spu) return; spu->hw_spu = hw_spu; hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); } #endif #define MP_NOPTS_VALUE (-1LL<<63) //both int64_t and double should be able to represent this exactly /** * palette must contain at least 256 32-bit entries, otherwise crashes * are possible */ void spudec_set_paletted(void *this, const uint8_t *pal_img, int pal_stride, const void *palette, int x, int y, int w, int h, double pts, double endpts) { int i; uint16_t g8a8_pal[256]; packet_t *packet; const uint32_t *pal = palette; spudec_handle_t *spu = this; uint8_t *img; uint8_t *aimg; int stride = (w + 7) & ~7; if ((unsigned)w >= 0x8000 || (unsigned)h > 0x4000) return; packet = calloc(1, sizeof(packet_t)); packet->is_decoded = 1; packet->width = w; packet->height = h; packet->stride = stride; packet->start_col = x; packet->start_row = y; packet->data_len = 2 * stride * h; if (packet->data_len) { // size 0 is a special "clear" packet packet->packet = malloc(packet->data_len); img = packet->packet; aimg = packet->packet + stride * h; for (i = 0; i < 256; i++) { uint32_t pixel = pal[i]; int alpha = pixel >> 24; int gray = (((pixel & 0x000000ff) >> 0) + ((pixel & 0x0000ff00) >> 7) + ((pixel & 0x00ff0000) >> 16)) >> 2; gray = FFMIN(gray, alpha); g8a8_pal[i] = (-alpha << 8) | gray; } pal2gray_alpha(g8a8_pal, pal_img, pal_stride, img, aimg, stride, w, h); } packet->start_pts = 0; packet->end_pts = 0x7fffffff; if (pts != MP_NOPTS_VALUE) packet->start_pts = pts * 90000; if (endpts != MP_NOPTS_VALUE) packet->end_pts = endpts * 90000; spudec_queue_packet(spu, packet); } // R: added to extract data void spudec_get_data(void *this, const unsigned char **image, size_t *image_size, unsigned *width, unsigned *height, unsigned *stride, unsigned *start_pts, unsigned *end_pts) { spudec_handle_t *spu = this; *image = spu->image; *image_size = spu->image_size; *width = spu->width; *height = spu->height; *stride = spu->stride; *start_pts = spu->start_pts; *end_pts = spu->end_pts; } diff --git a/mplayer/vobsub.c b/mplayer/vobsub.c index cc962ee..3bac2ac 100644 --- a/mplayer/vobsub.c +++ b/mplayer/vobsub.c @@ -1,1240 +1,1276 @@ /* -*- mode: c; c-basic-offset: 4 -*- * Some code freely inspired from VobSub <URL:http://vobsub.edensrising.com>, * with kind permission from Gabest <[email protected]> * * This file is part of MPlayer. * * MPlayer is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> //#include "config.h" #define CONFIG_UNRAR_EXEC 1 // moved from config.h //#include "mpcommon.h" #include "vobsub.h" #include "spudec.h" #include "mp_msg.h" #include "unrar_exec.h" -#include <libavutil/common.h> // use system's libavutil // Record the original -vobsubid set by commandline, since vobsub_id will be // overridden if slang match any of vobsub streams. static int vobsubid = -2; int vobsub_id = 0; // moved from mpcommon.h/mplayer.c /********************************************************************** * RAR stream handling * The RAR file must have the same basename as the file to open **********************************************************************/ #ifdef CONFIG_UNRAR_EXEC typedef struct { FILE *file; unsigned char *data; unsigned long size; unsigned long pos; } rar_stream_t; static rar_stream_t *rar_open(const char *const filename, const char *const mode) { rar_stream_t *stream; /* unrar_exec can only read */ if (strcmp("r", mode) && strcmp("rb", mode)) { errno = EINVAL; return NULL; } stream = malloc(sizeof(rar_stream_t)); if (stream == NULL) return NULL; /* first try normal access */ stream->file = fopen(filename, mode); if (stream->file == NULL) { char *rar_filename; const char *p; int rc; /* Guess the RAR archive filename */ rar_filename = NULL; p = strrchr(filename, '.'); if (p) { ptrdiff_t l = p - filename; rar_filename = malloc(l + 5); if (rar_filename == NULL) { free(stream); return NULL; } strncpy(rar_filename, filename, l); strcpy(rar_filename + l, ".rar"); } else { rar_filename = malloc(strlen(filename) + 5); if (rar_filename == NULL) { free(stream); return NULL; } strcpy(rar_filename, filename); strcat(rar_filename, ".rar"); } /* get rid of the path if there is any */ if ((p = strrchr(filename, '/')) == NULL) { p = filename; } else { p++; } rc = unrar_exec_get(&stream->data, &stream->size, p, rar_filename); if (!rc) { /* There is no matching filename in the archive. However, sometimes * the files we are looking for have been given arbitrary names in the archive. * Let's look for a file with an exact match in the extension only. */ int i, num_files, name_len; ArchiveList_struct *list, *lp; num_files = unrar_exec_list(rar_filename, &list); if (num_files > 0) { char *demanded_ext; demanded_ext = strrchr (p, '.'); if (demanded_ext) { int demanded_ext_len = strlen (demanded_ext); for (i = 0, lp = list; i < num_files; i++, lp = lp->next) { name_len = strlen (lp->item.Name); if (name_len >= demanded_ext_len && !strcasecmp (lp->item.Name + name_len - demanded_ext_len, demanded_ext)) { rc = unrar_exec_get(&stream->data, &stream->size, lp->item.Name, rar_filename); if (rc) break; } } } unrar_exec_freelist(list); } if (!rc) { free(rar_filename); free(stream); return NULL; } } free(rar_filename); stream->pos = 0; } return stream; } static int rar_close(rar_stream_t *stream) { if (stream->file) return fclose(stream->file); free(stream->data); return 0; } static int rar_eof(rar_stream_t *stream) { if (stream->file) return feof(stream->file); return stream->pos >= stream->size; } static long rar_tell(rar_stream_t *stream) { if (stream->file) return ftell(stream->file); return stream->pos; } static int rar_seek(rar_stream_t *stream, long offset, int whence) { if (stream->file) return fseek(stream->file, offset, whence); switch (whence) { case SEEK_SET: if (offset < 0) { errno = EINVAL; return -1; } stream->pos = offset; break; case SEEK_CUR: if (offset < 0 && stream->pos < (unsigned long) -offset) { errno = EINVAL; return -1; } stream->pos += offset; break; case SEEK_END: if (offset < 0 && stream->size < (unsigned long) -offset) { errno = EINVAL; return -1; } stream->pos = stream->size + offset; break; default: errno = EINVAL; return -1; } return 0; } static int rar_getc(rar_stream_t *stream) { if (stream->file) return getc(stream->file); if (rar_eof(stream)) return EOF; return stream->data[stream->pos++]; } static size_t rar_read(void *ptr, size_t size, size_t nmemb, rar_stream_t *stream) { size_t res; unsigned long remain; if (stream->file) return fread(ptr, size, nmemb, stream->file); if (rar_eof(stream)) return 0; res = size * nmemb; remain = stream->size - stream->pos; if (res > remain) res = remain / size * size; memcpy(ptr, stream->data + stream->pos, res); stream->pos += res; res /= size; return res; } #else typedef FILE rar_stream_t; #define rar_open fopen #define rar_close fclose #define rar_eof feof #define rar_tell ftell #define rar_seek fseek #define rar_getc getc #define rar_read fread #endif /**********************************************************************/ static ssize_t vobsub_getline(char **lineptr, size_t *n, rar_stream_t *stream) { size_t res = 0; int c; if (*lineptr == NULL) { *lineptr = malloc(4096); if (*lineptr) *n = 4096; } else if (*n == 0) { char *tmp = realloc(*lineptr, 4096); if (tmp) { *lineptr = tmp; *n = 4096; } } if (*lineptr == NULL || *n == 0) return -1; for (c = rar_getc(stream); c != EOF; c = rar_getc(stream)) { if (res + 1 >= *n) { char *tmp = realloc(*lineptr, *n * 2); if (tmp == NULL) return -1; *lineptr = tmp; *n *= 2; } (*lineptr)[res++] = c; if (c == '\n') { (*lineptr)[res] = 0; return res; } } if (res == 0) return -1; (*lineptr)[res] = 0; return res; } /********************************************************************** * MPEG parsing **********************************************************************/ typedef struct { rar_stream_t *stream; unsigned int pts; int aid; unsigned char *packet; unsigned int packet_reserve; unsigned int packet_size; int padding_was_here; int merge; } mpeg_t; static mpeg_t *mpeg_open(const char *filename) { mpeg_t *res = malloc(sizeof(mpeg_t)); int err = res == NULL; if (!err) { res->pts = 0; res->aid = -1; res->packet = NULL; res->packet_size = 0; res->packet_reserve = 0; res->padding_was_here = 1; res->merge = 0; res->stream = rar_open(filename, "rb"); err = res->stream == NULL; if (err) perror("fopen Vobsub file failed"); if (err) free(res); } return err ? NULL : res; } static void mpeg_free(mpeg_t *mpeg) { if (mpeg->packet) free(mpeg->packet); if (mpeg->stream) rar_close(mpeg->stream); free(mpeg); } static int mpeg_eof(mpeg_t *mpeg) { return rar_eof(mpeg->stream); } static off_t mpeg_tell(mpeg_t *mpeg) { return rar_tell(mpeg->stream); } static int mpeg_run(mpeg_t *mpeg) { unsigned int len, idx, version; int c; /* Goto start of a packet, it starts with 0x000001?? */ const unsigned char wanted[] = { 0, 0, 1 }; unsigned char buf[5]; mpeg->aid = -1; mpeg->packet_size = 0; if (rar_read(buf, 4, 1, mpeg->stream) != 1) return -1; while (memcmp(buf, wanted, sizeof(wanted)) != 0) { c = rar_getc(mpeg->stream); if (c < 0) return -1; memmove(buf, buf + 1, 3); buf[3] = c; } switch (buf[3]) { case 0xb9: /* System End Code */ break; case 0xba: /* Packet start code */ c = rar_getc(mpeg->stream); if (c < 0) return -1; if ((c & 0xc0) == 0x40) version = 4; else if ((c & 0xf0) == 0x20) version = 2; else { mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Unsupported MPEG version: 0x%02x\n", c); return -1; } if (version == 4) { if (rar_seek(mpeg->stream, 9, SEEK_CUR)) return -1; } else if (version == 2) { if (rar_seek(mpeg->stream, 7, SEEK_CUR)) return -1; } else abort(); if (!mpeg->padding_was_here) mpeg->merge = 1; break; case 0xbd: /* packet */ if (rar_read(buf, 2, 1, mpeg->stream) != 1) return -1; mpeg->padding_was_here = 0; len = buf[0] << 8 | buf[1]; idx = mpeg_tell(mpeg); c = rar_getc(mpeg->stream); if (c < 0) return -1; if ((c & 0xC0) == 0x40) { /* skip STD scale & size */ if (rar_getc(mpeg->stream) < 0) return -1; c = rar_getc(mpeg->stream); if (c < 0) return -1; } if ((c & 0xf0) == 0x20) { /* System-1 stream timestamp */ /* Do we need this? */ abort(); } else if ((c & 0xf0) == 0x30) { /* Do we need this? */ abort(); } else if ((c & 0xc0) == 0x80) { /* System-2 (.VOB) stream */ unsigned int pts_flags, hdrlen, dataidx; c = rar_getc(mpeg->stream); if (c < 0) return -1; pts_flags = c; c = rar_getc(mpeg->stream); if (c < 0) return -1; hdrlen = c; dataidx = mpeg_tell(mpeg) + hdrlen; if (dataidx > idx + len) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "Invalid header length: %d (total length: %d, idx: %d, dataidx: %d)\n", hdrlen, len, idx, dataidx); return -1; } if ((pts_flags & 0xc0) == 0x80) { if (rar_read(buf, 5, 1, mpeg->stream) != 1) return -1; if (!(((buf[0] & 0xf0) == 0x20) && (buf[0] & 1) && (buf[2] & 1) && (buf[4] & 1))) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub PTS error: 0x%02x %02x%02x %02x%02x \n", buf[0], buf[1], buf[2], buf[3], buf[4]); mpeg->pts = 0; } else mpeg->pts = ((buf[0] & 0x0e) << 29 | buf[1] << 22 | (buf[2] & 0xfe) << 14 | buf[3] << 7 | (buf[4] >> 1)); } else /* if ((pts_flags & 0xc0) == 0xc0) */ { /* what's this? */ /* abort(); */ } rar_seek(mpeg->stream, dataidx, SEEK_SET); mpeg->aid = rar_getc(mpeg->stream); if (mpeg->aid < 0) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "Bogus aid %d\n", mpeg->aid); return -1; } mpeg->packet_size = len - ((unsigned int) mpeg_tell(mpeg) - idx); if (mpeg->packet_reserve < mpeg->packet_size) { if (mpeg->packet) free(mpeg->packet); mpeg->packet = malloc(mpeg->packet_size); if (mpeg->packet) mpeg->packet_reserve = mpeg->packet_size; } if (mpeg->packet == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); mpeg->packet_reserve = 0; mpeg->packet_size = 0; return -1; } if (rar_read(mpeg->packet, mpeg->packet_size, 1, mpeg->stream) != 1) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "fread failure"); mpeg->packet_size = 0; return -1; } idx = len; } break; case 0xbe: /* Padding */ if (rar_read(buf, 2, 1, mpeg->stream) != 1) return -1; len = buf[0] << 8 | buf[1]; if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) return -1; mpeg->padding_was_here = 1; break; default: if (0xc0 <= buf[3] && buf[3] < 0xf0) { /* MPEG audio or video */ if (rar_read(buf, 2, 1, mpeg->stream) != 1) return -1; len = buf[0] << 8 | buf[1]; if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) return -1; } else { mp_msg(MSGT_VOBSUB, MSGL_ERR, "unknown header 0x%02X%02X%02X%02X\n", buf[0], buf[1], buf[2], buf[3]); return -1; } } return 0; } /********************************************************************** * Packet queue **********************************************************************/ typedef struct { unsigned int pts100; off_t filepos; unsigned int size; unsigned char *data; } packet_t; typedef struct { char *id; packet_t *packets; unsigned int packets_reserve; unsigned int packets_size; unsigned int current_index; } packet_queue_t; static void packet_construct(packet_t *pkt) { pkt->pts100 = 0; pkt->filepos = 0; pkt->size = 0; pkt->data = NULL; } static void packet_destroy(packet_t *pkt) { if (pkt->data) free(pkt->data); } static void packet_queue_construct(packet_queue_t *queue) { queue->id = NULL; queue->packets = NULL; queue->packets_reserve = 0; queue->packets_size = 0; queue->current_index = 0; } static void packet_queue_destroy(packet_queue_t *queue) { if (queue->packets) { while (queue->packets_size--) packet_destroy(queue->packets + queue->packets_size); free(queue->packets); } return; } /* Make sure there is enough room for needed_size packets in the packet queue. */ static int packet_queue_ensure(packet_queue_t *queue, unsigned int needed_size) { if (queue->packets_reserve < needed_size) { if (queue->packets) { packet_t *tmp = realloc(queue->packets, 2 * queue->packets_reserve * sizeof(packet_t)); if (tmp == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "realloc failure"); return -1; } queue->packets = tmp; queue->packets_reserve *= 2; } else { queue->packets = malloc(sizeof(packet_t)); if (queue->packets == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); return -1; } queue->packets_reserve = 1; } } return 0; } /* add one more packet */ static int packet_queue_grow(packet_queue_t *queue) { if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) return -1; packet_construct(queue->packets + queue->packets_size); ++queue->packets_size; return 0; } /* insert a new packet, duplicating pts from the current one */ static int packet_queue_insert(packet_queue_t *queue) { packet_t *pkts; if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) return -1; /* XXX packet_size does not reflect the real thing here, it will be updated a bit later */ memmove(queue->packets + queue->current_index + 2, queue->packets + queue->current_index + 1, sizeof(packet_t) * (queue->packets_size - queue->current_index - 1)); pkts = queue->packets + queue->current_index; ++queue->packets_size; ++queue->current_index; packet_construct(pkts + 1); pkts[1].pts100 = pkts[0].pts100; pkts[1].filepos = pkts[0].filepos; return 0; } /********************************************************************** * Vobsub **********************************************************************/ typedef struct { unsigned int palette[16]; int delay; unsigned int have_palette; unsigned int orig_frame_width, orig_frame_height; unsigned int origin_x, origin_y; /* index */ packet_queue_t *spu_streams; unsigned int spu_streams_size; unsigned int spu_streams_current; unsigned int spu_valid_streams_size; } vobsub_t; /* Make sure that the spu stream idx exists. */ static int vobsub_ensure_spu_stream(vobsub_t *vob, unsigned int index) { if (index >= vob->spu_streams_size) { /* This is a new stream */ if (vob->spu_streams) { packet_queue_t *tmp = realloc(vob->spu_streams, (index + 1) * sizeof(packet_queue_t)); if (tmp == NULL) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: realloc failure"); return -1; } vob->spu_streams = tmp; } else { vob->spu_streams = malloc((index + 1) * sizeof(packet_queue_t)); if (vob->spu_streams == NULL) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: malloc failure"); return -1; } } while (vob->spu_streams_size <= index) { packet_queue_construct(vob->spu_streams + vob->spu_streams_size); ++vob->spu_streams_size; } } return 0; } static int vobsub_add_id(vobsub_t *vob, const char *id, size_t idlen, const unsigned int index) { if (vobsub_ensure_spu_stream(vob, index) < 0) return -1; if (id && idlen) { if (vob->spu_streams[index].id) free(vob->spu_streams[index].id); vob->spu_streams[index].id = malloc(idlen + 1); if (vob->spu_streams[index].id == NULL) { mp_msg(MSGT_VOBSUB, MSGL_FATAL, "vobsub_add_id: malloc failure"); return -1; } vob->spu_streams[index].id[idlen] = 0; memcpy(vob->spu_streams[index].id, id, idlen); } vob->spu_streams_current = index; mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VOBSUB_ID=%d\n", index); if (id && idlen) mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VSID_%d_LANG=%s\n", index, vob->spu_streams[index].id); mp_msg(MSGT_VOBSUB, MSGL_V, "[vobsub] subtitle (vobsubid): %d language %s\n", index, vob->spu_streams[index].id); return 0; } static int vobsub_add_timestamp(vobsub_t *vob, off_t filepos, int ms) { packet_queue_t *queue; packet_t *pkt; if (vob->spu_streams == 0) { mp_msg(MSGT_VOBSUB, MSGL_WARN, "[vobsub] warning, binning some index entries. Check your index file\n"); return -1; } queue = vob->spu_streams + vob->spu_streams_current; if (packet_queue_grow(queue) >= 0) { pkt = queue->packets + (queue->packets_size - 1); pkt->filepos = filepos; pkt->pts100 = ms < 0 ? UINT_MAX : (unsigned int)ms * 90; return 0; } return -1; } static int vobsub_parse_id(vobsub_t *vob, const char *line) { // id: xx, index: n size_t idlen; const char *p, *q; p = line; while (isspace(*p)) ++p; q = p; while (isalpha(*q)) ++q; idlen = q - p; if (idlen == 0) return -1; ++q; while (isspace(*q)) ++q; if (strncmp("index:", q, 6)) return -1; q += 6; while (isspace(*q)) ++q; if (!isdigit(*q)) return -1; return vobsub_add_id(vob, p, idlen, atoi(q)); } static int vobsub_parse_timestamp(vobsub_t *vob, const char *line) { // timestamp: HH:MM:SS.mmm, filepos: 0nnnnnnnnn int h, m, s, ms; off_t filepos; if (sscanf(line, " %02d:%02d:%02d:%03d, filepos: %09"PRIx64"", &h, &m, &s, &ms, &filepos) != 5) return -1; return vobsub_add_timestamp(vob, filepos, vob->delay + ms + 1000 * (s + 60 * (m + 60 * h))); } static int vobsub_parse_origin(vobsub_t *vob, const char *line) { // org: X,Y unsigned x, y; if (sscanf(line, " %u,%u", &x, &y) == 2) { vob->origin_x = x; vob->origin_y = y; return 0; } return -1; } +/* + * The code for av_clip_uint8_c is copied from libavutil! + * See libavutil/common.h. The copyright for av_clip_uint8_c is: + * + * copyright (c) 2006 Michael Niedermayer <[email protected]> + * + * This file is part of Libav. + * + * Libav is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * Libav is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * Clip a signed integer value into the 0-255 range. + * @param a value to clip + * @return clipped value + */ +static __attribute__((always_inline)) inline __attribute__((const)) uint8_t av_clip_uint8_c(int a) +{ + if (a&(~0xFF)) return (-a)>>31; + else return a; +} +#ifndef av_clip_uint8 +# define av_clip_uint8 av_clip_uint8_c +#endif + unsigned int vobsub_palette_to_yuv(unsigned int pal) { int r, g, b, y, u, v; // Palette in idx file is not rgb value, it was calculated by wrong formula. // Here's reversed formula of the one used to generate palette in idx file. r = pal >> 16 & 0xff; g = pal >> 8 & 0xff; b = pal & 0xff; y = av_clip_uint8( 0.1494 * r + 0.6061 * g + 0.2445 * b); u = av_clip_uint8( 0.6066 * r - 0.4322 * g - 0.1744 * b + 128); v = av_clip_uint8(-0.08435 * r - 0.3422 * g + 0.4266 * b + 128); y = y * 219 / 255 + 16; return y << 16 | u << 8 | v; } unsigned int vobsub_rgb_to_yuv(unsigned int rgb) { int r, g, b, y, u, v; r = rgb >> 16 & 0xff; g = rgb >> 8 & 0xff; b = rgb & 0xff; y = ( 0.299 * r + 0.587 * g + 0.114 * b) * 219 / 255 + 16.5; u = (-0.16874 * r - 0.33126 * g + 0.5 * b) * 224 / 255 + 128.5; v = ( 0.5 * r - 0.41869 * g - 0.08131 * b) * 224 / 255 + 128.5; return y << 16 | u << 8 | v; } static int vobsub_parse_delay(vobsub_t *vob, const char *line) { int h, m, s, ms; int forward = 1; if (*(line + 7) == '+') { forward = 1; line++; } else if (*(line + 7) == '-') { forward = -1; line++; } mp_msg(MSGT_SPUDEC, MSGL_V, "forward=%d", forward); h = atoi(line + 7); mp_msg(MSGT_VOBSUB, MSGL_V, "h=%d,", h); m = atoi(line + 10); mp_msg(MSGT_VOBSUB, MSGL_V, "m=%d,", m); s = atoi(line + 13); mp_msg(MSGT_VOBSUB, MSGL_V, "s=%d,", s); ms = atoi(line + 16); mp_msg(MSGT_VOBSUB, MSGL_V, "ms=%d", ms); vob->delay = (ms + 1000 * (s + 60 * (m + 60 * h))) * forward; return 0; } static int vobsub_set_lang(const char *line) { if (vobsub_id == -1) vobsub_id = atoi(line + 8); // 8 == strlen("langidx:") return 0; } static int vobsub_parse_one_line(vobsub_t *vob, rar_stream_t *fd, unsigned char **extradata, unsigned int *extradata_len) { ssize_t line_size; int res = -1; size_t line_reserve = 0; char *line = NULL; unsigned char *tmp; do { line_size = vobsub_getline(&line, &line_reserve, fd); if (line_size < 0 || line_size > 1000000 || *extradata_len+line_size > 10000000) { break; } tmp = realloc(*extradata, *extradata_len+line_size+1); if(!tmp) { mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR out of memory"); break; } *extradata = tmp; memcpy(*extradata+*extradata_len, line, line_size); *extradata_len += line_size; (*extradata)[*extradata_len] = 0; if (*line == 0 || *line == '\r' || *line == '\n' || *line == '#') continue; else if (strncmp("langidx:", line, 8) == 0) res = vobsub_set_lang(line); else if (strncmp("delay:", line, 6) == 0) res = vobsub_parse_delay(vob, line); else if (strncmp("id:", line, 3) == 0) res = vobsub_parse_id(vob, line + 3); else if (strncmp("org:", line, 4) == 0) res = vobsub_parse_origin(vob, line + 4); else if (strncmp("timestamp:", line, 10) == 0) res = vobsub_parse_timestamp(vob, line + 10); else { //mp_msg(MSGT_VOBSUB, MSGL_V, "vobsub: ignoring %s", line); /* size, palette, forced subs: on, and custom colors: ON, tridx are handled by spudec_parse_extradata in spudec.c */ continue; } if (res < 0) mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR in %s", line); break; } while (1); if (line) free(line); return res; } int vobsub_parse_ifo(void* this, const char *const name, unsigned int *palette, unsigned int *width, unsigned int *height, int force, int sid, char *langid) { vobsub_t *vob = this; int res = -1; rar_stream_t *fd = rar_open(name, "rb"); if (fd == NULL) { //if (force) //mp_msg(MSGT_VOBSUB, MSGL_WARN, "VobSub: Can't open IFO file\n"); } else { // parse IFO header unsigned char block[0x800]; const char *const ifo_magic = "DVDVIDEO-VTS"; if (rar_read(block, sizeof(block), 1, fd) != 1) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO header\n"); } else if (memcmp(block, ifo_magic, strlen(ifo_magic) + 1)) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Bad magic in IFO header\n"); else { unsigned long pgci_sector = block[0xcc] << 24 | block[0xcd] << 16 | block[0xce] << 8 | block[0xcf]; int standard = (block[0x200] & 0x30) >> 4; int resolution = (block[0x201] & 0x0c) >> 2; *height = standard ? 576 : 480; *width = 0; switch (resolution) { case 0x0: *width = 720; break; case 0x1: *width = 704; break; case 0x2: *width = 352; break; case 0x3: *width = 352; *height /= 2; break; default: mp_msg(MSGT_VOBSUB, MSGL_WARN, "Vobsub: Unknown resolution %d \n", resolution); } if (langid && 0 <= sid && sid < 32) { unsigned char *tmp = block + 0x256 + sid * 6 + 2; langid[0] = tmp[0]; langid[1] = tmp[1]; langid[2] = 0; } if (rar_seek(fd, pgci_sector * sizeof(block), SEEK_SET) || rar_read(block, sizeof(block), 1, fd) != 1) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO PGCI\n"); else { unsigned long idx; unsigned long pgc_offset = block[0xc] << 24 | block[0xd] << 16 | block[0xe] << 8 | block[0xf]; for (idx = 0; idx < 16; ++idx) { unsigned char *p = block + pgc_offset + 0xa4 + 4 * idx; palette[idx] = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; } if (vob) vob->have_palette = 1; res = 0; } } rar_close(fd); } return res; } void *vobsub_open(const char *const name, const char *const ifo, const int force, void** spu) { unsigned char *extradata = NULL; unsigned int extradata_len = 0; vobsub_t *vob = calloc(1, sizeof(vobsub_t)); if (spu) *spu = NULL; if (vobsubid == -2) vobsubid = vobsub_id; if (vob) { char *buf; buf = malloc(strlen(name) + 5); if (buf) { rar_stream_t *fd; mpeg_t *mpg; /* read in the info file */ if (!ifo) { strcpy(buf, name); strcat(buf, ".ifo"); vobsub_parse_ifo(vob, buf, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); } else vobsub_parse_ifo(vob, ifo, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); /* read in the index */ strcpy(buf, name); strcat(buf, ".idx"); fd = rar_open(buf, "rb"); if (fd == NULL) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open IDX file\n"); else { free(buf); free(vob); return NULL; } } else { while (vobsub_parse_one_line(vob, fd, &extradata, &extradata_len) >= 0) /* NOOP */ ; rar_close(fd); } if (spu) *spu = spudec_new_scaled(vob->palette, vob->orig_frame_width, vob->orig_frame_height, extradata, extradata_len); if (extradata) free(extradata); /* read the indexed mpeg_stream */ strcpy(buf, name); strcat(buf, ".sub"); mpg = mpeg_open(buf); if (mpg == NULL) { if (force) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open SUB file\n"); else { free(buf); free(vob); return NULL; } } else { long last_pts_diff = 0; while (!mpeg_eof(mpg)) { off_t pos = mpeg_tell(mpg); if (mpeg_run(mpg) < 0) { if (!mpeg_eof(mpg)) mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: mpeg_run error\n"); break; } if (mpg->packet_size) { if ((mpg->aid & 0xe0) == 0x20) { unsigned int sid = mpg->aid & 0x1f; if (vobsub_ensure_spu_stream(vob, sid) >= 0) { packet_queue_t *queue = vob->spu_streams + sid; /* get the packet to fill */ if (queue->packets_size == 0 && packet_queue_grow(queue) < 0) abort(); while (queue->current_index + 1 < queue->packets_size && queue->packets[queue->current_index + 1].filepos <= pos) ++queue->current_index; if (queue->current_index < queue->packets_size) { packet_t *pkt; if (queue->packets[queue->current_index].data) { /* insert a new packet and fix the PTS ! */ packet_queue_insert(queue); queue->packets[queue->current_index].pts100 = mpg->pts + last_pts_diff; } pkt = queue->packets + queue->current_index; if (pkt->pts100 != UINT_MAX) { if (queue->packets_size > 1) last_pts_diff = pkt->pts100 - mpg->pts; else pkt->pts100 = mpg->pts; if (mpg->merge && queue->current_index > 0) { packet_t *last = &queue->packets[queue->current_index - 1]; pkt->pts100 = last->pts100; } mpg->merge = 0; /* FIXME: should not use mpg_sub internal informations, make a copy */ pkt->data = mpg->packet; pkt->size = mpg->packet_size; mpg->packet = NULL; mpg->packet_reserve = 0; mpg->packet_size = 0; } } } else mp_msg(MSGT_VOBSUB, MSGL_WARN, "don't know what to do with subtitle #%u\n", sid); } } } vob->spu_streams_current = vob->spu_streams_size; while (vob->spu_streams_current-- > 0) { vob->spu_streams[vob->spu_streams_current].current_index = 0; if (vobsubid == vob->spu_streams_current || vob->spu_streams[vob->spu_streams_current].packets_size > 0) ++vob->spu_valid_streams_size; } mpeg_free(mpg); } free(buf); } } return vob; } void vobsub_close(void *this) { vobsub_t *vob = this; if (vob->spu_streams) { while (vob->spu_streams_size--) packet_queue_destroy(vob->spu_streams + vob->spu_streams_size); free(vob->spu_streams); } free(vob); } unsigned int vobsub_get_indexes_count(void *vobhandle) { vobsub_t *vob = vobhandle; return vob->spu_valid_streams_size; } char *vobsub_get_id(void *vobhandle, unsigned int index) { vobsub_t *vob = vobhandle; return (index < vob->spu_streams_size) ? vob->spu_streams[index].id : NULL; } int vobsub_get_id_by_index(void *vobhandle, unsigned int index) { vobsub_t *vob = vobhandle; int i, j; if (vob == NULL) return -1; for (i = 0, j = 0; i < vob->spu_streams_size; ++i) if (i == vobsubid || vob->spu_streams[i].packets_size > 0) { if (j == index) return i; ++j; } return -1; } int vobsub_get_index_by_id(void *vobhandle, int id) { vobsub_t *vob = vobhandle; int i, j; if (vob == NULL || id < 0 || id >= vob->spu_streams_size) return -1; if (id != vobsubid && !vob->spu_streams[id].packets_size) return -1; for (i = 0, j = 0; i < id; ++i) if (i == vobsubid || vob->spu_streams[i].packets_size > 0) ++j; return j; } int vobsub_set_from_lang(void *vobhandle, char const *lang) { int i; vobsub_t *vob= vobhandle; while (lang && strlen(lang) >= 2) { for (i = 0; i < vob->spu_streams_size; i++) if (vob->spu_streams[i].id) if ((strncmp(vob->spu_streams[i].id, lang, 2) == 0)) { vobsub_id = i; mp_msg(MSGT_VOBSUB, MSGL_INFO, "Selected VOBSUB language: %d language: %s\n", i, vob->spu_streams[i].id); return 0; } lang+=2;while (lang[0]==',' || lang[0]==' ') ++lang; } mp_msg(MSGT_VOBSUB, MSGL_WARN, "No matching VOBSUB language found!\n"); return -1; } /// make sure we seek to the first packet of packets having same pts values. static void vobsub_queue_reseek(packet_queue_t *queue, unsigned int pts100) { int reseek_count = 0; unsigned int lastpts = 0; if (queue->current_index > 0 && (queue->packets[queue->current_index].pts100 == UINT_MAX || queue->packets[queue->current_index].pts100 > pts100)) { // possible pts seek previous, try to check it. int i = 1; while (queue->current_index >= i && queue->packets[queue->current_index-i].pts100 == UINT_MAX) ++i; if (queue->current_index >= i && queue->packets[queue->current_index-i].pts100 > pts100) // pts seek previous confirmed, reseek from beginning queue->current_index = 0; } while (queue->current_index < queue->packets_size && queue->packets[queue->current_index].pts100 <= pts100) { lastpts = queue->packets[queue->current_index].pts100; ++queue->current_index; ++reseek_count; } while (reseek_count-- && --queue->current_index) { if (queue->packets[queue->current_index-1].pts100 != UINT_MAX && queue->packets[queue->current_index-1].pts100 != lastpts) break; } } int vobsub_get_packet(void *vobhandle, float pts, void** data, int* timestamp) { vobsub_t *vob = vobhandle; unsigned int pts100 = 90000 * pts; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { packet_queue_t *queue = vob->spu_streams + vobsub_id; vobsub_queue_reseek(queue, pts100); while (queue->current_index < queue->packets_size) { packet_t *pkt = queue->packets + queue->current_index; if (pkt->pts100 != UINT_MAX) if (pkt->pts100 <= pts100) { ++queue->current_index; *data = pkt->data; *timestamp = pkt->pts100; return pkt->size; } else break; else ++queue->current_index; } } return -1; } int vobsub_get_next_packet(void *vobhandle, void** data, int* timestamp) { vobsub_t *vob = vobhandle; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { packet_queue_t *queue = vob->spu_streams + vobsub_id; if (queue->current_index < queue->packets_size) { packet_t *pkt = queue->packets + queue->current_index; ++queue->current_index; *data = pkt->data; *timestamp = pkt->pts100; return pkt->size; } } return -1; } void vobsub_seek(void * vobhandle, float pts) { vobsub_t * vob = vobhandle; packet_queue_t * queue; int seek_pts100 = pts * 90000; if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { /* do not seek if we don't know the id */ if (vobsub_get_id(vob, vobsub_id) == NULL) return; queue = vob->spu_streams + vobsub_id; queue->current_index = 0; vobsub_queue_reseek(queue, seek_pts100); } } void vobsub_reset(void *vobhandle) { vobsub_t *vob = vobhandle; if (vob->spu_streams) { unsigned int n = vob->spu_streams_size; while (n-- > 0) vob->spu_streams[n].current_index = 0; } } #if 0 // R: no output needed /********************************************************************** * Vobsub output **********************************************************************/ typedef struct { FILE *fsub; FILE *fidx; unsigned int aid; } vobsub_out_t; static void create_idx(vobsub_out_t *me, const unsigned int *palette, unsigned int orig_width, unsigned int orig_height) { int i; fprintf(me->fidx, "# VobSub index file, v7 (do not modify this line!)\n" "#\n" "# Generated by %s\n" "# See <URL:http://www.mplayerhq.hu/> for more information about MPlayer\n" "# See <URL:http://wiki.multimedia.cx/index.php?title=VOBsub> for more information about Vobsub\n" "#\n" "size: %ux%u\n", mplayer_version, orig_width, orig_height); if (palette) { fputs("palette:", me->fidx); for (i = 0; i < 16; ++i) { const double y = palette[i] >> 16 & 0xff, u = (palette[i] >> 8 & 0xff) - 128.0, v = (palette[i] & 0xff) - 128.0; if (i) putc(',', me->fidx); fprintf(me->fidx, " %02x%02x%02x", av_clip_uint8(y + 1.4022 * u), av_clip_uint8(y - 0.3456 * u - 0.7145 * v),
ruediger/VobSub2SRT
db3b89ccd920435e14a906ac8b48fe43621c80a7
configure: Use -p instead of redirect. Thanks to Vinzenz!
diff --git a/configure b/configure index 5d0e400..64a50b4 100755 --- a/configure +++ b/configure @@ -1,5 +1,5 @@ #!/bin/sh # -*- mode:sh; coding:utf-8; -*- -mkdir build 2>/dev/null +mkdir -p build cd build && cmake "$@" ..
ruediger/VobSub2SRT
c1bfcd208a6a1fec10bec9b1e8d92db70084b815
Switch the brew formula to use the root Makefile instead of the CMake's build/Makefile
diff --git a/packaging/vobsub2srt.rb b/packaging/vobsub2srt.rb index b68f29d..e7539aa 100644 --- a/packaging/vobsub2srt.rb +++ b/packaging/vobsub2srt.rb @@ -1,18 +1,18 @@ # Homebrew Formula for VobSub2SRT # Usage: brew install https://github.com/ruediger/VobSub2SRT/raw/master/vobsub2srt.rb require 'formula' class Vobsub2srt < Formula head 'git://github.com/ruediger/VobSub2SRT.git', :using => :git homepage 'https://github.com/ruediger/VobSub2SRT' depends_on 'cmake' depends_on 'tesseract' depends_on 'ffmpeg' def install system "./configure #{std_cmake_parameters}" - system "cd build; make documentation; make install" + system "make install" end end
ruediger/VobSub2SRT
bf5cedba9cbd44d2cd3561173c7a17260dcad9fd
Ignore Mac spore
diff --git a/.gitignore b/.gitignore index 9b89d8d..8ccca03 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ build/ test/ /.dput.cf /doc/vobsub2srt.1.gz /ppa_config.cmake /version /TAGS +*DS_Store \ No newline at end of file
ruediger/VobSub2SRT
d2a5d433a3a876ec1189e90f8c6f8e3aac438579
Add building documentation to target all.
diff --git a/Makefile b/Makefile index 2d006af..7355eb8 100644 --- a/Makefile +++ b/Makefile @@ -1,34 +1,34 @@ .PHONY: all clean distclean install uninstall package dput documentation -all: build | documentation +all: build $(MAKE) -C build clean: build $(MAKE) -C build clean distclean: rm -rf build/ documentation: build $(MAKE) -C build documentation -install: build | documentation +install: build $(MAKE) -C build install uninstall: build $(MAKE) -C build uninstall -package: build | documentation +package: build $(MAKE) -C build package dput: @if [ -d build/Debian ]; then \ git dch --snapshot --since=465fa781b93e66cfb7080c55880969cb4631d584; \ $(MAKE) -C build dput; \ else \ echo 'Use ./configure -DENABLE_PPA=True to activate PPA support.'; \ fi build: @echo "Please run ./configure (with appropriate parameters)!" @exit 1 diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 3544e53..7cec3f0 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -1,30 +1,30 @@ find_program(GZIP gzip HINTS /bin /usr/bin /usr/local/bin) if(GZIP-NOTFOUND) message(WARNING "Gzip not found! Uncompressed manpage installed") - add_custom_target(documentation + add_custom_target(documentation ALL DEPENDS vobsub2srt.1) install(FILES vobsub2srt.1 DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) else() add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz COMMAND ${GZIP} -9 -c vobsub2srt.1 > ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz MAIN_DEPENDENCY vobsub2srt.1 WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") - add_custom_target(documentation + add_custom_target(documentation ALL DEPENDS ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz) install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) endif() option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of $BASH_COMPLETION_DIR if available.") if(BASH_COMPLETION_PATH) message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) endif()
ruediger/VobSub2SRT
a00f715a309366ed6aafe3b74ed2042b4ae75a9a
make documentation so that `brew install` doesn't fail
diff --git a/packaging/vobsub2srt.rb b/packaging/vobsub2srt.rb index 9181385..b68f29d 100644 --- a/packaging/vobsub2srt.rb +++ b/packaging/vobsub2srt.rb @@ -1,18 +1,18 @@ # Homebrew Formula for VobSub2SRT # Usage: brew install https://github.com/ruediger/VobSub2SRT/raw/master/vobsub2srt.rb require 'formula' class Vobsub2srt < Formula head 'git://github.com/ruediger/VobSub2SRT.git', :using => :git homepage 'https://github.com/ruediger/VobSub2SRT' depends_on 'cmake' depends_on 'tesseract' depends_on 'ffmpeg' def install system "./configure #{std_cmake_parameters}" - system "cd build; make install" + system "cd build; make documentation; make install" end end
ruediger/VobSub2SRT
fea824deef580427733f52dbce522110b7d00890
gitignore: TAGS file
diff --git a/.gitignore b/.gitignore index 13bac65..9b89d8d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ build/ test/ /.dput.cf /doc/vobsub2srt.1.gz /ppa_config.cmake /version +/TAGS
ruediger/VobSub2SRT
c10d80eb6ee49703b6cc17ff7bff75f296e79764
build: Warn against building statically linked binaries
diff --git a/CMakeLists.txt b/CMakeLists.txt index b3bdf26..8a76983 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,146 +1,147 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) + message(WARNING "Building a statically linked version of VobSub2SRT is NOT recommended. You might run into library dependency issues. Please check the README!") set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra -Wno-long-long") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif()
ruediger/VobSub2SRT
3d0cf9184c433f60e179cddabdbce96188e3bd68
build: No warning for the use of long long.
diff --git a/CMakeLists.txt b/CMakeLists.txt index f422a5f..b3bdf26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,146 +1,146 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") -set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra") +set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra -Wno-long-long") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif()
ruediger/VobSub2SRT
aa28b55fdf0fe67563305aa2c02c4a90377055eb
Use -pedantic instead of -pedantic-errors. Fixes #19
diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ad357c..f422a5f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,146 +1,146 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") -set(CMAKE_CXX_FLAGS "-ansi -pedantic-errors -Wall -Wextra") +set(CMAKE_CXX_FLAGS "-ansi -pedantic -Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif()
ruediger/VobSub2SRT
63867cc686bbb07fea7a2f9fba4bf4518fadc47d
Check if Tesseract Init failed.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index e4aeb6c..14dd080 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,233 +1,236 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); fwrite(image, 1, image_size, pgm); fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { cout << i << ": " << vobsub_get_id(vob, i) << '\n'; } return 0; } // Handle stream Ids and language char const *tess_lang = "eng"; // default english if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; - tess_base_api.Init(tesseract_data_path.c_str(), tess_lang); + if(tess_base_api.Init(tesseract_data_path.c_str(), tess_lang) == -1) { + cerr << "Failed to initialize tesseract (OCR).\n"; + return 1; + } if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
b0c6af1d74d0621f0cc0ce30520c5cd5fbf9e553
Use sizeof instead of constant.
diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ index 9f4768d..e4aeb6c 100644 --- a/src/vobsub2srt.c++ +++ b/src/vobsub2srt.c++ @@ -1,233 +1,233 @@ /* * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles * into .srt text subtitles by using OCR (tesseract). See README. * * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // MPlayer stuff #include "mp_msg.h" // mplayer message framework #include "vobsub.h" #include "spudec.h" // Tesseract OCR #include "tesseract/baseapi.h" #include <iostream> #include <string> #include <cstdio> using namespace std; #include "langcodes.h++" #include "cmd_options.h++" typedef void* vob_t; typedef void* spu_t; /** Converts time stamp in pts format to a string containing the time stamp for the srt format * * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. */ std::string pts2srt(unsigned pts) { unsigned ms = pts/90; unsigned const h = ms / (3600 * 1000); ms -= h * 3600 * 1000; unsigned const m = ms / (60 * 1000); ms -= m * 60 * 1000; unsigned const s = ms / 1000; ms %= 1000; - enum { length = 13 }; // HH:MM:SS:MSS\0 + enum { length = sizeof("HH:MM:SS,MSS") }; char buf[length]; snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); return std::string(buf); } /// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, unsigned char const *image, size_t image_size) { char buf[500]; snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); FILE *pgm = fopen(buf, "wb"); if(pgm) { fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); fwrite(image, 1, image_size, pgm); fclose(pgm); } } #ifdef CONFIG_TESSERACT_NAMESPACE using namespace tesseract; #endif #ifndef TESSERACT_DATA_PATH #define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake #endif int main(int argc, char **argv) { bool dump_images = false; bool verb = false; bool list_languages = false; std::string ifo_file; std::string subname; std::string lang; std::string blacklist; std::string tesseract_data_path = TESSERACT_DATA_PATH; { cmd_options opts; opts. add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). add_option("verbose", verb, "extra verbosity"). add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). add_option("lang", lang, "language to select", 'l'). add_option("langlist", list_languages, "list languages and exit"). add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); if(not opts.parse_cmd(argc, argv) or subname.empty()) { return 1; } } // Init the mplayer part verbose = verb; // mplayer verbose level mp_msg_init(); // Open the sub/idx subtitles spu_t spu; vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); if(not vob or vobsub_get_indexes_count(vob) == 0) { cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; return 1; } // list languages and exit if(list_languages) { cout << "Languages:\n"; for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { cout << i << ": " << vobsub_get_id(vob, i) << '\n'; } return 0; } // Handle stream Ids and language char const *tess_lang = "eng"; // default english if(not lang.empty()) { if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; } else { // convert two letter lang code into three letter lang code (required by tesseract) char const *const lang3 = iso639_1_to_639_3(lang.c_str()); if(lang3) { tess_lang = lang3; } } } else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream char const *const lang1 = vobsub_get_id(vob, vobsub_id); if(lang1) { char const *const lang3 = iso639_1_to_639_3(lang1); if(lang3) { tess_lang = lang3; } } } // Init Tesseract #ifdef CONFIG_TESSERACT_NAMESPACE TessBaseAPI tess_base_api; tess_base_api.Init(tesseract_data_path.c_str(), tess_lang); if(not blacklist.empty()) { tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #else TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params if(not blacklist.empty()) { TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); } #endif // Open srt output file string const srt_filename = subname + ".srt"; FILE *srtout = fopen(srt_filename.c_str(), "w"); if(not srtout) { perror("could not open .srt file"); return 1; } // Read subtitles and convert void *packet; int timestamp; // pts100 int len; unsigned last_start_pts = 0; unsigned sub_counter = 1; while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { if(timestamp >= 0) { spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); spudec_heartbeat(spu, timestamp); unsigned char const *image; size_t image_size; unsigned width, height, stride, start_pts, end_pts; spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); // skip this packet if it is another packet of a subtitle that // was decoded from multiple mpeg packets. if (start_pts == last_start_pts) { continue; } last_start_pts = start_pts; if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" << start_pts << ")\n"; } if(dump_images) { dump_pgm(subname, sub_counter, width, height, image, image_size); } #ifdef CONFIG_TESSERACT_NAMESPACE char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); #else char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); #endif if(not text) { cerr << "ERROR: OCR failed for " << sub_counter << '\n'; continue; } if(verb) { cout << sub_counter << " Text: " << text << endl; } fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); delete[]text; ++sub_counter; } } #ifdef CONFIG_TESSERACT_NAMESPACE tess_base_api.End(); #else TessBaseAPI::End(); #endif fclose(srtout); cout << "Wrote Subtitles to '" << srt_filename << "'\n"; vobsub_close(vob); spudec_free(spu); }
ruediger/VobSub2SRT
af6a7bfded1e6a7ce53385c655191a129373efe5
Build: Strip leading v from git versions.
diff --git a/CMakeLists.txt b/CMakeLists.txt index f650178..6ad357c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,145 +1,146 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic-errors -Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + string(REGEX REPLACE "^v" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") include(ppa_config.cmake OPTIONAL) set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif()
ruediger/VobSub2SRT
48bbafe1721bc1b87ba3372f128f73850b60ad40
PPA: Fixed building of documentation
diff --git a/.gitignore b/.gitignore index 006ea86..13bac65 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ build/ test/ /.dput.cf /doc/vobsub2srt.1.gz +/ppa_config.cmake +/version diff --git a/CMakeLists.txt b/CMakeLists.txt index f43a467..f650178 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,143 +1,145 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic-errors -Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") #### uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) - set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff4-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) + set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff5-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") + include(ppa_config.cmake OPTIONAL) + set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif() diff --git a/CMakeModules/UploadPPA.cmake b/CMakeModules/UploadPPA.cmake index e4b8b9a..d1a80cf 100644 --- a/CMakeModules/UploadPPA.cmake +++ b/CMakeModules/UploadPPA.cmake @@ -1,355 +1,355 @@ ## -*- mode:cmake; coding:utf-8; -*- # Copyright (c) 2010 Daniel Pfeifer <[email protected]> # Changes Copyright (c) 2011 2012 Rüdiger Sonderfeld <[email protected]> # # UploadPPA.cmake is free software. It comes without any warranty, # to the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://sam.zoy.org/wtfpl/COPYING for more details. # ## # Documentation # # This CMake module uploads a project to a PPA. It creates all the files # necessary (similar to CPack) and uses debuild(1) and dput(1) to create the # package and upload it to a PPA. A PPA is a Personal Package Archive and can # be used by Debian/Ubuntu or other apt/deb based distributions to install and # update packages from a remote repository. # Canonicals Launchpad (http://launchpad.net) is usually used to host PPAs. # See https://help.launchpad.net/Packaging/PPA for further information # about PPAs. # # UploadPPA.cmake uses similar settings to CPack and the CPack DEB Generator. # Additionally the following variables are used # # CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS to specify build dependencies # (cmake is added as default) # CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG should point to a file containing the # changelog in debian format. If not set it checks whether a file # debian/changelog exists in the source directory or creates a simply changelog # file. # CPACK_DEBIAN_UPDATE_CHANGELOG if set to True then UploadPPA.cmake adds a new # entry to the changelog with the current version number and distribution name # (lsb_release -c is used). This can be useful because debuild uses the latest # version number from the changelog and the version number set in # CPACK_PACKAGE_VERSION. If they mismatch the creation of the package fails. # ## # Check packages # # ./configure -DENABLE_PPA=On # make dput # cd build/Debian # dpkg-source -x vobsub2srt_1.0pre4-ppa1.dsc # cd vobsub2srt-1.0pre4/ # debuild -i -us -uc -sa -b # # Check the lintian warnings! # ## # TODO # I plan to add support for git dch (from git-buildpackage) to auto generate # the changelog. ## find_program(DEBUILD_EXECUTABLE debuild) find_program(DPUT_EXECUTABLE dput) if(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) return() endif(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) # Strip "-dirty" flag from package version. # It can be added by, e.g., git describe but it causes trouble with debuild etc. string(REPLACE "-dirty" "" CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}) message(STATUS "version: ${CPACK_PACKAGE_VERSION}") # DEBIAN/control # debian policy enforce lower case for package name # Package: (mandatory) IF(NOT CPACK_DEBIAN_PACKAGE_NAME) STRING(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_DEBIAN_PACKAGE_NAME) ENDIF(NOT CPACK_DEBIAN_PACKAGE_NAME) # Section: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_SECTION) SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") ENDIF(NOT CPACK_DEBIAN_PACKAGE_SECTION) # Priority: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") ENDIF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) if(NOT CPACK_DEBIAN_PACKAGE_MAINTAINER) set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT}) endif() if(NOT CPACK_PACKAGE_DESCRIPTION AND EXISTS ${CPACK_PACKAGE_DESCRIPTION_FILE}) file(STRINGS ${CPACK_PACKAGE_DESCRIPTION_FILE} DESC_LINES) foreach(LINE ${DESC_LINES}) set(deb_long_description "${deb_long_description} ${LINE}\n") endforeach(LINE ${DESC_LINES}) else() # add space before each line string(REPLACE "\n" "\n " deb_long_description " ${CPACK_PACKAGE_DESCRIPTION}") endif() if(PPA_DEBIAN_VERSION) set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}-${PPA_DEBIAN_VERSION}") else() message(WARNING "Variable PPA_DEBIAN_VERSION not set! Building 'native' package!") set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") endif() message(STATUS "Debian version: ${DEBIAN_PACKAGE_VERSION}") set(DEBIAN_SOURCE_DIR ${CMAKE_BINARY_DIR}/Debian/${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}) ############################################################################## # debian/control set(debian_control ${DEBIAN_SOURCE_DIR}/debian/control) list(APPEND CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS cmake) list(REMOVE_DUPLICATES CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) list(SORT CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) string(REPLACE ";" ", " build_depends "${CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS}") string(REPLACE ";" ", " bin_depends "${CPACK_DEBIAN_PACKAGE_DEPENDS}") file(WRITE ${debian_control} "Source: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Section: ${CPACK_DEBIAN_PACKAGE_SECTION}\n" "Priority: ${CPACK_DEBIAN_PACKAGE_PRIORITY}\n" "Maintainer: ${CPACK_DEBIAN_PACKAGE_MAINTAINER}\n" "Build-Depends: ${build_depends}\n" "Standards-Version: 3.9.3\n" "Homepage: ${CPACK_DEBIAN_PACKAGE_HOMEPAGE}\n" "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${bin_depends}, \${shlibs:Depends}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}\n" "${deb_long_description}" ) foreach(COMPONENT ${CPACK_COMPONENTS_ALL}) string(TOUPPER ${COMPONENT} UPPER_COMPONENT) set(DEPENDS "${CPACK_DEBIAN_PACKAGE_NAME}") foreach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) set(DEPENDS "${DEPENDS}, ${CPACK_DEBIAN_PACKAGE_NAME}-${DEP}") endforeach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) file(APPEND ${debian_control} "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}-${COMPONENT}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${DEPENDS}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}" ": ${CPACK_COMPONENT_${UPPER_COMPONENT}_DISPLAY_NAME}\n" "${deb_long_description}" " .\n" " ${CPACK_COMPONENT_${UPPER_COMPONENT}_DESCRIPTION}\n" ) endforeach(COMPONENT ${CPACK_COMPONENTS_ALL}) ############################################################################## # debian/copyright set(debian_copyright ${DEBIAN_SOURCE_DIR}/debian/copyright) configure_file(${CPACK_RESOURCE_FILE_LICENSE} ${debian_copyright} COPYONLY) ############################################################################## # debian/rules set(debian_rules ${DEBIAN_SOURCE_DIR}/debian/rules) file(WRITE ${debian_rules} "#!/usr/bin/make -f\n" "\n" "DEBUG = debug_build\n" "RELEASE = release_build\n" "GZIP = gzip\n" "CFLAGS =\n" "CPPFLAGS =\n" "CXXFLAGS =\n" "FFLAGS =\n" "LDFLAGS =\n" "\n" "configure-debug:\n" "\tcmake -E make_directory $(DEBUG)\n" "\tcd $(DEBUG); cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-debug\n" "\n" "configure-release:\n" "\tcmake -E make_directory $(RELEASE)\n" "\tcd $(RELEASE); cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-release\n" "\n" - "build: build-arch\n" # build-indep + "build: build-arch build-indep\n" # build-indep "\n" "build-arch: configure-release\n" # configure-debug # "\t$(MAKE) --no-print-directory -C $(DEBUG) preinstall\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) preinstall\n" "\ttouch build-arch\n" "\n" "build-indep: configure-release\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) documentation\n" "\ttouch build-indep\n" "\n" "binary: binary-arch binary-indep\n" "\n" "binary-arch: build-arch\n" # "\tcd $(DEBUG); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" "\t$(GZIP) -9 -c debian/changelog > debian/tmp/usr/share/doc/${CMAKE_PROJECT_NAME}/changelog.Debian.gz\n" "\tcmake -E make_directory debian/tmp/DEBIAN\n" "\tdpkg-shlibdeps debian/tmp/usr/bin/*\n" "\tdpkg-gencontrol -p${CPACK_DEBIAN_PACKAGE_NAME} -Pdebian/tmp\n" "\tdpkg --build debian/tmp ..\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "binary-indep: build-indep\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "clean:\n" "\tcmake -E remove_directory $(DEBUG)\n" "\tcmake -E remove_directory $(RELEASE)\n" "\tcmake -E remove configure-debug configure-release build-arch build-indep\n" "\n" ".PHONY: binary binary-arch binary-indep clean\n" ) execute_process(COMMAND chmod +x ${debian_rules}) ############################################################################## # debian/compat file(WRITE ${DEBIAN_SOURCE_DIR}/debian/compat "7") ############################################################################## # debian/source/format file(WRITE ${DEBIAN_SOURCE_DIR}/debian/source/format "3.0 (quilt)") ############################################################################## # debian/changelog set(debian_changelog ${DEBIAN_SOURCE_DIR}/debian/changelog) if(NOT CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG) set(CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG ${CMAKE_SOURCE_DIR}/debian/changelog) endif() # TODO add support for git dch (git-buildpackage) if(EXISTS ${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG}) configure_file(${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG} ${debian_changelog} COPYONLY) if(CPACK_DEBIAN_UPDATE_CHANGELOG) file(READ ${debian_changelog} debian_changelog_content) execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package created with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n\n" ) file(APPEND ${debian_changelog} ${debian_changelog_content}) endif() else() execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package built with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n" ) endif() ########################################################################## # .orig.tar.gz #execute_process(COMMAND date +%y%m%d # OUTPUT_VARIABLE day_suffix # OUTPUT_STRIP_TRAILING_WHITESPACE # ) set(CPACK_SOURCE_IGNORE_FILES "/build/" "/debian/" "/.git/" ".gitignore" ".dput.cf" "/test/" "/packaging/" "*~") set(package_file_name "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}") file(WRITE "${CMAKE_BINARY_DIR}/Debian/cpack.cmake" "set(CPACK_GENERATOR TBZ2)\n" "set(CPACK_PACKAGE_NAME \"${CPACK_DEBIAN_PACKAGE_NAME}\")\n" "set(CPACK_PACKAGE_VERSION \"${CPACK_PACKAGE_VERSION}\")\n" "set(CPACK_PACKAGE_FILE_NAME \"${package_file_name}.orig\")\n" "set(CPACK_PACKAGE_DESCRIPTION \"${CPACK_PACKAGE_NAME} Source\")\n" "set(CPACK_IGNORE_FILES \"${CPACK_SOURCE_IGNORE_FILES}\")\n" "set(CPACK_INSTALLED_DIRECTORIES \"${CPACK_SOURCE_INSTALLED_DIRECTORIES}\")\n" ) set(orig_file "${DEBIAN_SOURCE_DIR}/${package_file_name}.orig.tar.bz2") add_custom_command(OUTPUT "${orig_file}" COMMAND cpack --config ./cpack.cmake WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/Debian" ) ############################################################################## # debuild -S set(DEB_SOURCE_CHANGES ${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}_source.changes ) add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} COMMAND ${DEBUILD_EXECUTABLE} -S WORKING_DIRECTORY ${DEBIAN_SOURCE_DIR} DEPENDS "${orig_file}" ) ############################################################################## # dput ppa:your-lp-id/ppa <source.changes> -add_custom_target(dput ${DPUT_EXECUTABLE} ${DPUT_HOST} ${DEB_SOURCE_CHANGES} - DEPENDS ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debian - ) + add_custom_target(dput ${DPUT_EXECUTABLE} ${DPUT_HOST} ${DEB_SOURCE_CHANGES} + DEPENDS ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debian + )
ruediger/VobSub2SRT
1404d47b4091547627909b2ea2996048f513da52
build: install targets depends on documentation target
diff --git a/Makefile b/Makefile index afdbb47..2d006af 100644 --- a/Makefile +++ b/Makefile @@ -1,34 +1,34 @@ .PHONY: all clean distclean install uninstall package dput documentation all: build | documentation $(MAKE) -C build clean: build $(MAKE) -C build clean distclean: rm -rf build/ documentation: build $(MAKE) -C build documentation -install: build +install: build | documentation $(MAKE) -C build install uninstall: build $(MAKE) -C build uninstall package: build | documentation $(MAKE) -C build package dput: @if [ -d build/Debian ]; then \ git dch --snapshot --since=465fa781b93e66cfb7080c55880969cb4631d584; \ $(MAKE) -C build dput; \ else \ echo 'Use ./configure -DENABLE_PPA=True to activate PPA support.'; \ fi build: @echo "Please run ./configure (with appropriate parameters)!" @exit 1
ruediger/VobSub2SRT
75c60306db6c036e6fd6410a2d71210e9fa4fbfa
build/install: Handle uninstall in cmake. Fixes #17
diff --git a/CMakeLists.txt b/CMakeLists.txt index 69367f1..f43a467 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,134 +1,143 @@ project(vobsub2srt) cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE) set( CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() message(STATUS "Source: ${CMAKE_SOURCE_DIR}") message(STATUS "Binary: ${CMAKE_BINARY_DIR}") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") endif() if(BUILD_STATIC) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) endif() set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") include(CheckIncludeFile) include(CheckCCompilerFlag) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXCompilerFlag) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) set(CMAKE_C_FLAGS "-std=gnu99") set(CMAKE_CXX_FLAGS "-ansi -pedantic-errors -Wall -Wextra") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) # TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type find_package(Libavutil) find_package(Threads) find_package(Tesseract) add_subdirectory(mplayer) add_subdirectory(src) add_subdirectory(doc) #### Detect Version if(NOT VOBSUB2SRT_VERSION) if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") if(NOT GIT_FOUND) find_package(Git QUIET) endif() if(GIT_FOUND) execute_process( COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" OUTPUT_VARIABLE VOBSUB2SRT_VERSION RESULT_VARIABLE EXECUTE_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) endif() endif() endif() if(NOT VOBSUB2SRT_VERSION) set(VOBSUB2SRT_VERSION "unknown-dirty") endif() message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") +#### uninstall target +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" + IMMEDIATE @ONLY) + +add_custom_target(uninstall + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) + #### Package Generation execute_process ( COMMAND /usr/bin/dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE RESULT_VARIABLE EXECUTE_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(EXECUTE_RESULT) message(STATUS "dpkg not found: No package generation.") else() message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") set(CPACK_STRIP_FILES TRUE) set(CPACK_DEBIAN_PACKAGE_SECTION "video") set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff4-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) # set(CPACK_DEBIAN_GIT_DCH TRUE) set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) set(PPA_DEBIAN_VERSION "ppa1") set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") include(CPack) if(ENABLE_PPA) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system include(UploadPPA) endif() endif() diff --git a/CMakeModules/cmake_uninstall.cmake.in b/CMakeModules/cmake_uninstall.cmake.in new file mode 100644 index 0000000..ecfa84a --- /dev/null +++ b/CMakeModules/cmake_uninstall.cmake.in @@ -0,0 +1,41 @@ +if (NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + message(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") +endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + +cmake_policy(SET CMP0007 OLD) # ignore empty list elements + +file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +string(REGEX REPLACE "\n" ";" files "${files}") +list(REVERSE files) +foreach (file ${files}) + message(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") + if (EXISTS "$ENV{DESTDIR}${file}") + execute_process( + COMMAND @CMAKE_COMMAND@ -E remove "$ENV{DESTDIR}${file}" + OUTPUT_VARIABLE rm_out + RESULT_VARIABLE rm_retval + ) + if(NOT ${rm_retval} EQUAL 0) + message(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") + endif (NOT ${rm_retval} EQUAL 0) + else (EXISTS "$ENV{DESTDIR}${file}") + message(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") + endif (EXISTS "$ENV{DESTDIR}${file}") +endforeach(file) + +set(INSTALL_SHARE_DOC @INSTALL_SHARE_DOC@) +if(INSTALL_SHARE_DOC) # prevent empty variable! + message(STATUS "Uninstalling \"$ENV{DESTDIR}${INSTALL_SHARE_DOC}\"") + # Call rmdir instead of cmake -E remove_directory to avoid removing non-empty + # directories in case install_share_doc points to a common directory + execute_process( + COMMAND rmdir -- "$ENV{DESTDIR}${INSTALL_SHARE_DOC}" + OUTPUT_VARIABLE rm_out + RESULT_VARIABLE rm_retval + ) + if(NOT rm_retval EQUAL 0) + message(FATAL_ERROR "Removing directory $ENV{DESTDIR}${INSTALL_SHARE_DOC}") + endif() +else() + message(WARNING "No share/doc path found!") +endif() diff --git a/Makefile b/Makefile index 5157b0b..afdbb47 100644 --- a/Makefile +++ b/Makefile @@ -1,39 +1,34 @@ .PHONY: all clean distclean install uninstall package dput documentation all: build | documentation $(MAKE) -C build clean: build $(MAKE) -C build clean distclean: rm -rf build/ documentation: build $(MAKE) -C build documentation install: build $(MAKE) -C build install uninstall: build - @if [ -f build/install_manifest.txt ]; then \ - echo 'Uninstalling' ; \ - xargs rm < build/install_manifest.txt ; \ - else \ - echo 'VobSub2Srt does not seem to be installed.'; \ - fi + $(MAKE) -C build uninstall package: build | documentation $(MAKE) -C build package dput: @if [ -d build/Debian ]; then \ git dch --snapshot --since=465fa781b93e66cfb7080c55880969cb4631d584; \ $(MAKE) -C build dput; \ else \ echo 'Use ./configure -DENABLE_PPA=True to activate PPA support.'; \ fi build: @echo "Please run ./configure (with appropriate parameters)!" @exit 1
ruediger/VobSub2SRT
102877663fbea7a1a299f64e736c561e60ab244c
Create vobsub2srt.1.gz in build directory.
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 372f20c..3544e53 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -1,30 +1,30 @@ find_program(GZIP gzip HINTS /bin /usr/bin /usr/local/bin) if(GZIP-NOTFOUND) message(WARNING "Gzip not found! Uncompressed manpage installed") add_custom_target(documentation DEPENDS vobsub2srt.1) install(FILES vobsub2srt.1 DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) else() add_custom_command( - OUTPUT vobsub2srt.1.gz - COMMAND ${GZIP} -9 -c vobsub2srt.1 > vobsub2srt.1.gz + OUTPUT ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz + COMMAND ${GZIP} -9 -c vobsub2srt.1 > ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz MAIN_DEPENDENCY vobsub2srt.1 WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") add_custom_target(documentation - DEPENDS vobsub2srt.1.gz) + DEPENDS ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz) - install(FILES vobsub2srt.1.gz DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) + install(FILES ${CMAKE_BINARY_DIR}/doc/vobsub2srt.1.gz DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) endif() option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of $BASH_COMPLETION_DIR if available.") if(BASH_COMPLETION_PATH) message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) endif()
ruediger/VobSub2SRT
16f64202ecc58f803104274fee1394c932306a10
build: made documentation an ordered prerequisite of all and package.
diff --git a/Makefile b/Makefile index 6cdf649..5157b0b 100644 --- a/Makefile +++ b/Makefile @@ -1,39 +1,39 @@ .PHONY: all clean distclean install uninstall package dput documentation -all: build +all: build | documentation $(MAKE) -C build clean: build $(MAKE) -C build clean distclean: rm -rf build/ documentation: build $(MAKE) -C build documentation install: build $(MAKE) -C build install uninstall: build @if [ -f build/install_manifest.txt ]; then \ echo 'Uninstalling' ; \ xargs rm < build/install_manifest.txt ; \ else \ echo 'VobSub2Srt does not seem to be installed.'; \ fi -package: build +package: build | documentation $(MAKE) -C build package dput: @if [ -d build/Debian ]; then \ git dch --snapshot --since=465fa781b93e66cfb7080c55880969cb4631d584; \ $(MAKE) -C build dput; \ else \ echo 'Use ./configure -DENABLE_PPA=True to activate PPA support.'; \ fi build: @echo "Please run ./configure (with appropriate parameters)!" @exit 1
ruediger/VobSub2SRT
f12a6b5674091bc43e6909fee94d5fe93f90f0fe
UploadPPA: added comment on how to check the package before uploading
diff --git a/CMakeModules/UploadPPA.cmake b/CMakeModules/UploadPPA.cmake index e0fad4c..e4b8b9a 100644 --- a/CMakeModules/UploadPPA.cmake +++ b/CMakeModules/UploadPPA.cmake @@ -1,343 +1,355 @@ ## -*- mode:cmake; coding:utf-8; -*- # Copyright (c) 2010 Daniel Pfeifer <[email protected]> # Changes Copyright (c) 2011 2012 Rüdiger Sonderfeld <[email protected]> # # UploadPPA.cmake is free software. It comes without any warranty, # to the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://sam.zoy.org/wtfpl/COPYING for more details. # ## # Documentation # # This CMake module uploads a project to a PPA. It creates all the files # necessary (similar to CPack) and uses debuild(1) and dput(1) to create the # package and upload it to a PPA. A PPA is a Personal Package Archive and can # be used by Debian/Ubuntu or other apt/deb based distributions to install and # update packages from a remote repository. # Canonicals Launchpad (http://launchpad.net) is usually used to host PPAs. # See https://help.launchpad.net/Packaging/PPA for further information # about PPAs. # # UploadPPA.cmake uses similar settings to CPack and the CPack DEB Generator. # Additionally the following variables are used # # CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS to specify build dependencies # (cmake is added as default) # CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG should point to a file containing the # changelog in debian format. If not set it checks whether a file # debian/changelog exists in the source directory or creates a simply changelog # file. # CPACK_DEBIAN_UPDATE_CHANGELOG if set to True then UploadPPA.cmake adds a new # entry to the changelog with the current version number and distribution name # (lsb_release -c is used). This can be useful because debuild uses the latest # version number from the changelog and the version number set in # CPACK_PACKAGE_VERSION. If they mismatch the creation of the package fails. # ## +# Check packages +# +# ./configure -DENABLE_PPA=On +# make dput +# cd build/Debian +# dpkg-source -x vobsub2srt_1.0pre4-ppa1.dsc +# cd vobsub2srt-1.0pre4/ +# debuild -i -us -uc -sa -b +# +# Check the lintian warnings! +# +## # TODO # I plan to add support for git dch (from git-buildpackage) to auto generate # the changelog. ## find_program(DEBUILD_EXECUTABLE debuild) find_program(DPUT_EXECUTABLE dput) if(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) return() endif(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) # Strip "-dirty" flag from package version. # It can be added by, e.g., git describe but it causes trouble with debuild etc. string(REPLACE "-dirty" "" CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}) message(STATUS "version: ${CPACK_PACKAGE_VERSION}") # DEBIAN/control # debian policy enforce lower case for package name # Package: (mandatory) IF(NOT CPACK_DEBIAN_PACKAGE_NAME) STRING(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_DEBIAN_PACKAGE_NAME) ENDIF(NOT CPACK_DEBIAN_PACKAGE_NAME) # Section: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_SECTION) SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") ENDIF(NOT CPACK_DEBIAN_PACKAGE_SECTION) # Priority: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") ENDIF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) if(NOT CPACK_DEBIAN_PACKAGE_MAINTAINER) set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT}) endif() if(NOT CPACK_PACKAGE_DESCRIPTION AND EXISTS ${CPACK_PACKAGE_DESCRIPTION_FILE}) file(STRINGS ${CPACK_PACKAGE_DESCRIPTION_FILE} DESC_LINES) foreach(LINE ${DESC_LINES}) set(deb_long_description "${deb_long_description} ${LINE}\n") endforeach(LINE ${DESC_LINES}) else() # add space before each line string(REPLACE "\n" "\n " deb_long_description " ${CPACK_PACKAGE_DESCRIPTION}") endif() if(PPA_DEBIAN_VERSION) set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}-${PPA_DEBIAN_VERSION}") else() message(WARNING "Variable PPA_DEBIAN_VERSION not set! Building 'native' package!") set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") endif() message(STATUS "Debian version: ${DEBIAN_PACKAGE_VERSION}") set(DEBIAN_SOURCE_DIR ${CMAKE_BINARY_DIR}/Debian/${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}) ############################################################################## # debian/control set(debian_control ${DEBIAN_SOURCE_DIR}/debian/control) list(APPEND CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS cmake) list(REMOVE_DUPLICATES CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) list(SORT CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) string(REPLACE ";" ", " build_depends "${CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS}") string(REPLACE ";" ", " bin_depends "${CPACK_DEBIAN_PACKAGE_DEPENDS}") file(WRITE ${debian_control} "Source: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Section: ${CPACK_DEBIAN_PACKAGE_SECTION}\n" "Priority: ${CPACK_DEBIAN_PACKAGE_PRIORITY}\n" "Maintainer: ${CPACK_DEBIAN_PACKAGE_MAINTAINER}\n" "Build-Depends: ${build_depends}\n" "Standards-Version: 3.9.3\n" "Homepage: ${CPACK_DEBIAN_PACKAGE_HOMEPAGE}\n" "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${bin_depends}, \${shlibs:Depends}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}\n" "${deb_long_description}" ) foreach(COMPONENT ${CPACK_COMPONENTS_ALL}) string(TOUPPER ${COMPONENT} UPPER_COMPONENT) set(DEPENDS "${CPACK_DEBIAN_PACKAGE_NAME}") foreach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) set(DEPENDS "${DEPENDS}, ${CPACK_DEBIAN_PACKAGE_NAME}-${DEP}") endforeach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) file(APPEND ${debian_control} "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}-${COMPONENT}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${DEPENDS}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}" ": ${CPACK_COMPONENT_${UPPER_COMPONENT}_DISPLAY_NAME}\n" "${deb_long_description}" " .\n" " ${CPACK_COMPONENT_${UPPER_COMPONENT}_DESCRIPTION}\n" ) endforeach(COMPONENT ${CPACK_COMPONENTS_ALL}) ############################################################################## # debian/copyright set(debian_copyright ${DEBIAN_SOURCE_DIR}/debian/copyright) configure_file(${CPACK_RESOURCE_FILE_LICENSE} ${debian_copyright} COPYONLY) ############################################################################## # debian/rules set(debian_rules ${DEBIAN_SOURCE_DIR}/debian/rules) file(WRITE ${debian_rules} "#!/usr/bin/make -f\n" "\n" "DEBUG = debug_build\n" "RELEASE = release_build\n" "GZIP = gzip\n" "CFLAGS =\n" "CPPFLAGS =\n" "CXXFLAGS =\n" "FFLAGS =\n" "LDFLAGS =\n" "\n" "configure-debug:\n" "\tcmake -E make_directory $(DEBUG)\n" "\tcd $(DEBUG); cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-debug\n" "\n" "configure-release:\n" "\tcmake -E make_directory $(RELEASE)\n" "\tcd $(RELEASE); cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-release\n" "\n" "build: build-arch\n" # build-indep "\n" "build-arch: configure-release\n" # configure-debug # "\t$(MAKE) --no-print-directory -C $(DEBUG) preinstall\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) preinstall\n" "\ttouch build-arch\n" "\n" "build-indep: configure-release\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) documentation\n" "\ttouch build-indep\n" "\n" "binary: binary-arch binary-indep\n" "\n" "binary-arch: build-arch\n" # "\tcd $(DEBUG); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" "\t$(GZIP) -9 -c debian/changelog > debian/tmp/usr/share/doc/${CMAKE_PROJECT_NAME}/changelog.Debian.gz\n" "\tcmake -E make_directory debian/tmp/DEBIAN\n" "\tdpkg-shlibdeps debian/tmp/usr/bin/*\n" "\tdpkg-gencontrol -p${CPACK_DEBIAN_PACKAGE_NAME} -Pdebian/tmp\n" "\tdpkg --build debian/tmp ..\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "binary-indep: build-indep\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "clean:\n" "\tcmake -E remove_directory $(DEBUG)\n" "\tcmake -E remove_directory $(RELEASE)\n" "\tcmake -E remove configure-debug configure-release build-arch build-indep\n" "\n" ".PHONY: binary binary-arch binary-indep clean\n" ) execute_process(COMMAND chmod +x ${debian_rules}) ############################################################################## # debian/compat file(WRITE ${DEBIAN_SOURCE_DIR}/debian/compat "7") ############################################################################## # debian/source/format file(WRITE ${DEBIAN_SOURCE_DIR}/debian/source/format "3.0 (quilt)") ############################################################################## # debian/changelog set(debian_changelog ${DEBIAN_SOURCE_DIR}/debian/changelog) if(NOT CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG) set(CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG ${CMAKE_SOURCE_DIR}/debian/changelog) endif() # TODO add support for git dch (git-buildpackage) if(EXISTS ${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG}) configure_file(${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG} ${debian_changelog} COPYONLY) if(CPACK_DEBIAN_UPDATE_CHANGELOG) file(READ ${debian_changelog} debian_changelog_content) execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package created with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n\n" ) file(APPEND ${debian_changelog} ${debian_changelog_content}) endif() else() execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package built with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n" ) endif() ########################################################################## # .orig.tar.gz #execute_process(COMMAND date +%y%m%d # OUTPUT_VARIABLE day_suffix # OUTPUT_STRIP_TRAILING_WHITESPACE # ) set(CPACK_SOURCE_IGNORE_FILES "/build/" "/debian/" "/.git/" ".gitignore" ".dput.cf" "/test/" "/packaging/" "*~") set(package_file_name "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}") file(WRITE "${CMAKE_BINARY_DIR}/Debian/cpack.cmake" "set(CPACK_GENERATOR TBZ2)\n" "set(CPACK_PACKAGE_NAME \"${CPACK_DEBIAN_PACKAGE_NAME}\")\n" "set(CPACK_PACKAGE_VERSION \"${CPACK_PACKAGE_VERSION}\")\n" "set(CPACK_PACKAGE_FILE_NAME \"${package_file_name}.orig\")\n" "set(CPACK_PACKAGE_DESCRIPTION \"${CPACK_PACKAGE_NAME} Source\")\n" "set(CPACK_IGNORE_FILES \"${CPACK_SOURCE_IGNORE_FILES}\")\n" "set(CPACK_INSTALLED_DIRECTORIES \"${CPACK_SOURCE_INSTALLED_DIRECTORIES}\")\n" ) set(orig_file "${DEBIAN_SOURCE_DIR}/${package_file_name}.orig.tar.bz2") add_custom_command(OUTPUT "${orig_file}" COMMAND cpack --config ./cpack.cmake WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/Debian" ) ############################################################################## # debuild -S set(DEB_SOURCE_CHANGES ${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}_source.changes ) add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} COMMAND ${DEBUILD_EXECUTABLE} -S WORKING_DIRECTORY ${DEBIAN_SOURCE_DIR} DEPENDS "${orig_file}" ) ############################################################################## # dput ppa:your-lp-id/ppa <source.changes> add_custom_target(dput ${DPUT_EXECUTABLE} ${DPUT_HOST} ${DEB_SOURCE_CHANGES} DEPENDS ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debian )
ruediger/VobSub2SRT
74b2409130a3cbfcd00b4ae37c5cf9b9c5acde18
UploadPPA: create changelog.Debian.gz
diff --git a/CMakeModules/UploadPPA.cmake b/CMakeModules/UploadPPA.cmake index 83e5564..e0fad4c 100644 --- a/CMakeModules/UploadPPA.cmake +++ b/CMakeModules/UploadPPA.cmake @@ -1,341 +1,343 @@ ## -*- mode:cmake; coding:utf-8; -*- # Copyright (c) 2010 Daniel Pfeifer <[email protected]> # Changes Copyright (c) 2011 2012 Rüdiger Sonderfeld <[email protected]> # # UploadPPA.cmake is free software. It comes without any warranty, # to the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://sam.zoy.org/wtfpl/COPYING for more details. # ## # Documentation # # This CMake module uploads a project to a PPA. It creates all the files # necessary (similar to CPack) and uses debuild(1) and dput(1) to create the # package and upload it to a PPA. A PPA is a Personal Package Archive and can # be used by Debian/Ubuntu or other apt/deb based distributions to install and # update packages from a remote repository. # Canonicals Launchpad (http://launchpad.net) is usually used to host PPAs. # See https://help.launchpad.net/Packaging/PPA for further information # about PPAs. # # UploadPPA.cmake uses similar settings to CPack and the CPack DEB Generator. # Additionally the following variables are used # # CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS to specify build dependencies # (cmake is added as default) # CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG should point to a file containing the # changelog in debian format. If not set it checks whether a file # debian/changelog exists in the source directory or creates a simply changelog # file. # CPACK_DEBIAN_UPDATE_CHANGELOG if set to True then UploadPPA.cmake adds a new # entry to the changelog with the current version number and distribution name # (lsb_release -c is used). This can be useful because debuild uses the latest # version number from the changelog and the version number set in # CPACK_PACKAGE_VERSION. If they mismatch the creation of the package fails. # ## # TODO # I plan to add support for git dch (from git-buildpackage) to auto generate # the changelog. ## find_program(DEBUILD_EXECUTABLE debuild) find_program(DPUT_EXECUTABLE dput) if(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) return() endif(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) # Strip "-dirty" flag from package version. # It can be added by, e.g., git describe but it causes trouble with debuild etc. string(REPLACE "-dirty" "" CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}) message(STATUS "version: ${CPACK_PACKAGE_VERSION}") # DEBIAN/control # debian policy enforce lower case for package name # Package: (mandatory) IF(NOT CPACK_DEBIAN_PACKAGE_NAME) STRING(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_DEBIAN_PACKAGE_NAME) ENDIF(NOT CPACK_DEBIAN_PACKAGE_NAME) # Section: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_SECTION) SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") ENDIF(NOT CPACK_DEBIAN_PACKAGE_SECTION) # Priority: (recommended) IF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") ENDIF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) if(NOT CPACK_DEBIAN_PACKAGE_MAINTAINER) set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT}) endif() if(NOT CPACK_PACKAGE_DESCRIPTION AND EXISTS ${CPACK_PACKAGE_DESCRIPTION_FILE}) file(STRINGS ${CPACK_PACKAGE_DESCRIPTION_FILE} DESC_LINES) foreach(LINE ${DESC_LINES}) set(deb_long_description "${deb_long_description} ${LINE}\n") endforeach(LINE ${DESC_LINES}) else() # add space before each line string(REPLACE "\n" "\n " deb_long_description " ${CPACK_PACKAGE_DESCRIPTION}") endif() if(PPA_DEBIAN_VERSION) set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}-${PPA_DEBIAN_VERSION}") else() message(WARNING "Variable PPA_DEBIAN_VERSION not set! Building 'native' package!") set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") endif() message(STATUS "Debian version: ${DEBIAN_PACKAGE_VERSION}") set(DEBIAN_SOURCE_DIR ${CMAKE_BINARY_DIR}/Debian/${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}) ############################################################################## # debian/control set(debian_control ${DEBIAN_SOURCE_DIR}/debian/control) list(APPEND CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS cmake) list(REMOVE_DUPLICATES CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) list(SORT CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) string(REPLACE ";" ", " build_depends "${CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS}") string(REPLACE ";" ", " bin_depends "${CPACK_DEBIAN_PACKAGE_DEPENDS}") file(WRITE ${debian_control} "Source: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Section: ${CPACK_DEBIAN_PACKAGE_SECTION}\n" "Priority: ${CPACK_DEBIAN_PACKAGE_PRIORITY}\n" "Maintainer: ${CPACK_DEBIAN_PACKAGE_MAINTAINER}\n" "Build-Depends: ${build_depends}\n" "Standards-Version: 3.9.3\n" "Homepage: ${CPACK_DEBIAN_PACKAGE_HOMEPAGE}\n" "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${bin_depends}, \${shlibs:Depends}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}\n" "${deb_long_description}" ) foreach(COMPONENT ${CPACK_COMPONENTS_ALL}) string(TOUPPER ${COMPONENT} UPPER_COMPONENT) set(DEPENDS "${CPACK_DEBIAN_PACKAGE_NAME}") foreach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) set(DEPENDS "${DEPENDS}, ${CPACK_DEBIAN_PACKAGE_NAME}-${DEP}") endforeach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) file(APPEND ${debian_control} "\n" "Package: ${CPACK_DEBIAN_PACKAGE_NAME}-${COMPONENT}\n" "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" "Depends: ${DEPENDS}\n" "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}" ": ${CPACK_COMPONENT_${UPPER_COMPONENT}_DISPLAY_NAME}\n" "${deb_long_description}" " .\n" " ${CPACK_COMPONENT_${UPPER_COMPONENT}_DESCRIPTION}\n" ) endforeach(COMPONENT ${CPACK_COMPONENTS_ALL}) ############################################################################## # debian/copyright set(debian_copyright ${DEBIAN_SOURCE_DIR}/debian/copyright) configure_file(${CPACK_RESOURCE_FILE_LICENSE} ${debian_copyright} COPYONLY) ############################################################################## # debian/rules set(debian_rules ${DEBIAN_SOURCE_DIR}/debian/rules) file(WRITE ${debian_rules} "#!/usr/bin/make -f\n" "\n" "DEBUG = debug_build\n" "RELEASE = release_build\n" + "GZIP = gzip\n" "CFLAGS =\n" "CPPFLAGS =\n" "CXXFLAGS =\n" "FFLAGS =\n" "LDFLAGS =\n" "\n" "configure-debug:\n" "\tcmake -E make_directory $(DEBUG)\n" "\tcd $(DEBUG); cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-debug\n" "\n" "configure-release:\n" "\tcmake -E make_directory $(RELEASE)\n" "\tcd $(RELEASE); cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" "\ttouch configure-release\n" "\n" "build: build-arch\n" # build-indep "\n" "build-arch: configure-release\n" # configure-debug # "\t$(MAKE) --no-print-directory -C $(DEBUG) preinstall\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) preinstall\n" "\ttouch build-arch\n" "\n" "build-indep: configure-release\n" "\t$(MAKE) --no-print-directory -C $(RELEASE) documentation\n" "\ttouch build-indep\n" "\n" "binary: binary-arch binary-indep\n" "\n" "binary-arch: build-arch\n" # "\tcd $(DEBUG); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" + "\t$(GZIP) -9 -c debian/changelog > debian/tmp/usr/share/doc/${CMAKE_PROJECT_NAME}/changelog.Debian.gz\n" "\tcmake -E make_directory debian/tmp/DEBIAN\n" "\tdpkg-shlibdeps debian/tmp/usr/bin/*\n" "\tdpkg-gencontrol -p${CPACK_DEBIAN_PACKAGE_NAME} -Pdebian/tmp\n" "\tdpkg --build debian/tmp ..\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "binary-indep: build-indep\n" ) foreach(component ${CPACK_COMPONENTS_ALL}) string(TOUPPER "${component}" COMPONENT) if(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) set(path debian/${component}) file(APPEND ${debian_rules} # "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" "\tcmake -E make_directory ${path}/DEBIAN\n" "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" "\tdpkg --build ${path} ..\n" ) endif(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) endforeach(component) file(APPEND ${debian_rules} "\n" "clean:\n" "\tcmake -E remove_directory $(DEBUG)\n" "\tcmake -E remove_directory $(RELEASE)\n" "\tcmake -E remove configure-debug configure-release build-arch build-indep\n" "\n" ".PHONY: binary binary-arch binary-indep clean\n" ) execute_process(COMMAND chmod +x ${debian_rules}) ############################################################################## # debian/compat file(WRITE ${DEBIAN_SOURCE_DIR}/debian/compat "7") ############################################################################## # debian/source/format file(WRITE ${DEBIAN_SOURCE_DIR}/debian/source/format "3.0 (quilt)") ############################################################################## # debian/changelog set(debian_changelog ${DEBIAN_SOURCE_DIR}/debian/changelog) if(NOT CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG) set(CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG ${CMAKE_SOURCE_DIR}/debian/changelog) endif() # TODO add support for git dch (git-buildpackage) if(EXISTS ${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG}) configure_file(${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG} ${debian_changelog} COPYONLY) if(CPACK_DEBIAN_UPDATE_CHANGELOG) file(READ ${debian_changelog} debian_changelog_content) execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package created with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n\n" ) file(APPEND ${debian_changelog} ${debian_changelog_content}) endif() else() execute_process( COMMAND date -R OUTPUT_VARIABLE DATE_TIME OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND lsb_release -cs OUTPUT_VARIABLE DISTRI OUTPUT_STRIP_TRAILING_WHITESPACE) file(WRITE ${debian_changelog} "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" " * Package built with CMake\n\n" " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n" ) endif() ########################################################################## # .orig.tar.gz #execute_process(COMMAND date +%y%m%d # OUTPUT_VARIABLE day_suffix # OUTPUT_STRIP_TRAILING_WHITESPACE # ) set(CPACK_SOURCE_IGNORE_FILES "/build/" "/debian/" "/.git/" ".gitignore" ".dput.cf" "/test/" "/packaging/" "*~") set(package_file_name "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}") file(WRITE "${CMAKE_BINARY_DIR}/Debian/cpack.cmake" "set(CPACK_GENERATOR TBZ2)\n" "set(CPACK_PACKAGE_NAME \"${CPACK_DEBIAN_PACKAGE_NAME}\")\n" "set(CPACK_PACKAGE_VERSION \"${CPACK_PACKAGE_VERSION}\")\n" "set(CPACK_PACKAGE_FILE_NAME \"${package_file_name}.orig\")\n" "set(CPACK_PACKAGE_DESCRIPTION \"${CPACK_PACKAGE_NAME} Source\")\n" "set(CPACK_IGNORE_FILES \"${CPACK_SOURCE_IGNORE_FILES}\")\n" "set(CPACK_INSTALLED_DIRECTORIES \"${CPACK_SOURCE_INSTALLED_DIRECTORIES}\")\n" ) set(orig_file "${DEBIAN_SOURCE_DIR}/${package_file_name}.orig.tar.bz2") add_custom_command(OUTPUT "${orig_file}" COMMAND cpack --config ./cpack.cmake WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/Debian" ) ############################################################################## # debuild -S set(DEB_SOURCE_CHANGES ${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}_source.changes ) add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} COMMAND ${DEBUILD_EXECUTABLE} -S WORKING_DIRECTORY ${DEBIAN_SOURCE_DIR} DEPENDS "${orig_file}" ) ############################################################################## # dput ppa:your-lp-id/ppa <source.changes> add_custom_target(dput ${DPUT_EXECUTABLE} ${DPUT_HOST} ${DEB_SOURCE_CHANGES} DEPENDS ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debian )
ruediger/VobSub2SRT
5fd4cf6565f032a082e2c289ec40c94ed052d6f3
build: print a warning if manpage is not compressed
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..006ea86 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +test/ +/.dput.cf +/doc/vobsub2srt.1.gz diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..69367f1 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,134 @@ +project(vobsub2srt) + +cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR) + +set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMakeModules) + +if(NOT CMAKE_BUILD_TYPE) + set( + CMAKE_BUILD_TYPE + Debug + CACHE + STRING + "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." + FORCE) +endif() + +message(STATUS "Source: ${CMAKE_SOURCE_DIR}") +message(STATUS "Binary: ${CMAKE_BINARY_DIR}") +message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") + +if(${CMAKE_BINARY_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) + message(FATAL_ERROR "In-source builds are not permitted. Make a separate folder for building:\nmkdir build; cd build; cmake ..\nBefore that, remove the files that cmake just created:\nrm -rf CMakeCache.txt CMakeFiles") +endif() + +if(BUILD_STATIC) + set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) +endif() + +set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) +set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) + +set(INSTALL_EXECUTABLES_PATH ${CMAKE_INSTALL_PREFIX}/bin) +set(INSTALL_LIBRARIES_PATH ${CMAKE_INSTALL_PREFIX}/lib) +set(INSTALL_HEADERS_PATH ${CMAKE_INSTALL_PREFIX}/include) +set(INSTALL_ETC_PATH ${CMAKE_INSTALL_PREFIX}/etc) +set(INSTALL_PC_PATH ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) +set(INSTALL_SHARE_DOC ${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}) +install(FILES "${CMAKE_SOURCE_DIR}/debian/copyright" DESTINATION ${INSTALL_SHARE_DOC}) +install(FILES "${CMAKE_SOURCE_DIR}/README.org" DESTINATION ${INSTALL_SHARE_DOC} RENAME README) + +add_definitions("-DINSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\"") + +include(CheckIncludeFile) +include(CheckCCompilerFlag) +include(CheckCSourceCompiles) +include(CheckCSourceRuns) +include(CheckCXXCompilerFlag) +include(CheckCXXSourceCompiles) +include(CheckCXXSourceRuns) + +set(CMAKE_C_FLAGS "-std=gnu99") +set(CMAKE_CXX_FLAGS "-ansi -pedantic-errors -Wall -Wextra") + +set(CMAKE_CXX_FLAGS_RELEASE "-O3 -mtune=native -march=native -DNDEBUG -fomit-frame-pointer -ffast-math") # TODO -Ofast GCC 4.6 +set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) +set(CMAKE_CXX_FLAGS_DEBUG "-g3 -DDEBUG") +set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) +# TODO RelWithDebInfo MinSizeRel? maybe move -march=native -ffast-math etc. to a different build type + +find_package(Libavutil) +find_package(Threads) +find_package(Tesseract) + +add_subdirectory(mplayer) +add_subdirectory(src) +add_subdirectory(doc) + +#### Detect Version +if(NOT VOBSUB2SRT_VERSION) + if(EXISTS "${vobsub2srt_SOURCE_DIR}/version") + file(READ "${vobsub2srt_SOURCE_DIR}/version" VOBSUB2SRT_VERSION) + string(REGEX REPLACE "\n" "" VOBSUB2SRT_VERSION "${VOBSUB2SRT_VERSION}") + elseif(EXISTS "${vobsub2srt_SOURCE_DIR}/.git") + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + if(GIT_FOUND) + execute_process( + COMMAND "${GIT_EXECUTABLE}" describe --tags --dirty --always + WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}" + OUTPUT_VARIABLE VOBSUB2SRT_VERSION + RESULT_VARIABLE EXECUTE_GIT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET) + endif() + endif() +endif() + +if(NOT VOBSUB2SRT_VERSION) + set(VOBSUB2SRT_VERSION "unknown-dirty") +endif() + +message(STATUS "vobsub2srt version: ${VOBSUB2SRT_VERSION}") + +#### Package Generation +execute_process ( + COMMAND /usr/bin/dpkg --print-architecture + OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE + RESULT_VARIABLE EXECUTE_RESULT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET +) +if(EXECUTE_RESULT) + message(STATUS "dpkg not found: No package generation.") +else() + message(STATUS "Debian architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") + set(CPACK_GENERATOR "DEB") + set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}") + set(CPACK_PACKAGE_VERSION "${VOBSUB2SRT_VERSION}") + set(CPACK_PACKAGE_CONTACT "Rüdiger Sonderfeld <[email protected]>") + set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ruediger/VobSub2SRT") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Converts VobSub subtitles (.idx/.srt format) into .srt subtitles.") + set(CPACK_PACKAGE_DESCRIPTION "VobSub2SRT is a simple command line program to convert .idx / .sub subtitles\ninto .srt text subtitles by using OCR. It is based on code from the MPlayer\nproject - a really great movie player.\nTesseract is used as OCR software.") + + set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/debian/copyright") + set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.org") + set(CPACK_STRIP_FILES TRUE) + + set(CPACK_DEBIAN_PACKAGE_SECTION "video") + set(CPACK_DEBIAN_PACKAGE_DEPENDS libtesseract-dev) + set(CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS libavutil-dev libtiff4-dev libtesseract-dev tesseract-ocr-eng cmake pkg-config) +# set(CPACK_DEBIAN_GIT_DCH TRUE) + set(CPACK_DEBIAN_UPDATE_CHANGELOG TRUE) + set(PPA_DEBIAN_VERSION "ppa1") + + set(DPUT_HOST "ppa:ruediger-c-plusplus/vobsub2srt") + + include(CPack) + + if(ENABLE_PPA) + set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "any") # can be build on any system + include(UploadPPA) + endif() +endif() diff --git a/CMakeModules/FindLibavutil.cmake b/CMakeModules/FindLibavutil.cmake new file mode 100644 index 0000000..53de43d --- /dev/null +++ b/CMakeModules/FindLibavutil.cmake @@ -0,0 +1,4 @@ +# Find libavutil (part of ffmpeg) + +include(FindPkgConfig) +pkg_check_modules(Libavutil REQUIRED libavutil) diff --git a/CMakeModules/FindTesseract.cmake b/CMakeModules/FindTesseract.cmake new file mode 100644 index 0000000..4b15d74 --- /dev/null +++ b/CMakeModules/FindTesseract.cmake @@ -0,0 +1,69 @@ +# Tesseract OCR + +if(Tesseract_INCLUDE_DIR AND Tesseract_LIBRARIES) + set(Tesseract_FIND_QUIETLY TRUE) +endif() + +find_path(Tesseract_INCLUDE_DIR tesseract/baseapi.h + HINTS + /usr/include + /usr/local/include) + +find_library(Tesseract_LIBRARIES NAMES tesseract_full tesseract_api tesseract + HINTS + /usr/lib + /usr/local/lib) + +find_library(Tiff_LIBRARY NAMES tiff + HINTS + /usr/lib + /usr/local/lib) + +if(BUILD_STATIC) +# -llept -lgif -lwebp -ltiff -lpng -ljpeg -lz +find_library(Lept_LIBRARY NAMES lept + HINTS + /usr/lib + /usr/local/lib) + +find_library(Webp_LIBRARY NAMES webp + HINTS + /usr/lib + /usr/local/lib) + +find_package(GIF) +find_package(JPEG) +find_package(PNG) +#find_package(TIFF) TODO replace manual find_library call +find_package(ZLIB) + +endif() + +if(TESSERACT_DATA_PATH) + add_definitions(-DTESSERACT_DATA_PATH="${TESSERACT_DATA_PATH}") +endif() + +set(CMAKE_REQUIRED_INCLUDES ${Tesseract_INCLUDE_DIR}) +check_cxx_source_compiles( + "#include \"tesseract/baseapi.h\" + using namespace tesseract; + int main() { + }" + TESSERACT_NAMESPACE) +if(TESSERACT_NAMESPACE) + add_definitions("-DCONFIG_TESSERACT_NAMESPACE") +else() + message(WARNING "You are using an old Tesseract version. Support for Tesseract 2 is deprecated and will be removed in the future!") +endif() +list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES ${Tesseract_INCLUDE_DIR}) + +if(BUILD_STATIC) + set(Tesseract_LIBRARIES ${Tesseract_LIBRARIES} ${Lept_LIBRARY} ${PNG_LIBRARY} ${Tiff_LIBRARY} ${Webp_LIBRARY} ${GIF_LIBRARY} ${JPEG_LIBRARY} ${ZLIB_LIBRARY}) +else() + set(Tesseract_LIBRARIES ${Tesseract_LIBRARIES} ${Tiff_LIBRARY}) +endif() + +include(FindPackageHandleStandardArgs) + +find_package_handle_standard_args(Tesseract DEFAULT_MSG Tesseract_LIBRARIES Tesseract_INCLUDE_DIR) +mark_as_advanced(Tesseract_INCLUDE_DIR Tesseract_LIBRARIES) diff --git a/CMakeModules/UploadPPA.cmake b/CMakeModules/UploadPPA.cmake new file mode 100644 index 0000000..83e5564 --- /dev/null +++ b/CMakeModules/UploadPPA.cmake @@ -0,0 +1,341 @@ +## -*- mode:cmake; coding:utf-8; -*- +# Copyright (c) 2010 Daniel Pfeifer <[email protected]> +# Changes Copyright (c) 2011 2012 Rüdiger Sonderfeld <[email protected]> +# +# UploadPPA.cmake is free software. It comes without any warranty, +# to the extent permitted by applicable law. You can redistribute it +# and/or modify it under the terms of the Do What The Fuck You Want +# To Public License, Version 2, as published by Sam Hocevar. See +# http://sam.zoy.org/wtfpl/COPYING for more details. +# +## +# Documentation +# +# This CMake module uploads a project to a PPA. It creates all the files +# necessary (similar to CPack) and uses debuild(1) and dput(1) to create the +# package and upload it to a PPA. A PPA is a Personal Package Archive and can +# be used by Debian/Ubuntu or other apt/deb based distributions to install and +# update packages from a remote repository. +# Canonicals Launchpad (http://launchpad.net) is usually used to host PPAs. +# See https://help.launchpad.net/Packaging/PPA for further information +# about PPAs. +# +# UploadPPA.cmake uses similar settings to CPack and the CPack DEB Generator. +# Additionally the following variables are used +# +# CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS to specify build dependencies +# (cmake is added as default) +# CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG should point to a file containing the +# changelog in debian format. If not set it checks whether a file +# debian/changelog exists in the source directory or creates a simply changelog +# file. +# CPACK_DEBIAN_UPDATE_CHANGELOG if set to True then UploadPPA.cmake adds a new +# entry to the changelog with the current version number and distribution name +# (lsb_release -c is used). This can be useful because debuild uses the latest +# version number from the changelog and the version number set in +# CPACK_PACKAGE_VERSION. If they mismatch the creation of the package fails. +# +## +# TODO +# I plan to add support for git dch (from git-buildpackage) to auto generate +# the changelog. +## + +find_program(DEBUILD_EXECUTABLE debuild) +find_program(DPUT_EXECUTABLE dput) + +if(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) + return() +endif(NOT DEBUILD_EXECUTABLE OR NOT DPUT_EXECUTABLE) + +# Strip "-dirty" flag from package version. +# It can be added by, e.g., git describe but it causes trouble with debuild etc. +string(REPLACE "-dirty" "" CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}) +message(STATUS "version: ${CPACK_PACKAGE_VERSION}") + +# DEBIAN/control +# debian policy enforce lower case for package name +# Package: (mandatory) +IF(NOT CPACK_DEBIAN_PACKAGE_NAME) + STRING(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_DEBIAN_PACKAGE_NAME) +ENDIF(NOT CPACK_DEBIAN_PACKAGE_NAME) + +# Section: (recommended) +IF(NOT CPACK_DEBIAN_PACKAGE_SECTION) + SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") +ENDIF(NOT CPACK_DEBIAN_PACKAGE_SECTION) + +# Priority: (recommended) +IF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) + SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") +ENDIF(NOT CPACK_DEBIAN_PACKAGE_PRIORITY) + +if(NOT CPACK_DEBIAN_PACKAGE_MAINTAINER) + set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT}) +endif() + +if(NOT CPACK_PACKAGE_DESCRIPTION AND EXISTS ${CPACK_PACKAGE_DESCRIPTION_FILE}) + file(STRINGS ${CPACK_PACKAGE_DESCRIPTION_FILE} DESC_LINES) + foreach(LINE ${DESC_LINES}) + set(deb_long_description "${deb_long_description} ${LINE}\n") + endforeach(LINE ${DESC_LINES}) +else() + # add space before each line + string(REPLACE "\n" "\n " deb_long_description " ${CPACK_PACKAGE_DESCRIPTION}") +endif() + +if(PPA_DEBIAN_VERSION) + set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}-${PPA_DEBIAN_VERSION}") +else() + message(WARNING "Variable PPA_DEBIAN_VERSION not set! Building 'native' package!") + set(DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") +endif() +message(STATUS "Debian version: ${DEBIAN_PACKAGE_VERSION}") + +set(DEBIAN_SOURCE_DIR ${CMAKE_BINARY_DIR}/Debian/${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}) + +############################################################################## +# debian/control +set(debian_control ${DEBIAN_SOURCE_DIR}/debian/control) +list(APPEND CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS cmake) +list(REMOVE_DUPLICATES CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) +list(SORT CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS) +string(REPLACE ";" ", " build_depends "${CPACK_DEBIAN_PACKAGE_BUILD_DEPENDS}") +string(REPLACE ";" ", " bin_depends "${CPACK_DEBIAN_PACKAGE_DEPENDS}") +file(WRITE ${debian_control} + "Source: ${CPACK_DEBIAN_PACKAGE_NAME}\n" + "Section: ${CPACK_DEBIAN_PACKAGE_SECTION}\n" + "Priority: ${CPACK_DEBIAN_PACKAGE_PRIORITY}\n" + "Maintainer: ${CPACK_DEBIAN_PACKAGE_MAINTAINER}\n" + "Build-Depends: ${build_depends}\n" + "Standards-Version: 3.9.3\n" + "Homepage: ${CPACK_DEBIAN_PACKAGE_HOMEPAGE}\n" + "\n" + "Package: ${CPACK_DEBIAN_PACKAGE_NAME}\n" + "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" + "Depends: ${bin_depends}, \${shlibs:Depends}\n" + "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}\n" + "${deb_long_description}" + ) + +foreach(COMPONENT ${CPACK_COMPONENTS_ALL}) + string(TOUPPER ${COMPONENT} UPPER_COMPONENT) + set(DEPENDS "${CPACK_DEBIAN_PACKAGE_NAME}") + foreach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) + set(DEPENDS "${DEPENDS}, ${CPACK_DEBIAN_PACKAGE_NAME}-${DEP}") + endforeach(DEP ${CPACK_COMPONENT_${UPPER_COMPONENT}_DEPENDS}) + file(APPEND ${debian_control} "\n" + "Package: ${CPACK_DEBIAN_PACKAGE_NAME}-${COMPONENT}\n" + "Architecture: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}\n" + "Depends: ${DEPENDS}\n" + "Description: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}" + ": ${CPACK_COMPONENT_${UPPER_COMPONENT}_DISPLAY_NAME}\n" + "${deb_long_description}" + " .\n" + " ${CPACK_COMPONENT_${UPPER_COMPONENT}_DESCRIPTION}\n" + ) +endforeach(COMPONENT ${CPACK_COMPONENTS_ALL}) + +############################################################################## +# debian/copyright +set(debian_copyright ${DEBIAN_SOURCE_DIR}/debian/copyright) +configure_file(${CPACK_RESOURCE_FILE_LICENSE} ${debian_copyright} COPYONLY) + +############################################################################## +# debian/rules +set(debian_rules ${DEBIAN_SOURCE_DIR}/debian/rules) +file(WRITE ${debian_rules} + "#!/usr/bin/make -f\n" + "\n" + "DEBUG = debug_build\n" + "RELEASE = release_build\n" + "CFLAGS =\n" + "CPPFLAGS =\n" + "CXXFLAGS =\n" + "FFLAGS =\n" + "LDFLAGS =\n" + "\n" + "configure-debug:\n" + "\tcmake -E make_directory $(DEBUG)\n" + "\tcd $(DEBUG); cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" + "\ttouch configure-debug\n" + "\n" + "configure-release:\n" + "\tcmake -E make_directory $(RELEASE)\n" + "\tcd $(RELEASE); cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr ..\n" + "\ttouch configure-release\n" + "\n" + "build: build-arch\n" # build-indep + "\n" + "build-arch: configure-release\n" # configure-debug +# "\t$(MAKE) --no-print-directory -C $(DEBUG) preinstall\n" + "\t$(MAKE) --no-print-directory -C $(RELEASE) preinstall\n" + "\ttouch build-arch\n" + "\n" + "build-indep: configure-release\n" + "\t$(MAKE) --no-print-directory -C $(RELEASE) documentation\n" + "\ttouch build-indep\n" + "\n" + "binary: binary-arch binary-indep\n" + "\n" + "binary-arch: build-arch\n" +# "\tcd $(DEBUG); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" + "\tcd $(RELEASE); cmake -DCOMPONENT=Unspecified -DCMAKE_INSTALL_PREFIX=../debian/tmp/usr -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n" + "\tcmake -E make_directory debian/tmp/DEBIAN\n" + "\tdpkg-shlibdeps debian/tmp/usr/bin/*\n" + "\tdpkg-gencontrol -p${CPACK_DEBIAN_PACKAGE_NAME} -Pdebian/tmp\n" + "\tdpkg --build debian/tmp ..\n" + ) + +foreach(component ${CPACK_COMPONENTS_ALL}) + string(TOUPPER "${component}" COMPONENT) + if(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) + set(path debian/${component}) + file(APPEND ${debian_rules} +# "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" + "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" + "\tcmake -E make_directory ${path}/DEBIAN\n" + "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" + "\tdpkg --build ${path} ..\n" + ) + endif(NOT CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) +endforeach(component) + +file(APPEND ${debian_rules} + "\n" + "binary-indep: build-indep\n" + ) + +foreach(component ${CPACK_COMPONENTS_ALL}) + string(TOUPPER "${component}" COMPONENT) + if(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) + set(path debian/${component}) + file(APPEND ${debian_rules} +# "\tcd $(DEBUG); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" + "\tcd $(RELEASE); cmake -DCOMPONENT=${component} -DCMAKE_INSTALL_PREFIX=../${path}/usr -P cmake_install.cmake\n" + "\tcmake -E make_directory ${path}/DEBIAN\n" + "\tdpkg-gencontrol -p${CPACK_COMPONENT_${COMPONENT}_DEB_PACKAGE} -P${path}\n" + "\tdpkg --build ${path} ..\n" + ) + endif(CPACK_COMPONENT_${COMPONENT}_BINARY_INDEP) +endforeach(component) + +file(APPEND ${debian_rules} + "\n" + "clean:\n" + "\tcmake -E remove_directory $(DEBUG)\n" + "\tcmake -E remove_directory $(RELEASE)\n" + "\tcmake -E remove configure-debug configure-release build-arch build-indep\n" + "\n" + ".PHONY: binary binary-arch binary-indep clean\n" + ) + +execute_process(COMMAND chmod +x ${debian_rules}) + +############################################################################## +# debian/compat +file(WRITE ${DEBIAN_SOURCE_DIR}/debian/compat "7") + +############################################################################## +# debian/source/format +file(WRITE ${DEBIAN_SOURCE_DIR}/debian/source/format "3.0 (quilt)") + +############################################################################## +# debian/changelog +set(debian_changelog ${DEBIAN_SOURCE_DIR}/debian/changelog) +if(NOT CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG) + set(CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG ${CMAKE_SOURCE_DIR}/debian/changelog) +endif() + +# TODO add support for git dch (git-buildpackage) + +if(EXISTS ${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG}) + configure_file(${CPACK_DEBIAN_RESOURCE_FILE_CHANGELOG} ${debian_changelog} COPYONLY) + + if(CPACK_DEBIAN_UPDATE_CHANGELOG) + file(READ ${debian_changelog} debian_changelog_content) + execute_process( + COMMAND date -R + OUTPUT_VARIABLE DATE_TIME + OUTPUT_STRIP_TRAILING_WHITESPACE) + execute_process( + COMMAND lsb_release -cs + OUTPUT_VARIABLE DISTRI + OUTPUT_STRIP_TRAILING_WHITESPACE) + file(WRITE ${debian_changelog} + "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" + " * Package created with CMake\n\n" + " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n\n" + ) + file(APPEND ${debian_changelog} ${debian_changelog_content}) + endif() + +else() + execute_process( + COMMAND date -R + OUTPUT_VARIABLE DATE_TIME + OUTPUT_STRIP_TRAILING_WHITESPACE) + execute_process( + COMMAND lsb_release -cs + OUTPUT_VARIABLE DISTRI + OUTPUT_STRIP_TRAILING_WHITESPACE) + file(WRITE ${debian_changelog} + "${CPACK_DEBIAN_PACKAGE_NAME} (${DEBIAN_PACKAGE_VERSION}) ${DISTRI}; urgency=low\n\n" + " * Package built with CMake\n\n" + " -- ${CPACK_DEBIAN_PACKAGE_MAINTAINER} ${DATE_TIME}\n" + ) +endif() + +########################################################################## +# .orig.tar.gz +#execute_process(COMMAND date +%y%m%d +# OUTPUT_VARIABLE day_suffix +# OUTPUT_STRIP_TRAILING_WHITESPACE +# ) + +set(CPACK_SOURCE_IGNORE_FILES + "/build/" + "/debian/" + "/.git/" + ".gitignore" + ".dput.cf" + "/test/" + "/packaging/" + "*~") + +set(package_file_name "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}") + +file(WRITE "${CMAKE_BINARY_DIR}/Debian/cpack.cmake" + "set(CPACK_GENERATOR TBZ2)\n" + "set(CPACK_PACKAGE_NAME \"${CPACK_DEBIAN_PACKAGE_NAME}\")\n" + "set(CPACK_PACKAGE_VERSION \"${CPACK_PACKAGE_VERSION}\")\n" + "set(CPACK_PACKAGE_FILE_NAME \"${package_file_name}.orig\")\n" + "set(CPACK_PACKAGE_DESCRIPTION \"${CPACK_PACKAGE_NAME} Source\")\n" + "set(CPACK_IGNORE_FILES \"${CPACK_SOURCE_IGNORE_FILES}\")\n" + "set(CPACK_INSTALLED_DIRECTORIES \"${CPACK_SOURCE_INSTALLED_DIRECTORIES}\")\n" + ) + +set(orig_file "${DEBIAN_SOURCE_DIR}/${package_file_name}.orig.tar.bz2") +add_custom_command(OUTPUT "${orig_file}" + COMMAND cpack --config ./cpack.cmake + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/Debian" + ) + +############################################################################## +# debuild -S +set(DEB_SOURCE_CHANGES + ${CPACK_DEBIAN_PACKAGE_NAME}_${DEBIAN_PACKAGE_VERSION}_source.changes + ) + +add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} + COMMAND ${DEBUILD_EXECUTABLE} -S + WORKING_DIRECTORY ${DEBIAN_SOURCE_DIR} + DEPENDS "${orig_file}" + ) + +############################################################################## +# dput ppa:your-lp-id/ppa <source.changes> +add_custom_target(dput ${DPUT_EXECUTABLE} ${DPUT_HOST} ${DEB_SOURCE_CHANGES} + DEPENDS ${CMAKE_BINARY_DIR}/Debian/${DEB_SOURCE_CHANGES} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debian + ) diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6cdf649 --- /dev/null +++ b/Makefile @@ -0,0 +1,39 @@ +.PHONY: all clean distclean install uninstall package dput documentation + +all: build + $(MAKE) -C build + +clean: build + $(MAKE) -C build clean + +distclean: + rm -rf build/ + +documentation: build + $(MAKE) -C build documentation + +install: build + $(MAKE) -C build install + +uninstall: build + @if [ -f build/install_manifest.txt ]; then \ + echo 'Uninstalling' ; \ + xargs rm < build/install_manifest.txt ; \ + else \ + echo 'VobSub2Srt does not seem to be installed.'; \ + fi + +package: build + $(MAKE) -C build package + +dput: + @if [ -d build/Debian ]; then \ + git dch --snapshot --since=465fa781b93e66cfb7080c55880969cb4631d584; \ + $(MAKE) -C build dput; \ + else \ + echo 'Use ./configure -DENABLE_PPA=True to activate PPA support.'; \ + fi + +build: + @echo "Please run ./configure (with appropriate parameters)!" + @exit 1 diff --git a/README b/README new file mode 120000 index 0000000..314e17d --- /dev/null +++ b/README @@ -0,0 +1 @@ +README.org \ No newline at end of file diff --git a/README.org b/README.org new file mode 100644 index 0000000..7851732 --- /dev/null +++ b/README.org @@ -0,0 +1,94 @@ +# -*- mode:org; mode:visual-line; coding:utf-8; -*- +VobSub2SRT is a simple command line program to convert =.idx= / =.sub= subtitles into =.srt= text subtitles by using OCR. It is based on code from the [[http://www.mplayerhq.hu][MPlayer project]] - a really really great movie player. [[http://code.google.com/p/tesseract-ocr/][Tesseract]] is used as OCR software. + +vobsub2srt is released under the GPL3+ license. The MPlayer code included is GPL2+ licensed. + +The quality of the OCR depends on the text in the subtitles. Currently the code does not use any preprocessing. But I'm currently looking into adding filters and scaling options to improve the OCR. You can correct mistakes in the =.srt= files with a text editor or a special subtitle editor. + +* Building +You need tesseract and libavutil (part of the [[http://ffmpeg.org/][FFmpeg]] project). You also need cmake and a gcc to build it. With Ubuntu 12.04 you can install the dependencies with + +#+BEGIN_EXAMPLE + sudo apt-get install libavutil-dev libtiff4-dev libtesseract-dev tesseract-ocr-eng build-essential cmake pkg-config +#+END_EXAMPLE + +You should also install the tesseract data for the languages you want to use! Note that the support for tesseract 2 is deprecated and will be removed in the future! + +#+BEGIN_EXAMPLE + ./configure + make + sudo make install +#+END_EXAMPLE + +This should install the program vobsub2srt to =/usr/local/bin=. You can uninstall vobsub2srt with =sudo make uninstall=. If you want to install the bash completion script then set the =BASH_COMPLETION_PATH= parameter: + +#+BEGIN_EXAMPLE + ./configure -DBASH_COMPLETION_PATH="$BASH_COMPLETION_DIR" +#+END_EXAMPLE + +** Static binary +I recommend using the dynamic binary! However if you really need a static binary you can add the flag =-DBUILD_STATIC=ON= to the =./configure= call. But be aware that building static binaries can be quit troublesome. You need the static library files for tesseract, libtill, avutils, and for their dependencies as well. On Ubuntu 12.04 the static libraries are only included in the dev packages! You probably also need the Gold linker. + +For Ubuntu 12.04 you need the following extra packages: + +#+BEGIN_EXAMPLE + sudo apt-get install libleptonica-dev libpng12-dev libwebp-dev libgif-dev zlib1g-dev libjpeg-dev binutils-gold +#+END_EXAMPLE + +If linking fails with undefined references then checking what other dependencies your version of leptonica has is a good starting point. You can do this by running =ldd /usr/lib/liblept.so= (or whatever the path to leptonica is on your system). Add those dependencies to =CMakeModules/FindTesseract.cmake=. + +** Ubuntu PPA and .deb packages +I have created a [[https://launchpad.net/~ruediger-c-plusplus/+archive/vobsub2srt][PPA (Personal Package Archive)]] to make installation on Ubuntu easy. Simply add the PPA to your apt-get sources and run an update and you can install the =vobsub2srt= package: + +#+BEGIN_EXAMPLE + sudo add-apt-repository ppa:ruediger-c-plusplus/vobsub2srt + sudo apt-get update + sudo apt-get install vobsub2srt +#+END_EXAMPLE + +*** .deb (Debian/Ubuntu) +You can build a *.deb package (Debian/Ubuntu) with =make package=. The package is created in the =build= directory. + +You can also create a source package and upload it to your own PPA by using the =UploadPPA.cmake=. But this is only recommended for people experienced with cmake and creating Debian packages. + +** Homebrew +Vobsub2srt contains a formula for [[http://mxcl.github.com/homebrew/][Homebrew]] (a package manager for OS X). It can be installed by using the command =brew install https://github.com/ruediger/VobSub2SRT/raw/master/packaging/vobsub2srt.rb=. + +** Gentoo ebuild +An [[http://en.wikipedia.org/wiki/Ebuild][ebuild]] for Gentoo Linux is also available. You can make it available to emerge with the following steps + +#+BEGIN_EXAMPLE + sudo mkdir -p /usr/local/portage/media/video/vobsub2srt/ + wget https://github.com/ruediger/VobSub2SRT/raw/master/packaging/vobsub2srt-9999.ebuild + sudo mv vobsub2srt-9999.ebuild /usr/local/portage/media/video/vobsub2srt/ + cd /usr/local/portage/media/video/vobsub2srt/ + sudo ebuild vobsub2srt-999.ebuild digest +#+END_EXAMPLE + +You should be able to install vobsub2srt with =emerge vobsub2srt= now. If you want to use a newer version (3+) of tesseract you have to use layman. See [[https://github.com/ruediger/VobSub2SRT/issues/13][#13]] for details. +** Arch AUR +There also exist a [[https://wiki.archlinux.org/index.php/PKGBUILD][PKGBUILD]] file for Arch Linux in AUR: [[https://aur.archlinux.org/packages.php?ID=50015]] +* Usage +vobsub2srt converts subtitles in VobSub (=.idx= / =.sub=) format into subtitles in =.srt= format. VobSub subtitles consist of two or three files called =Filename.idx=, =Filename.sub= and optional =Filename.ifo=. To convert subtitles simply call + +#+BEGIN_EXAMPLE + vobsub2srt Filename +#+END_EXAMPLE + +with =Filename= being the file name of the subtitle files *WITHOUT* the extension (=.idx= / =.sub=). vobsub2srt writes the subtitles to a file called =Filename.srt=. + +If a subtitle file contains more than one language you can use the =--lang= parameter to set the correct language (Use =--langlist= to find out about the languages in the file). + +If you want to dump the subtitles as images (e.g. to check for correct ocr) you can use the =--dump-images= flag. + +Use =--help= or read the manpage to get more information about the options of vobsub2srt. + +* Contributors +Most code is from the MPlayer project. +- Armin Häberling <[email protected]> wrote a patch to fix an issue with multiple instances of the same subtitle in result file (21af426) +- James Harris <[email protected]> wrote the formula for Homebrew (54f311d6) +- Leo Koppelkamm reported and fixed issue #5 and problems with long filenames (b903074c, 36ec8da, d3602d6) +- Till Korten <[email protected]> wrote the ebuild script (#13) +- Andreasf fixed missing libavutil include path (3a175eb, #15) +* To Do +- implement preprocessing (first step scaling. Code available in =spudec.c=) diff --git a/configure b/configure new file mode 100755 index 0000000..5d0e400 --- /dev/null +++ b/configure @@ -0,0 +1,5 @@ +#!/bin/sh +# -*- mode:sh; coding:utf-8; -*- + +mkdir build 2>/dev/null +cd build && cmake "$@" .. diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..6ccb9d6 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,89 @@ +vobsub2srt (0.0ubuntu1~1.gbpdb8f2d) UNRELEASED; urgency=low + + ** SNAPSHOT build @db8f2d14276aba886292eb13d48ac05ef1f34bcf ** + + [ Rüdiger Sonderfeld ] + * FinLibavutil: added comment + * added detection and linking for Tesseract + * added more code to extract spu and made spudec.h c++ compat + * Tesseract: search and link libtiff + * ignore test dir for now + * added function to extract the required data from spudec_handle_t + * finished basic structure + * build: added install + * added GPL3+ license header and fixed bug in tesseract usage + * added GPL3+ text + * added README + * R: comments to mark changes from original MPlayer code + * cleaned up the dump_pgm code + * added code to handle cmd args + * improved error message when files not found + * fixed critical mistake ++j vs ++i + * mplayer: fixed vobsub_set_from_lang api (const correctness) + * added --lang flag and code to set the correct language stream and tesseract test data (required ISO 639-1 to ISO 639-3 conversion) + * try to set correct tesseract lang for default stream + * dump_images: use XXX as subtitle id + * should be --dump-images and not --dump_images + * updated README + * added --tesseract-data to set the tesseract data path from the cmd + * print text only when verbose is set + * improved error message when OCR failed + * added GPL3+ header to langcodes.?++ + * moved cmd_options into own code file + * use start_pts from the subfile and not the time stamp from the idx file. + * changed README to org-mode + * README: minor org-mode fix + * README: minor fix (big) + * README: another minor fix (missing == tags) + * updated README + * added manpage vobsub2srt(1) + * install manpage + * updated README (manpage) + + [ Armin Häberling ] + * fix issue with multiple instances of the same subtitle in result file. + + [ Rüdiger Sonderfeld ] + * README: added Contributors (Armin) + * added missing libtiff4-dev dependency + * fixed bug in cmd_options (wasn't relevant for vobsub2srt though) + * Made VobSub2SRT work with Tesseract 3.00. + * forgot to replace Flusspferd with VobSub2SRT + * cmake: fixed Hints (FindTesseract) + * build: added support to build *.deb (Debian/Ubuntu etc.) package (make package) + * README: added make package + * added libtesseract_api as alternative to _full (for tesseract 3.0 support) and changed TESSERACT_NAMESPACE flag to CONFIG_TESSERACT_NAMESPACE + * added support for an ocr blacklist + * added --blacklist documentation + * build/deb: changed version number to prevent problems with dpkg + + [ James Harris ] + * Added Homebrew formula for easy OS X installation. + + [ Rüdiger Sonderfeld ] + * mplayer code: merged spudec.c changes from mplayer trunk. + * stop if .srt file can not be opened + * doc: Added information about the Homebrew formula. + * added James Harris to the Contributors (Homebrew formula) + * build: added version detection + + [ Leo Koppelkamm ] + * Fix issue with some sub files + * Switch off unnecessary messages: + * fix an issue with long directory names + + [ Rüdiger Sonderfeld ] + * Keep in sync with mplayer: Fix typos. + * Keep in sync with mplayer: vobsub: simplify timestamp parsing. + * Keep in sync with mplayer: vobsub: simplify origin parsing. + * README: added Leo Koppelkamm to the list of contributors + * build: apparently tesseract on Ubuntu 11.10 uses threads. CMake now links thread libraries. + * build: prepared for UploadPPA.cmake + + -- Rüdiger Sonderfeld <[email protected]> Wed, 16 Nov 2011 01:16:16 +0100 + +vobsub2srt (0.0) oneiric; urgency=low + + * Initial + + -- Rüdiger Sonderfeld <[email protected]> Mon, 14 Nov 2011 01:35:36 +0100 diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..bb63a54 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,50 @@ +This package is fetched from https://github.com/ruediger/VobSub2SRT. + +Licenses: +GPLv2+: + This package is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + MPlayer is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with MPlayer; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +On Debian systems, the complete text of the GNU General +Public License can be found in `/usr/share/common-licenses/GPL-2'. + +GPLv3+: + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +On Debian systems, the complete text of the GNU General +Public License can be found in `/usr/share/common-licenses/GPL-3'. + +Licenses, upstream authors and copyright holders: + +mplayer part + License: GPLv2+ + Copyright (C) 2005 Jindrich Makovicka <makovick gmail com> + Copyright (C) 2007 Ulion <ulion2002 gmail com> + Copyright (C) 2005 Jindrich Makovicka <makovick gmail com> + Copyright (C) 2007 Ulion <ulion2002 gmail com> + +vobsub2srt part + License: GPLv3+ + Copyright (C) 2010-2012 Rüdiger Sonderfeld <[email protected]> diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt new file mode 100644 index 0000000..372f20c --- /dev/null +++ b/doc/CMakeLists.txt @@ -0,0 +1,30 @@ +find_program(GZIP gzip + HINTS + /bin + /usr/bin + /usr/local/bin) + +if(GZIP-NOTFOUND) + message(WARNING "Gzip not found! Uncompressed manpage installed") + add_custom_target(documentation + DEPENDS vobsub2srt.1) + + install(FILES vobsub2srt.1 DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) +else() + add_custom_command( + OUTPUT vobsub2srt.1.gz + COMMAND ${GZIP} -9 -c vobsub2srt.1 > vobsub2srt.1.gz + MAIN_DEPENDENCY vobsub2srt.1 + WORKING_DIRECTORY "${vobsub2srt_SOURCE_DIR}/doc") + + add_custom_target(documentation + DEPENDS vobsub2srt.1.gz) + + install(FILES vobsub2srt.1.gz DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) +endif() + +option(BASH_COMPLETION_PATH "Install the bash completion script to the given path. Should be set to the value of $BASH_COMPLETION_DIR if available.") +if(BASH_COMPLETION_PATH) + message(STATUS "Bash completion path: ${BASH_COMPLETION_PATH}") + install(FILES completion.sh DESTINATION ${BASH_COMPLETION_PATH} RENAME vobsub2srt) +endif() diff --git a/doc/completion.sh b/doc/completion.sh new file mode 100755 index 0000000..f52b17a --- /dev/null +++ b/doc/completion.sh @@ -0,0 +1,57 @@ +#!/bin/bash +# -*- mode:sh; coding:utf-8; -*- +# +# Bash completions for vobsub2srt(1). +# +# Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +have vobsub2srt && +_vobsub2srt() { + local cmd cur prev tmp arg + cmd=${COMP_WORDS[0]} + _get_comp_words_by_ref cur prev + + case $prev in + --ifo) + _filedir '(ifo|IFO)' + return 0 + ;; + --lang|-l) + _get_first_arg + tmp=$( "$cmd" --langlist -- "$arg" 2>/dev/null | sed -E -e '/Languages:/d; s/^[[:digit:]]+: //;' ) + COMPREPLY=( $( compgen -W "$tmp" -- "$cur" ) ) + return 0 + ;; + --tesseract-data) + _filedir -d + return 0 + ;; + esac + + case $cur in + -*) + COMPREPLY=( $( compgen -W '--dump-images --verbose --ifo --lang --langlist --tesseract-data --blacklist' -- "$cur" ) ) + ;; + *) + _filedir '(idx|IDX|sub|SUB)' + COMPREPLY=$( echo "$COMPREPLY" | sed -E -e 's/.(idx|IDX|sub|SUB)$//' ) # remove suffix + ;; + esac + + return 0 +} && +complete -F _vobsub2srt vobsub2srt diff --git a/doc/vobsub2srt.1 b/doc/vobsub2srt.1 new file mode 100644 index 0000000..2b62b89 --- /dev/null +++ b/doc/vobsub2srt.1 @@ -0,0 +1,42 @@ +.TH vobsub2srt 1 "27 September 2010" +.SH NAME +vobsub2srt \- converts vobsub (.idx/.sub) into .srt subtitles +.SH SYNOPSIS +\fBvobsub2srt\fR [\fIOPTION\fR] \fIFILENAME\fR +.SH DESCRIPTION +.PP +vobsub2srt converts subtitles in vobsub (.idx/.sub) format into the .srt format. VobSub subtitles contain images and srt is a text format. OCR is used to extract the text from the subtitles. vobsub2srt uses tesseract for OCR and is based on code from the MPlayer project. +.SH OPTIONS +.TP +\fIFILENAME\fR +File name of the subtitles \fBWITHOUT\fR the .idx or .sub extension. The .srt subtitles are written to a file called \fIFILENAME\fR.srt. +.TP +\fB\-\-dump\-images\fR +Dump the subtitles as images (format \fIFILENAME\fR-\fINUMBER\fR.pgm in PGM format). +.TP +\fB\-\-verbose\fR +Print more information about the file (e.g. subtitle languages) +.TP +\fB\-\-lang\fR \fIlanguage\fR +Select the language of the subtitle (two letter ISO 639-1 code e.g. en for English or de for German). Use \fI--verbose\fR to see the languages in the subtitle file. +.TP +\fB\-\-langlist\fR +List languages and exit. +.TP +\fB\-\-ifo\fR \fIifo-file\fR +To use a specific IFO file. Default: \fIFILENAME\fR.IFO is tried. IFO file is optional! +.TP +\fB\-\-tesseract-data\fR \fIpath\fR +Set path to tesseract-data. +.TP +\fB\-\-blacklist\fR \fIblacklist\fR +Blacklist characters for OCR (e.g. |\\/`_~<>) +.SH EXAMPLES +.nf + $ \fBvobsub2srt \-\-lang en foobar\fR +.fi +Converts the English language subtitles from the VobSub files \fIfoobar.idx\fR/\fIfoobar.sub\fR to srt subtitles in \fIfoobar.srt\fR. +.SH HOMEPAGE +For more information see \fIhttp://github.com/ruediger/VobSub2SRT\fR +.SH AUTHOR +R\[:u]diger Sonderfeld <\fIruediger -AT- c-plusplus -DOT- de\fR> diff --git a/mplayer/CMakeLists.txt b/mplayer/CMakeLists.txt new file mode 100644 index 0000000..b357c68 --- /dev/null +++ b/mplayer/CMakeLists.txt @@ -0,0 +1,17 @@ +add_definitions("-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE -D_REENTRANT") +add_definitions("-Wundef -Wall -Wno-switch -Wno-parentheses -Wpointer-arith -Wredundant-decls -Wstrict-prototypes -Wmissing-prototypes -Wdisabled-optimization -Wno-pointer-sign -Wdeclaration-after-statement") + +include_directories(${Libavutil_INCLUDE_DIRS}) + +set(mplayer_sources + mp_msg.c + mp_msg.h + spudec.c + spudec.h + unrar_exec.c + unrar_exec.h + vobsub.c + vobsub.h + ) + +add_library(mplayer STATIC ${mplayer_sources}) diff --git a/mplayer/README b/mplayer/README new file mode 100644 index 0000000..bedd401 --- /dev/null +++ b/mplayer/README @@ -0,0 +1,3 @@ +The code in this folder is copied from the MPlayer project (http://www.mplayerhq.hu/). A really great movie player! It is licensed under the GPL2+ license. + +I added comments prefixed with R: to mark changes from the original MPlayer code. diff --git a/mplayer/mp_msg.c b/mplayer/mp_msg.c new file mode 100644 index 0000000..dc0bbb3 --- /dev/null +++ b/mplayer/mp_msg.c @@ -0,0 +1,245 @@ +/* + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <stdio.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> + +#if 0 // R: no iconv, charset stuff +#include "config.h" +#include "osdep/getch2.h" +#endif + +#ifdef CONFIG_ICONV +#include <iconv.h> +#include <errno.h> +#endif + +#include "mp_msg.h" + +/* maximum message length of mp_msg */ +#define MSGSIZE_MAX 3072 + +int mp_msg_levels[MSGT_MAX]; // verbose level of this module. initialized to -2 +int mp_msg_level_all = MSGL_STATUS; +int verbose = 0; +int mp_msg_color = 0; +int mp_msg_module = 0; +#ifdef CONFIG_ICONV +char *mp_msg_charset = NULL; +static char *old_charset = NULL; +static iconv_t msgiconv; +#endif + +const char* filename_recode(const char* filename) +{ +#if !defined(CONFIG_ICONV) || !defined(MSG_CHARSET) + return filename; +#else + static iconv_t inv_msgiconv = (iconv_t)(-1); + static char recoded_filename[MSGSIZE_MAX]; + size_t filename_len, max_path; + char* precoded; + if (!mp_msg_charset || + !strcasecmp(mp_msg_charset, MSG_CHARSET) || + !strcasecmp(mp_msg_charset, "noconv")) + return filename; + if (inv_msgiconv == (iconv_t)(-1)) { + inv_msgiconv = iconv_open(MSG_CHARSET, mp_msg_charset); + if (inv_msgiconv == (iconv_t)(-1)) + return filename; + } + filename_len = strlen(filename); + max_path = MSGSIZE_MAX - 4; + precoded = recoded_filename; + if (iconv(inv_msgiconv, &filename, &filename_len, + &precoded, &max_path) == (size_t)(-1) && errno == E2BIG) { + precoded[0] = precoded[1] = precoded[2] = '.'; + precoded += 3; + } + *precoded = '\0'; + return recoded_filename; +#endif +} + +void mp_msg_init(void){ + int i; +#if 0 // R: don't check MPLAYER_VERBOSE environment var + char *env = getenv("MPLAYER_VERBOSE"); + if (env) + verbose = atoi(env); +#endif + for(i=0;i<MSGT_MAX;i++) mp_msg_levels[i] = -2; + mp_msg_levels[MSGT_IDENTIFY] = -1; // no -identify output by default +#ifdef CONFIG_ICONV + mp_msg_charset = getenv("MPLAYER_CHARSET"); + if (!mp_msg_charset) + mp_msg_charset = get_term_charset(); +#endif +} + +int mp_msg_test(int mod, int lev) +{ + return lev <= (mp_msg_levels[mod] == -2 ? mp_msg_level_all + verbose : mp_msg_levels[mod]); +} + +static void set_msg_color(FILE* stream, int lev) +{ + static const unsigned char v_colors[10] = {9, 1, 3, 15, 7, 2, 2, 8, 8, 8}; + int c = v_colors[lev]; +#ifdef MP_ANNOY_ME + /* that's only a silly color test */ + { + int c; + static int flag = 1; + if (flag) + for(c = 0; c < 24; c++) + printf("\033[%d;3%dm*** COLOR TEST %d ***\n", c>7, c&7, c); + flag = 0; + } +#endif + if (mp_msg_color) + fprintf(stream, "\033[%d;3%dm", c >> 3, c & 7); +} + +static void print_msg_module(FILE* stream, int mod) +{ + static const char *module_text[MSGT_MAX] = { + "GLOBAL", + "CPLAYER", + "GPLAYER", + "VIDEOOUT", + "AUDIOOUT", + "DEMUXER", + "DS", + "DEMUX", + "HEADER", + "AVSYNC", + "AUTOQ", + "CFGPARSER", + "DECAUDIO", + "DECVIDEO", + "SEEK", + "WIN32", + "OPEN", + "DVD", + "PARSEES", + "LIRC", + "STREAM", + "CACHE", + "MENCODER", + "XACODEC", + "TV", + "OSDEP", + "SPUDEC", + "PLAYTREE", + "INPUT", + "VFILTER", + "OSD", + "NETWORK", + "CPUDETECT", + "CODECCFG", + "SWS", + "VOBSUB", + "SUBREADER", + "AFILTER", + "NETST", + "MUXER", + "OSDMENU", + "IDENTIFY", + "RADIO", + "ASS", + "LOADER", + "STATUSLINE", + }; + int c2 = (mod + 1) % 15 + 1; + + if (!mp_msg_module) + return; + if (mp_msg_color) + fprintf(stream, "\033[%d;3%dm", c2 >> 3, c2 & 7); + fprintf(stream, "%9s", module_text[mod]); + if (mp_msg_color) + fprintf(stream, "\033[0;37m"); + fprintf(stream, ": "); +} + +void mp_msg(int mod, int lev, const char *format, ... ){ + va_list va; + char tmp[MSGSIZE_MAX]; + FILE *stream = lev <= MSGL_WARN ? stderr : stdout; + static int header = 1; + // indicates if last line printed was a status line + static int statusline; + size_t len; + + if (!mp_msg_test(mod, lev)) return; // do not display + va_start(va, format); + vsnprintf(tmp, MSGSIZE_MAX, format, va); + va_end(va); + tmp[MSGSIZE_MAX-2] = '\n'; + tmp[MSGSIZE_MAX-1] = 0; + +#if defined(CONFIG_ICONV) && defined(MSG_CHARSET) + if (mp_msg_charset && strcasecmp(mp_msg_charset, "noconv")) { + char tmp2[MSGSIZE_MAX]; + size_t inlen = strlen(tmp), outlen = MSGSIZE_MAX; + char *in = tmp, *out = tmp2; + if (!old_charset || strcmp(old_charset, mp_msg_charset)) { + if (old_charset) { + free(old_charset); + iconv_close(msgiconv); + } + msgiconv = iconv_open(mp_msg_charset, MSG_CHARSET); + old_charset = strdup(mp_msg_charset); + } + if (msgiconv == (iconv_t)(-1)) { + fprintf(stderr,"iconv: conversion from %s to %s unsupported\n" + ,MSG_CHARSET,mp_msg_charset); + }else{ + memset(tmp2, 0, MSGSIZE_MAX); + while (iconv(msgiconv, &in, &inlen, &out, &outlen) == -1) { + if (!inlen || !outlen) + break; + *out++ = *in++; + outlen--; inlen--; + } + strncpy(tmp, tmp2, MSGSIZE_MAX); + tmp[MSGSIZE_MAX-1] = 0; + tmp[MSGSIZE_MAX-2] = '\n'; + } + } +#endif + + // as a status line normally is intended to be overwitten by next status line + // output a '\n' to get a normal message on a separate line + if (statusline && lev != MSGL_STATUS) fprintf(stream, "\n"); + statusline = lev == MSGL_STATUS; + + if (header) + print_msg_module(stream, mod); + set_msg_color(stream, lev); + len = strlen(tmp); + header = len && (tmp[len-1] == '\n' || tmp[len-1] == '\r'); + + fprintf(stream, "%s", tmp); + if (mp_msg_color) + fprintf(stream, "\033[0m"); + fflush(stream); +} diff --git a/mplayer/mp_msg.h b/mplayer/mp_msg.h new file mode 100644 index 0000000..b483821 --- /dev/null +++ b/mplayer/mp_msg.h @@ -0,0 +1,171 @@ +/* + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef MPLAYER_MP_MSG_H +#define MPLAYER_MP_MSG_H + +#ifdef __cplusplus +extern "C" { +#endif + +// defined in mplayer.c and mencoder.c +extern int verbose; + +// verbosity elevel: + +/* Only messages level MSGL_FATAL-MSGL_STATUS should be translated, + * messages level MSGL_V and above should not be translated. */ + +#define MSGL_FATAL 0 // will exit/abort +#define MSGL_ERR 1 // continues +#define MSGL_WARN 2 // only warning +#define MSGL_HINT 3 // short help message +#define MSGL_INFO 4 // -quiet +#define MSGL_STATUS 5 // v=0 +#define MSGL_V 6 // v=1 +#define MSGL_DBG2 7 // v=2 +#define MSGL_DBG3 8 // v=3 +#define MSGL_DBG4 9 // v=4 +#define MSGL_DBG5 10 // v=5 + +#define MSGL_FIXME 1 // for conversions from printf where the appropriate MSGL is not known; set equal to ERR for obtrusiveness +#define MSGT_FIXME 0 // for conversions from printf where the appropriate MSGT is not known; set equal to GLOBAL for obtrusiveness + +// code/module: + +#define MSGT_GLOBAL 0 // common player stuff errors +#define MSGT_CPLAYER 1 // console player (mplayer.c) +#define MSGT_GPLAYER 2 // gui player + +#define MSGT_VO 3 // libvo +#define MSGT_AO 4 // libao + +#define MSGT_DEMUXER 5 // demuxer.c (general stuff) +#define MSGT_DS 6 // demux stream (add/read packet etc) +#define MSGT_DEMUX 7 // fileformat-specific stuff (demux_*.c) +#define MSGT_HEADER 8 // fileformat-specific header (*header.c) + +#define MSGT_AVSYNC 9 // mplayer.c timer stuff +#define MSGT_AUTOQ 10 // mplayer.c auto-quality stuff + +#define MSGT_CFGPARSER 11 // cfgparser.c + +#define MSGT_DECAUDIO 12 // av decoder +#define MSGT_DECVIDEO 13 + +#define MSGT_SEEK 14 // seeking code +#define MSGT_WIN32 15 // win32 dll stuff +#define MSGT_OPEN 16 // open.c (stream opening) +#define MSGT_DVD 17 // open.c (DVD init/read/seek) + +#define MSGT_PARSEES 18 // parse_es.c (mpeg stream parser) +#define MSGT_LIRC 19 // lirc_mp.c and input lirc driver + +#define MSGT_STREAM 20 // stream.c +#define MSGT_CACHE 21 // cache2.c + +#define MSGT_MENCODER 22 + +#define MSGT_XACODEC 23 // XAnim codecs + +#define MSGT_TV 24 // TV input subsystem + +#define MSGT_OSDEP 25 // OS-dependent parts + +#define MSGT_SPUDEC 26 // spudec.c + +#define MSGT_PLAYTREE 27 // Playtree handeling (playtree.c, playtreeparser.c) + +#define MSGT_INPUT 28 + +#define MSGT_VFILTER 29 + +#define MSGT_OSD 30 + +#define MSGT_NETWORK 31 + +#define MSGT_CPUDETECT 32 + +#define MSGT_CODECCFG 33 + +#define MSGT_SWS 34 + +#define MSGT_VOBSUB 35 +#define MSGT_SUBREADER 36 + +#define MSGT_AFILTER 37 // Audio filter messages + +#define MSGT_NETST 38 // Netstream + +#define MSGT_MUXER 39 // muxer layer + +#define MSGT_OSD_MENU 40 + +#define MSGT_IDENTIFY 41 // -identify output + +#define MSGT_RADIO 42 + +#define MSGT_ASS 43 // libass messages + +#define MSGT_LOADER 44 // dll loader messages + +#define MSGT_STATUSLINE 45 // playback/encoding status line + +#define MSGT_TELETEXT 46 // Teletext decoder + +#define MSGT_MAX 64 + + +extern char *mp_msg_charset; +extern int mp_msg_color; +extern int mp_msg_module; + +extern int mp_msg_levels[MSGT_MAX]; +extern int mp_msg_level_all; + + +void mp_msg_init(void); +int mp_msg_test(int mod, int lev); + +//#include "config.h" // R: not needed + +#ifdef __GNUC__ +void mp_msg(int mod, int lev, const char *format, ... ) __attribute__ ((format (printf, 3, 4))); +#if 0 // R: not needed and args... doesn't work with -ansi +# ifdef MP_DEBUG +# define mp_dbg(mod,lev, args... ) mp_msg(mod, lev, ## args ) +# else +# define mp_dbg(mod,lev, args... ) /* only useful for developers */ +# endif +#endif +#else // not GNU C +void mp_msg(int mod, int lev, const char *format, ... ); +# ifdef MP_DEBUG +# define mp_dbg(mod,lev, ... ) mp_msg(mod, lev, __VA_ARGS__) +# else +# define mp_dbg(mod,lev, ... ) /* only useful for developers */ +# endif +#endif /* __GNUC__ */ + +const char* filename_recode(const char* filename); + +#ifdef __cplusplus +} +#endif + +#endif /* MPLAYER_MP_MSG_H */ diff --git a/mplayer/spudec.c b/mplayer/spudec.c new file mode 100644 index 0000000..5b3f7eb --- /dev/null +++ b/mplayer/spudec.c @@ -0,0 +1,1473 @@ +/* + * Skeleton of function spudec_process_controll() is from xine sources. + * Further works: + * LGB,... (yeah, try to improve it and insert your name here! ;-) + * + * Kim Minh Kaplan + * implement fragments reassembly, RLE decoding. + * read brightness from the IFO. + * + * For information on SPU format see <URL:http://sam.zoy.org/doc/dvd/subtitles/> + * and <URL:http://members.aol.com/mpucoder/DVD/spu.html> + * + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +// #include "config.h" +#include "mp_msg.h" + +#include <errno.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <math.h> +//#include "libvo/sub.h" // R: no OSD stuff needed +//#include "libvo/video_out.h" // R: no OSD stuff needed + +int sub_pos = 100; // R: copied from libvo/sub.c + +#include "spudec.h" +#include "vobsub.h" +#include <libavutil/avutil.h> // R: Use systems' avutil +//#include <libavutil/intreadwrite.h> // R: Use systems' avutil +// #include "libswscale/swscale.h" // R: no swscalar gaussian aamode + +/* Valid values for spu_aamode: + 0: none (fastest, most ugly) + 1: approximate + 2: full (slowest) + 3: bilinear (similiar to vobsub, fast and not too bad) + 4: uses swscaler gaussian (this is the only one that looks good) R: Not supported (libswscale dependency removed) + */ + +int spu_aamode = 3; +int spu_alignment = -1; +float spu_gaussvar = 1.0; + +typedef struct packet_t packet_t; +struct packet_t { + int is_decoded; + unsigned char *packet; + int data_len; + unsigned int palette[4]; + unsigned int alpha[4]; + unsigned int control_start; /* index of start of control data */ + unsigned int current_nibble[2]; /* next data nibble (4 bits) to be + processed (for RLE decoding) for + even and odd lines */ + int deinterlace_oddness; /* 0 or 1, index into current_nibble */ + unsigned int start_col; + unsigned int start_row; + unsigned int width, height, stride; + unsigned int start_pts, end_pts; + packet_t *next; +}; + +struct palette_crop_cache { + int valid; + uint32_t palette; + int sx, sy, ex, ey; + int result; +}; + +typedef struct { + packet_t *queue_head; + packet_t *queue_tail; + unsigned int global_palette[16]; + unsigned int orig_frame_width, orig_frame_height; + unsigned char* packet; + size_t packet_reserve; /* size of the memory pointed to by packet */ + unsigned int packet_offset; /* end of the currently assembled fragment */ + unsigned int packet_size; /* size of the packet once all fragments are assembled */ + int packet_pts; /* PTS for this packet */ + unsigned int palette[4]; + unsigned int alpha[4]; + unsigned int cuspal[4]; + unsigned int custom; + unsigned int now_pts; + unsigned int start_pts, end_pts; + unsigned int start_col; + unsigned int start_row; + unsigned int width, height, stride; + size_t image_size; /* Size of the image buffer */ + unsigned char *image; /* Grayscale value */ + unsigned char *aimage; /* Alpha value */ + unsigned int pal_start_col, pal_start_row; + unsigned int pal_width, pal_height; + unsigned char *pal_image; /* palette entry value */ + unsigned int scaled_frame_width, scaled_frame_height; + unsigned int scaled_start_col, scaled_start_row; + unsigned int scaled_width, scaled_height, scaled_stride; + size_t scaled_image_size; + unsigned char *scaled_image; + unsigned char *scaled_aimage; + int auto_palette; /* 1 if we lack a palette and must use an heuristic. */ + int font_start_level; /* Darkest value used for the computed font */ + // const vo_functions_t *hw_spu; // R: not necessary + int spu_changed; + unsigned int forced_subs_only; /* flag: 0=display all subtitle, !0 display only forced subtitles */ + unsigned int is_forced_sub; /* true if current subtitle is a forced subtitle */ + + struct palette_crop_cache palette_crop_cache; +} spudec_handle_t; + +static void spudec_queue_packet(spudec_handle_t *this, packet_t *packet) +{ + if (this->queue_head == NULL) + this->queue_head = packet; + else + this->queue_tail->next = packet; + this->queue_tail = packet; +} + +static packet_t *spudec_dequeue_packet(spudec_handle_t *this) +{ + packet_t *retval = this->queue_head; + + this->queue_head = retval->next; + if (this->queue_head == NULL) + this->queue_tail = NULL; + + return retval; +} + +static void spudec_free_packet(packet_t *packet) +{ + free(packet->packet); + free(packet); +} + +static inline unsigned int get_be16(const unsigned char *p) +{ + return (p[0] << 8) + p[1]; +} + +static inline unsigned int get_be24(const unsigned char *p) +{ + return (get_be16(p) << 8) + p[2]; +} + +static void next_line(packet_t *packet) +{ + if (packet->current_nibble[packet->deinterlace_oddness] % 2) + packet->current_nibble[packet->deinterlace_oddness]++; + packet->deinterlace_oddness = (packet->deinterlace_oddness + 1) % 2; +} + +static inline unsigned char get_nibble(packet_t *packet) +{ + unsigned char nib; + unsigned int *nibblep = packet->current_nibble + packet->deinterlace_oddness; + if (*nibblep / 2 >= packet->control_start) { + mp_msg(MSGT_SPUDEC,MSGL_WARN, "SPUdec: ERROR: get_nibble past end of packet\n"); + return 0; + } + nib = packet->packet[*nibblep / 2]; + if (*nibblep % 2) + nib &= 0xf; + else + nib >>= 4; + ++*nibblep; + return nib; +} + +/* Cut the sub to visible part */ +static inline void spudec_cut_image(spudec_handle_t *this) +{ + unsigned int fy, ly; + unsigned int first_y, last_y; + + if (this->stride == 0 || this->height == 0) { + return; + } + + for (fy = 0; fy < this->image_size && !this->aimage[fy]; fy++); + for (ly = this->stride * this->height-1; ly && !this->aimage[ly]; ly--); + first_y = fy / this->stride; + last_y = ly / this->stride; + //printf("first_y: %d, last_y: %d\n", first_y, last_y); + this->start_row += first_y; + + // Some subtitles trigger this condition + if (last_y + 1 > first_y ) { + this->height = last_y - first_y +1; + } else { + this->height = 0; + return; + } + +// printf("new h %d new start %d (sz %d st %d)---\n\n", this->height, this->start_row, this->image_size, this->stride); + + if (first_y > 0) { + memmove(this->image, this->image + this->stride * first_y, this->stride * this->height); + memmove(this->aimage, this->aimage + this->stride * first_y, this->stride * this->height); + } +} + + +static int spudec_alloc_image(spudec_handle_t *this, int stride, int height) +{ + if (this->width > stride) // just a safeguard + this->width = stride; + this->stride = stride; + this->height = height; + if (this->image_size < this->stride * this->height) { + if (this->image != NULL) { + free(this->image); + free(this->pal_image); + this->image_size = 0; + this->pal_width = this->pal_height = 0; + } + this->image = malloc(2 * this->stride * this->height); + if (this->image) { + this->image_size = this->stride * this->height; + this->aimage = this->image + this->image_size; + // use stride here as well to simplify reallocation checks + this->pal_image = malloc(this->stride * this->height); + } + } + return this->image != NULL; +} + +/** + * \param pal palette in MPlayer-style gray-alpha values, i.e. + * alpha == 0 means transparent, 1 fully opaque, + * gray value <= 256 - alpha. + */ +static void pal2gray_alpha(const uint16_t *pal, + const uint8_t *src, int src_stride, + uint8_t *dst, uint8_t *dsta, + int dst_stride, int w, int h) +{ + int x, y; + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) { + uint16_t pixel = pal[src[x]]; + *dst++ = pixel; + *dsta++ = pixel >> 8; + } + for (; x < dst_stride; x++) + *dsta++ = *dst++ = 0; + src += src_stride; + } +} + +static int apply_palette_crop(spudec_handle_t *this, + unsigned crop_x, unsigned crop_y, + unsigned crop_w, unsigned crop_h) +{ + int i; + uint8_t *src; + uint16_t pal[4]; + unsigned stride = (crop_w + 7) & ~7; + if (crop_x > this->pal_width || crop_y > this->pal_height || + crop_w > this->pal_width - crop_x || crop_h > this->pal_width - crop_y || + crop_w > 0x8000 || crop_h > 0x8000 || + stride * crop_h > this->image_size) { + return 0; + } + for (i = 0; i < 4; ++i) { + int color; + int alpha = this->alpha[i]; + // extend 4 -> 8 bit + alpha |= alpha << 4; + if (this->custom && (this->cuspal[i] >> 31) != 0) + alpha = 0; + color = this->custom ? this->cuspal[i] : + this->global_palette[this->palette[i]]; + color = (color >> 16) & 0xff; + // convert to MPlayer-style gray/alpha palette + color = FFMIN(color, alpha); + pal[i] = (-alpha << 8) | color; + } + src = this->pal_image + crop_y * this->pal_width + crop_x; + pal2gray_alpha(pal, src, this->pal_width, + this->image, this->aimage, stride, + crop_w, crop_h); + this->width = crop_w; + this->height = crop_h; + this->stride = stride; + this->start_col = this->pal_start_col + crop_x; + this->start_row = this->pal_start_row + crop_y; + spudec_cut_image(this); + + // reset scaled image + this->scaled_frame_width = 0; + this->scaled_frame_height = 0; + this->palette_crop_cache.valid = 0; + return 1; +} + +int spudec_apply_palette_crop(void *this, uint32_t palette, + int sx, int sy, int ex, int ey) +{ + spudec_handle_t *spu = this; + struct palette_crop_cache *c = &spu->palette_crop_cache; + if (c->valid && c->palette == palette && + c->sx == sx && c->sy == sy && c->ex == ex && c->ey == ey) + return c->result; + spu->palette[0] = (palette >> 28) & 0xf; + spu->palette[1] = (palette >> 24) & 0xf; + spu->palette[2] = (palette >> 20) & 0xf; + spu->palette[3] = (palette >> 16) & 0xf; + spu->alpha[0] = (palette >> 12) & 0xf; + spu->alpha[1] = (palette >> 8) & 0xf; + spu->alpha[2] = (palette >> 4) & 0xf; + spu->alpha[3] = palette & 0xf; + spu->spu_changed = 1; + c->result = apply_palette_crop(spu, + sx - spu->pal_start_col, sy - spu->pal_start_row, + ex - sx, ey - sy); + c->palette = palette; + c->sx = sx; c->sy = sy; + c->ex = ex; c->ey = ey; + c->valid = 1; + return c->result; +} + +static void spudec_process_data(spudec_handle_t *this, packet_t *packet) +{ + unsigned int i, x, y; + uint8_t *dst; + + if (!spudec_alloc_image(this, packet->stride, packet->height)) + return; + + this->pal_start_col = packet->start_col; + this->pal_start_row = packet->start_row; + this->pal_height = packet->height; + this->pal_width = packet->width; + this->stride = packet->stride; + memcpy(this->palette, packet->palette, sizeof(this->palette)); + memcpy(this->alpha, packet->alpha, sizeof(this->alpha)); + + i = packet->current_nibble[1]; + x = 0; + y = 0; + dst = this->pal_image; + while (packet->current_nibble[0] < i + && packet->current_nibble[1] / 2 < packet->control_start + && y < this->pal_height) { + unsigned int len, color; + unsigned int rle = 0; + rle = get_nibble(packet); + if (rle < 0x04) { + if (rle == 0) { + rle = (rle << 4) | get_nibble(packet); + if (rle < 0x04) + rle = (rle << 4) | get_nibble(packet); + } + rle = (rle << 4) | get_nibble(packet); + } + color = 3 - (rle & 0x3); + len = rle >> 2; + x += len; + if (len == 0 || x >= this->pal_width) { + len += this->pal_width - x; + next_line(packet); + x = 0; + ++y; + } + memset(dst, color, len); + dst += len; + } + apply_palette_crop(this, 0, 0, this->pal_width, this->pal_height); +} + + +/* + This function tries to create a usable palette. + It determines how many non-transparent colors are used, and assigns different +gray scale values to each color. + I tested it with four streams and even got something readable. Half of the +times I got black characters with white around and half the reverse. +*/ +static void compute_palette(spudec_handle_t *this, packet_t *packet) +{ + int used[16],i,cused,start,step,color; + + memset(used, 0, sizeof(used)); + for (i=0; i<4; i++) + if (packet->alpha[i]) /* !Transparent? */ + used[packet->palette[i]] = 1; + for (cused=0, i=0; i<16; i++) + if (used[i]) cused++; + if (!cused) return; + if (cused == 1) { + start = 0x80; + step = 0; + } else { + start = this->font_start_level; + step = (0xF0-this->font_start_level)/(cused-1); + } + memset(used, 0, sizeof(used)); + for (i=0; i<4; i++) { + color = packet->palette[i]; + if (packet->alpha[i] && !used[color]) { /* not assigned? */ + used[color] = 1; + this->global_palette[color] = start<<16; + start += step; + } + } +} + +static void spudec_process_control(spudec_handle_t *this, int pts100) +{ + int a,b,c,d; /* Temporary vars */ + unsigned int date, type; + unsigned int off; + unsigned int start_off = 0; + unsigned int next_off; + unsigned int start_pts = 0; + unsigned int end_pts = 0; + unsigned int current_nibble[2] = {0, 0}; + unsigned int control_start; + unsigned int display = 0; + unsigned int start_col = 0; + unsigned int end_col = 0; + unsigned int start_row = 0; + unsigned int end_row = 0; + unsigned int width = 0; + unsigned int height = 0; + unsigned int stride = 0; + + control_start = get_be16(this->packet + 2); + next_off = control_start; + while (start_off != next_off) { + start_off = next_off; + date = get_be16(this->packet + start_off) * 1024; + next_off = get_be16(this->packet + start_off + 2); + mp_msg(MSGT_SPUDEC,MSGL_DBG2, "date=%d\n", date); + off = start_off + 4; + for (type = this->packet[off++]; type != 0xff; type = this->packet[off++]) { + mp_msg(MSGT_SPUDEC,MSGL_DBG2, "cmd=%d ",type); + switch(type) { + case 0x00: + /* Menu ID, 1 byte */ + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Menu ID\n"); + /* shouldn't a Menu ID type force display start? */ + start_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; + end_pts = UINT_MAX; + display = 1; + this->is_forced_sub=~0; // current subtitle is forced + break; + case 0x01: + /* Start display */ + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Start display!\n"); + start_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; + end_pts = UINT_MAX; + display = 1; + this->is_forced_sub=0; + break; + case 0x02: + /* Stop display */ + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Stop display!\n"); + end_pts = pts100 < 0 && -pts100 >= date ? 0 : pts100 + date; + break; + case 0x03: + /* Palette */ + this->palette[0] = this->packet[off] >> 4; + this->palette[1] = this->packet[off] & 0xf; + this->palette[2] = this->packet[off + 1] >> 4; + this->palette[3] = this->packet[off + 1] & 0xf; + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Palette %d, %d, %d, %d\n", + this->palette[0], this->palette[1], this->palette[2], this->palette[3]); + off+=2; + break; + case 0x04: + /* Alpha */ + a = this->packet[off] >> 4; + b = this->packet[off] & 0xf; + c = this->packet[off + 1] >> 4; + d = this->packet[off + 1] & 0xf; + // Note: some DVDs change these values to create a fade-in/fade-out effect + // We can not handle this, so just keep the highest value during the display time. + if (display) { + a = FFMAX(a, this->alpha[0]); + b = FFMAX(b, this->alpha[1]); + c = FFMAX(c, this->alpha[2]); + d = FFMAX(d, this->alpha[3]); + } + this->alpha[0] = a; + this->alpha[1] = b; + this->alpha[2] = c; + this->alpha[3] = d; + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Alpha %d, %d, %d, %d\n", + this->alpha[0], this->alpha[1], this->alpha[2], this->alpha[3]); + off+=2; + break; + case 0x05: + /* Co-ords */ + a = get_be24(this->packet + off); + b = get_be24(this->packet + off + 3); + start_col = a >> 12; + end_col = a & 0xfff; + width = (end_col < start_col) ? 0 : end_col - start_col + 1; + stride = (width + 7) & ~7; /* Kludge: draw_alpha needs width multiple of 8 */ + start_row = b >> 12; + end_row = b & 0xfff; + height = (end_row < start_row) ? 0 : end_row - start_row /* + 1 */; + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Coords col: %d - %d row: %d - %d (%dx%d)\n", + start_col, end_col, start_row, end_row, + width, height); + off+=6; + break; + case 0x06: + /* Graphic lines */ + current_nibble[0] = 2 * get_be16(this->packet + off); + current_nibble[1] = 2 * get_be16(this->packet + off + 2); + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Graphic offset 1: %d offset 2: %d\n", + current_nibble[0] / 2, current_nibble[1] / 2); + off+=4; + break; + case 0xff: + /* All done, bye-bye */ + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"Done!\n"); + return; +// break; + default: + mp_msg(MSGT_SPUDEC,MSGL_WARN,"spudec: Error determining control type 0x%02x. Skipping %d bytes.\n", + type, next_off - off); + goto next_control; + } + } + next_control: + if (!display) + continue; + if (end_pts == UINT_MAX && start_off != next_off) { + end_pts = get_be16(this->packet + next_off) * 1024; + end_pts = 1 - pts100 >= end_pts ? 0 : pts100 + end_pts - 1; + } + if (end_pts > 0) { + packet_t *packet = calloc(1, sizeof(packet_t)); + int i; + packet->start_pts = start_pts; + packet->end_pts = end_pts; + packet->current_nibble[0] = current_nibble[0]; + packet->current_nibble[1] = current_nibble[1]; + packet->start_row = start_row; + packet->start_col = start_col; + packet->width = width; + packet->height = height; + packet->stride = stride; + packet->control_start = control_start; + for (i=0; i<4; i++) { + packet->alpha[i] = this->alpha[i]; + packet->palette[i] = this->palette[i]; + } + packet->packet = malloc(this->packet_size); + memcpy(packet->packet, this->packet, this->packet_size); + spudec_queue_packet(this, packet); + } + } +} + +static void spudec_decode(spudec_handle_t *this, int pts100) +{ +#if 0 // R: OSD stuff removed + if (!this->hw_spu) + spudec_process_control(this, pts100); + else if (pts100 >= 0) { + static vo_mpegpes_t packet = { NULL, 0, 0x20, 0 }; + static vo_mpegpes_t *pkg=&packet; + packet.data = this->packet; + packet.size = this->packet_size; + packet.timestamp = pts100; + this->hw_spu->draw_frame((uint8_t**)&pkg); + } +#else + spudec_process_control(this, pts100); +#endif +} + +int spudec_changed(void * this) +{ + spudec_handle_t * spu = this; + return spu->spu_changed || spu->now_pts > spu->end_pts; +} + +void spudec_assemble(void *this, unsigned char *packet, unsigned int len, int pts100) +{ + spudec_handle_t *spu = this; +// spudec_heartbeat(this, pts100); + if (len < 2) { + mp_msg(MSGT_SPUDEC,MSGL_WARN,"SPUasm: packet too short\n"); + return; + } + spu->packet_pts = pts100; + if (spu->packet_offset == 0) { + unsigned int len2 = get_be16(packet); + // Start new fragment + if (spu->packet_reserve < len2) { + free(spu->packet); + spu->packet = malloc(len2); + spu->packet_reserve = spu->packet != NULL ? len2 : 0; + } + if (spu->packet != NULL) { + spu->packet_size = len2; + if (len > len2) { + mp_msg(MSGT_SPUDEC,MSGL_WARN,"SPUasm: invalid frag len / len2: %d / %d \n", len, len2); + return; + } + memcpy(spu->packet, packet, len); + spu->packet_offset = len; + spu->packet_pts = pts100; + } + } else { + // Continue current fragment + if (spu->packet_size < spu->packet_offset + len){ + mp_msg(MSGT_SPUDEC,MSGL_WARN,"SPUasm: invalid fragment\n"); + spu->packet_size = spu->packet_offset = 0; + return; + } else { + memcpy(spu->packet + spu->packet_offset, packet, len); + spu->packet_offset += len; + } + } +#if 1 + // check if we have a complete packet (unfortunatelly packet_size is bad + // for some disks) + // [cb] packet_size is padded to be even -> may be one byte too long + if ((spu->packet_offset == spu->packet_size) || + ((spu->packet_offset + 1) == spu->packet_size)){ + unsigned int x=0,y; + while(x+4<=spu->packet_offset){ + y=get_be16(spu->packet+x+2); // next control pointer + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPUtest: x=%d y=%d off=%d size=%d\n",x,y,spu->packet_offset,spu->packet_size); + if(x>=4 && x==y){ // if it points to self - we're done! + // we got it! + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPUgot: off=%d size=%d \n",spu->packet_offset,spu->packet_size); + spudec_decode(spu, pts100); + spu->packet_offset = 0; + break; + } + if(y<=x || y>=spu->packet_size){ // invalid? + mp_msg(MSGT_SPUDEC,MSGL_WARN,"SPUtest: broken packet!!!!! y=%d < x=%d\n",y,x); + spu->packet_size = spu->packet_offset = 0; + break; + } + x=y; + } + // [cb] packet is done; start new packet + spu->packet_offset = 0; + } +#else + if (spu->packet_offset == spu->packet_size) { + spudec_decode(spu, pts100); + spu->packet_offset = 0; + } +#endif +} + +void spudec_reset(void *this) // called after seek +{ + spudec_handle_t *spu = this; + while (spu->queue_head) + spudec_free_packet(spudec_dequeue_packet(spu)); + spu->now_pts = 0; + spu->end_pts = 0; + spu->packet_size = spu->packet_offset = 0; +} + +void spudec_heartbeat(void *this, unsigned int pts100) +{ + spudec_handle_t *spu = this; + spu->now_pts = pts100; + + // TODO: detect and handle broken timestamps (e.g. due to wrapping) + while (spu->queue_head != NULL && pts100 >= spu->queue_head->start_pts) { + packet_t *packet = spudec_dequeue_packet(spu); + spu->start_pts = packet->start_pts; + spu->end_pts = packet->end_pts; + if (packet->is_decoded) { + free(spu->image); + spu->image_size = packet->data_len; + spu->image = packet->packet; + spu->aimage = packet->packet + packet->stride * packet->height; + packet->packet = NULL; + spu->width = packet->width; + spu->height = packet->height; + spu->stride = packet->stride; + spu->start_col = packet->start_col; + spu->start_row = packet->start_row; + + // reset scaled image + spu->scaled_frame_width = 0; + spu->scaled_frame_height = 0; + } else { + if (spu->auto_palette) + compute_palette(spu, packet); + spudec_process_data(spu, packet); + } + spudec_free_packet(packet); + spu->spu_changed = 1; + } +} + +int spudec_visible(void *this){ + spudec_handle_t *spu = this; + int ret=(spu->start_pts <= spu->now_pts && + spu->now_pts < spu->end_pts && + spu->height > 0); +// printf("spu visible: %d \n",ret); + return ret; +} + +void spudec_set_forced_subs_only(void * const this, const unsigned int flag) +{ + if(this){ + ((spudec_handle_t *)this)->forced_subs_only=flag; + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPU: Display only forced subs now %s\n", flag ? "enabled": "disabled"); + } +} + +void spudec_draw(void *this, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)) +{ + spudec_handle_t *spu = this; + if (spudec_visible(spu)) + { + draw_alpha(spu->start_col, spu->start_row, spu->width, spu->height, + spu->image, spu->aimage, spu->stride); + spu->spu_changed = 0; + } +} + +/* calc the bbox for spudec subs */ +void spudec_calc_bbox(void *me, unsigned int dxs, unsigned int dys, unsigned int* bbox) +{ + spudec_handle_t *spu = me; + if (spu->orig_frame_width == 0 || spu->orig_frame_height == 0 + || (spu->orig_frame_width == dxs && spu->orig_frame_height == dys)) { + // unscaled + bbox[0] = spu->start_col; + bbox[1] = spu->start_col + spu->width; + bbox[2] = spu->start_row; + bbox[3] = spu->start_row + spu->height; + } + else { + // scaled + unsigned int scalex = 0x100 * dxs / spu->orig_frame_width; + unsigned int scaley = 0x100 * dys / spu->orig_frame_height; + bbox[0] = spu->start_col * scalex / 0x100; + bbox[1] = spu->start_col * scalex / 0x100 + spu->width * scalex / 0x100; + switch (spu_alignment) { + case 0: + bbox[3] = dys*sub_pos/100 + spu->height * scaley / 0x100; + if (bbox[3] > dys) bbox[3] = dys; + bbox[2] = bbox[3] - spu->height * scaley / 0x100; + break; + case 1: + if (sub_pos < 50) { + bbox[2] = dys*sub_pos/100 - spu->height * scaley / 0x200; + bbox[3] = bbox[2] + spu->height; + } else { + bbox[3] = dys*sub_pos/100 + spu->height * scaley / 0x200; + if (bbox[3] > dys) bbox[3] = dys; + bbox[2] = bbox[3] - spu->height * scaley / 0x100; + } + break; + case 2: + bbox[2] = dys*sub_pos/100 - spu->height * scaley / 0x100; + bbox[3] = bbox[2] + spu->height; + break; + default: /* -1 */ + bbox[2] = spu->start_row * scaley / 0x100; + bbox[3] = spu->start_row * scaley / 0x100 + spu->height * scaley / 0x100; + break; + } + } +} +/* transform mplayer's alpha value into an opacity value that is linear */ +static inline int canon_alpha(int alpha) +{ + return (uint8_t)-alpha; +} + +typedef struct { + unsigned position; + unsigned left_up; + unsigned right_down; +}scale_pixel; + + +static void scale_table(unsigned int start_src, unsigned int start_tar, unsigned int end_src, unsigned int end_tar, scale_pixel * table) +{ + unsigned int t; + unsigned int delta_src = end_src - start_src; + unsigned int delta_tar = end_tar - start_tar; + int src = 0; + int src_step; + if (delta_src == 0 || delta_tar == 0) { + return; + } + src_step = (delta_src << 16) / delta_tar >>1; + for (t = 0; t<=delta_tar; src += (src_step << 1), t++){ + table[t].position= FFMIN(src >> 16, end_src - 1); + table[t].right_down = src & 0xffff; + table[t].left_up = 0x10000 - table[t].right_down; + } +} + +/* bilinear scale, similar to vobsub's code */ +static void scale_image(int x, int y, scale_pixel* table_x, scale_pixel* table_y, spudec_handle_t * spu) +{ + int alpha[4]; + int color[4]; + unsigned int scale[4]; + int base = table_y[y].position * spu->stride + table_x[x].position; + int scaled = y * spu->scaled_stride + x; + alpha[0] = canon_alpha(spu->aimage[base]); + alpha[1] = canon_alpha(spu->aimage[base + 1]); + alpha[2] = canon_alpha(spu->aimage[base + spu->stride]); + alpha[3] = canon_alpha(spu->aimage[base + spu->stride + 1]); + color[0] = spu->image[base]; + color[1] = spu->image[base + 1]; + color[2] = spu->image[base + spu->stride]; + color[3] = spu->image[base + spu->stride + 1]; + scale[0] = (table_x[x].left_up * table_y[y].left_up >> 16) * alpha[0]; + if (table_y[y].left_up == 0x10000) // necessary to avoid overflow-case + scale[0] = table_x[x].left_up * alpha[0]; + scale[1] = (table_x[x].right_down * table_y[y].left_up >>16) * alpha[1]; + scale[2] = (table_x[x].left_up * table_y[y].right_down >> 16) * alpha[2]; + scale[3] = (table_x[x].right_down * table_y[y].right_down >> 16) * alpha[3]; + spu->scaled_image[scaled] = (color[0] * scale[0] + color[1] * scale[1] + color[2] * scale[2] + color[3] * scale[3])>>24; + spu->scaled_aimage[scaled] = (scale[0] + scale[1] + scale[2] + scale[3]) >> 16; + if (spu->scaled_aimage[scaled]){ + // ensure that MPlayer's simplified alpha-blending can not overflow + spu->scaled_image[scaled] = FFMIN(spu->scaled_image[scaled], spu->scaled_aimage[scaled]); + // convert to MPlayer-style alpha + spu->scaled_aimage[scaled] = -spu->scaled_aimage[scaled]; + } +} + +#if 0 // R: removed sws scaling +static void sws_spu_image(unsigned char *d1, unsigned char *d2, int dw, int dh, + int ds, const unsigned char* s1, unsigned char* s2, + int sw, int sh, int ss) +{ + struct SwsContext *ctx; + static SwsFilter filter; + static int firsttime = 1; + static float oldvar; + int i; + + if (!firsttime && oldvar != spu_gaussvar) sws_freeVec(filter.lumH); + if (firsttime) { + filter.lumH = filter.lumV = + filter.chrH = filter.chrV = sws_getGaussianVec(spu_gaussvar, 3.0); + sws_normalizeVec(filter.lumH, 1.0); + firsttime = 0; + oldvar = spu_gaussvar; + } + + ctx=sws_getContext(sw, sh, PIX_FMT_GRAY8, dw, dh, PIX_FMT_GRAY8, SWS_GAUSS, &filter, NULL, NULL); + sws_scale(ctx,&s1,&ss,0,sh,&d1,&ds); + for (i=ss*sh-1; i>=0; i--) if (!s2[i]) s2[i] = 255; //else s2[i] = 1; + sws_scale(ctx,&s2,&ss,0,sh,&d2,&ds); + for (i=ds*dh-1; i>=0; i--) if (d2[i]==0) d2[i] = 1; else if (d2[i]==255) d2[i] = 0; + sws_freeContext(ctx); +} +#endif + +void spudec_draw_scaled(void *me, unsigned int dxs, unsigned int dys, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)) +{ + spudec_handle_t *spu = me; + scale_pixel *table_x; + scale_pixel *table_y; + + if (spudec_visible(spu)) { + + // check if only forced subtitles are requested + if( (spu->forced_subs_only) && !(spu->is_forced_sub) ){ + return; + } + + if (!(spu_aamode&16) && (spu->orig_frame_width == 0 || spu->orig_frame_height == 0 + || (spu->orig_frame_width == dxs && spu->orig_frame_height == dys))) { + spudec_draw(spu, draw_alpha); + } + else { + if (spu->scaled_frame_width != dxs || spu->scaled_frame_height != dys) { /* Resizing is needed */ + /* scaled_x = scalex * x / 0x100 + scaled_y = scaley * y / 0x100 + order of operations is important because of rounding. */ + unsigned int scalex = 0x100 * dxs / spu->orig_frame_width; + unsigned int scaley = 0x100 * dys / spu->orig_frame_height; + spu->scaled_start_col = spu->start_col * scalex / 0x100; + spu->scaled_start_row = spu->start_row * scaley / 0x100; + spu->scaled_width = spu->width * scalex / 0x100; + spu->scaled_height = spu->height * scaley / 0x100; + /* Kludge: draw_alpha needs width multiple of 8 */ + spu->scaled_stride = (spu->scaled_width + 7) & ~7; + if (spu->scaled_image_size < spu->scaled_stride * spu->scaled_height) { + if (spu->scaled_image) { + free(spu->scaled_image); + spu->scaled_image_size = 0; + } + spu->scaled_image = malloc(2 * spu->scaled_stride * spu->scaled_height); + if (spu->scaled_image) { + spu->scaled_image_size = spu->scaled_stride * spu->scaled_height; + spu->scaled_aimage = spu->scaled_image + spu->scaled_image_size; + } + } + if (spu->scaled_image) { + unsigned int x, y; + // needs to be 0-initialized because draw_alpha draws always a + // multiple of 8 pixels. TODO: optimize + if (spu->scaled_width & 7) + memset(spu->scaled_image, 0, 2 * spu->scaled_image_size); + if (spu->scaled_width <= 1 || spu->scaled_height <= 1) { + goto nothing_to_do; + } + switch(spu_aamode&15) { + case 4: +#if 0 // R: no swscalar gaussian aa supported + sws_spu_image(spu->scaled_image, spu->scaled_aimage, + spu->scaled_width, spu->scaled_height, spu->scaled_stride, + spu->image, spu->aimage, spu->width, spu->height, spu->stride); +#else + mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: no swsscalar gaussian aa supported"); +#endif + break; + case 3: + table_x = calloc(spu->scaled_width, sizeof(scale_pixel)); + table_y = calloc(spu->scaled_height, sizeof(scale_pixel)); + if (!table_x || !table_y) { + mp_msg(MSGT_SPUDEC, MSGL_FATAL, "Fatal: spudec_draw_scaled: calloc failed\n"); + } + scale_table(0, 0, spu->width - 1, spu->scaled_width - 1, table_x); + scale_table(0, 0, spu->height - 1, spu->scaled_height - 1, table_y); + for (y = 0; y < spu->scaled_height; y++) + for (x = 0; x < spu->scaled_width; x++) + scale_image(x, y, table_x, table_y, spu); + free(table_x); + free(table_y); + break; + case 0: + /* no antialiasing */ + for (y = 0; y < spu->scaled_height; ++y) { + int unscaled_y = y * 0x100 / scaley; + int strides = spu->stride * unscaled_y; + int scaled_strides = spu->scaled_stride * y; + for (x = 0; x < spu->scaled_width; ++x) { + int unscaled_x = x * 0x100 / scalex; + spu->scaled_image[scaled_strides + x] = spu->image[strides + unscaled_x]; + spu->scaled_aimage[scaled_strides + x] = spu->aimage[strides + unscaled_x]; + } + } + break; + case 1: + { + /* Intermediate antialiasing. */ + for (y = 0; y < spu->scaled_height; ++y) { + const unsigned int unscaled_top = y * spu->orig_frame_height / dys; + unsigned int unscaled_bottom = (y + 1) * spu->orig_frame_height / dys; + if (unscaled_bottom >= spu->height) + unscaled_bottom = spu->height - 1; + for (x = 0; x < spu->scaled_width; ++x) { + const unsigned int unscaled_left = x * spu->orig_frame_width / dxs; + unsigned int unscaled_right = (x + 1) * spu->orig_frame_width / dxs; + unsigned int color = 0; + unsigned int alpha = 0; + unsigned int walkx, walky; + unsigned int base, tmp; + if (unscaled_right >= spu->width) + unscaled_right = spu->width - 1; + for (walky = unscaled_top; walky <= unscaled_bottom; ++walky) + for (walkx = unscaled_left; walkx <= unscaled_right; ++walkx) { + base = walky * spu->stride + walkx; + tmp = canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + base = y * spu->scaled_stride + x; + spu->scaled_image[base] = alpha ? color / alpha : 0; + spu->scaled_aimage[base] = + alpha * (1 + unscaled_bottom - unscaled_top) * (1 + unscaled_right - unscaled_left); + /* spu->scaled_aimage[base] = + alpha * dxs * dys / spu->orig_frame_width / spu->orig_frame_height; */ + if (spu->scaled_aimage[base]) { + spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; + if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) + spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; + } + } + } + } + break; + case 2: + { + /* Best antialiasing. Very slow. */ + /* Any pixel (x, y) represents pixels from the original + rectangular region comprised between the columns + unscaled_y and unscaled_y + 0x100 / scaley and the rows + unscaled_x and unscaled_x + 0x100 / scalex + + The original rectangular region that the scaled pixel + represents is cut in 9 rectangular areas like this: + + +---+-----------------+---+ + | 1 | 2 | 3 | + +---+-----------------+---+ + | | | | + | 4 | 5 | 6 | + | | | | + +---+-----------------+---+ + | 7 | 8 | 9 | + +---+-----------------+---+ + + The width of the left column is at most one pixel and + it is never null and its right column is at a pixel + boundary. The height of the top row is at most one + pixel it is never null and its bottom row is at a + pixel boundary. The width and height of region 5 are + integral values. The width of the right column is + what remains and is less than one pixel. The height + of the bottom row is what remains and is less than + one pixel. + + The row above 1, 2, 3 is unscaled_y. The row between + 1, 2, 3 and 4, 5, 6 is top_low_row. The row between 4, + 5, 6 and 7, 8, 9 is (unsigned int)unscaled_y_bottom. + The row beneath 7, 8, 9 is unscaled_y_bottom. + + The column left of 1, 4, 7 is unscaled_x. The column + between 1, 4, 7 and 2, 5, 8 is left_right_column. The + column between 2, 5, 8 and 3, 6, 9 is (unsigned + int)unscaled_x_right. The column right of 3, 6, 9 is + unscaled_x_right. */ + const double inv_scalex = (double) 0x100 / scalex; + const double inv_scaley = (double) 0x100 / scaley; + for (y = 0; y < spu->scaled_height; ++y) { + const double unscaled_y = y * inv_scaley; + const double unscaled_y_bottom = unscaled_y + inv_scaley; + const unsigned int top_low_row = FFMIN(unscaled_y_bottom, unscaled_y + 1.0); + const double top = top_low_row - unscaled_y; + const unsigned int height = unscaled_y_bottom > top_low_row + ? (unsigned int) unscaled_y_bottom - top_low_row + : 0; + const double bottom = unscaled_y_bottom > top_low_row + ? unscaled_y_bottom - floor(unscaled_y_bottom) + : 0.0; + for (x = 0; x < spu->scaled_width; ++x) { + const double unscaled_x = x * inv_scalex; + const double unscaled_x_right = unscaled_x + inv_scalex; + const unsigned int left_right_column = FFMIN(unscaled_x_right, unscaled_x + 1.0); + const double left = left_right_column - unscaled_x; + const unsigned int width = unscaled_x_right > left_right_column + ? (unsigned int) unscaled_x_right - left_right_column + : 0; + const double right = unscaled_x_right > left_right_column + ? unscaled_x_right - floor(unscaled_x_right) + : 0.0; + double color = 0.0; + double alpha = 0.0; + double tmp; + unsigned int base; + /* Now use these informations to compute a good alpha, + and lightness. The sum is on each of the 9 + region's surface and alpha and lightness. + + transformed alpha = sum(surface * alpha) / sum(surface) + transformed color = sum(surface * alpha * color) / sum(surface * alpha) + */ + /* 1: top left part */ + base = spu->stride * (unsigned int) unscaled_y; + tmp = left * top * canon_alpha(spu->aimage[base + (unsigned int) unscaled_x]); + alpha += tmp; + color += tmp * spu->image[base + (unsigned int) unscaled_x]; + /* 2: top center part */ + if (width > 0) { + unsigned int walkx; + for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { + base = spu->stride * (unsigned int) unscaled_y + walkx; + tmp = /* 1.0 * */ top * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + } + /* 3: top right part */ + if (right > 0.0) { + base = spu->stride * (unsigned int) unscaled_y + (unsigned int) unscaled_x_right; + tmp = right * top * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + /* 4: center left part */ + if (height > 0) { + unsigned int walky; + for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { + base = spu->stride * walky + (unsigned int) unscaled_x; + tmp = left /* * 1.0 */ * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + } + /* 5: center part */ + if (width > 0 && height > 0) { + unsigned int walky; + for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { + unsigned int walkx; + base = spu->stride * walky; + for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { + tmp = /* 1.0 * 1.0 * */ canon_alpha(spu->aimage[base + walkx]); + alpha += tmp; + color += tmp * spu->image[base + walkx]; + } + } + } + /* 6: center right part */ + if (right > 0.0 && height > 0) { + unsigned int walky; + for (walky = top_low_row; walky < (unsigned int) unscaled_y_bottom; ++walky) { + base = spu->stride * walky + (unsigned int) unscaled_x_right; + tmp = right /* * 1.0 */ * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + } + /* 7: bottom left part */ + if (bottom > 0.0) { + base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x; + tmp = left * bottom * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + /* 8: bottom center part */ + if (width > 0 && bottom > 0.0) { + unsigned int walkx; + base = spu->stride * (unsigned int) unscaled_y_bottom; + for (walkx = left_right_column; walkx < (unsigned int) unscaled_x_right; ++walkx) { + tmp = /* 1.0 * */ bottom * canon_alpha(spu->aimage[base + walkx]); + alpha += tmp; + color += tmp * spu->image[base + walkx]; + } + } + /* 9: bottom right part */ + if (right > 0.0 && bottom > 0.0) { + base = spu->stride * (unsigned int) unscaled_y_bottom + (unsigned int) unscaled_x_right; + tmp = right * bottom * canon_alpha(spu->aimage[base]); + alpha += tmp; + color += tmp * spu->image[base]; + } + /* Finally mix these transparency and brightness information suitably */ + base = spu->scaled_stride * y + x; + spu->scaled_image[base] = alpha > 0 ? color / alpha : 0; + spu->scaled_aimage[base] = alpha * scalex * scaley / 0x10000; + if (spu->scaled_aimage[base]) { + spu->scaled_aimage[base] = 256 - spu->scaled_aimage[base]; + if (spu->scaled_aimage[base] + spu->scaled_image[base] > 255) + spu->scaled_image[base] = 256 - spu->scaled_aimage[base]; + } + } + } + } + } +nothing_to_do: + /* Kludge: draw_alpha needs width multiple of 8. */ + if (spu->scaled_width < spu->scaled_stride) + for (y = 0; y < spu->scaled_height; ++y) { + memset(spu->scaled_aimage + y * spu->scaled_stride + spu->scaled_width, 0, + spu->scaled_stride - spu->scaled_width); + } + spu->scaled_frame_width = dxs; + spu->scaled_frame_height = dys; + } + } + if (spu->scaled_image){ + switch (spu_alignment) { + case 0: + spu->scaled_start_row = dys*sub_pos/100; + if (spu->scaled_start_row + spu->scaled_height > dys) + spu->scaled_start_row = dys - spu->scaled_height; + break; + case 1: + spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height/2; + if (sub_pos >= 50 && spu->scaled_start_row + spu->scaled_height > dys) + spu->scaled_start_row = dys - spu->scaled_height; + break; + case 2: + spu->scaled_start_row = dys*sub_pos/100 - spu->scaled_height; + break; + } + draw_alpha(spu->scaled_start_col, spu->scaled_start_row, spu->scaled_width, spu->scaled_height, + spu->scaled_image, spu->scaled_aimage, spu->scaled_stride); + spu->spu_changed = 0; + } + } + } + else + { + mp_msg(MSGT_SPUDEC,MSGL_DBG2,"SPU not displayed: start_pts=%d end_pts=%d now_pts=%d\n", + spu->start_pts, spu->end_pts, spu->now_pts); + } +} + +void spudec_update_palette(void * this, unsigned int *palette) +{ + spudec_handle_t *spu = this; + if (spu && palette) { + memcpy(spu->global_palette, palette, sizeof(spu->global_palette)); +#if 0 // R: OSD stuff removed + if(spu->hw_spu) + spu->hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); +#endif + } +} + +void spudec_set_font_factor(void * this, double factor) +{ + spudec_handle_t *spu = this; + spu->font_start_level = (int)(0xF0-(0xE0*factor)); +} + +#ifndef AV_RB32 // R: AV_RB32 for older ffmpeg (libavutil) releases +#ifndef __GNUC__ // only implemented the GCC version of AV_RB32 +#error "Get a newer ffmpeg (libavutil) version" +#endif + +/* +code taken from ffmpeg/libavutil. intreadwrite.h and bswap.h + +bswap.h is copyright (C) 2006 by Michael Niedermayer <[email protected]> +intreadwrite.h does not contain a specific copyright notice. + +the code is licensed under LGPL 2 with the following license header + +FFmpeg is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +FFmpeg is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with FFmpeg; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +union unaligned_32 { uint32_t l; } __attribute__((packed)) __attribute__((may_alias)); +#define AV_RN32(p) (((const union unaligned_32 *) (p))->l) + +#ifdef AV_HAVE_BIGENDIAN // TODO add detection + +#define AV_RB32(p) AV_RN32(p) + +#else // little endian +static __attribute__((always_inline)) inline uint32_t __attribute__((const)) av_bswap32(uint32_t x) { + x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); + x= (x>>16) | (x<<16); + return x; +} + +#define AV_RB32(p) av_bswap32(AV_RN32(p)) + +#endif // AV_HAVE_BIG_ENDIAN +#endif // AV_RB32 + +static void spudec_parse_extradata(spudec_handle_t *this, + uint8_t *extradata, int extradata_len) +{ + uint8_t *buffer, *ptr; + unsigned int *pal = this->global_palette, *cuspal = this->cuspal; + unsigned int tridx; + int i; + + if (extradata_len == 16*4) { + for (i=0; i<16; i++) + pal[i] = AV_RB32(extradata + i*4); + this->auto_palette = 0; + return; + } + + if (!(ptr = buffer = malloc(extradata_len+1))) + return; + memcpy(buffer, extradata, extradata_len); + buffer[extradata_len] = 0; + + do { + if (*ptr == '#') + continue; + if (!strncmp(ptr, "size: ", 6)) + sscanf(ptr + 6, "%dx%d", &this->orig_frame_width, &this->orig_frame_height); + if (!strncmp(ptr, "palette: ", 9) && + sscanf(ptr + 9, "%x, %x, %x, %x, %x, %x, %x, %x, " + "%x, %x, %x, %x, %x, %x, %x, %x", + &pal[ 0], &pal[ 1], &pal[ 2], &pal[ 3], + &pal[ 4], &pal[ 5], &pal[ 6], &pal[ 7], + &pal[ 8], &pal[ 9], &pal[10], &pal[11], + &pal[12], &pal[13], &pal[14], &pal[15]) == 16) { + for (i=0; i<16; i++) + pal[i] = vobsub_palette_to_yuv(pal[i]); + this->auto_palette = 0; + } + if (!strncasecmp(ptr, "forced subs: on", 15)) + this->forced_subs_only = 1; + if (!strncmp(ptr, "custom colors: ON, tridx: ", 26) && + sscanf(ptr + 26, "%x, colors: %x, %x, %x, %x", + &tridx, cuspal+0, cuspal+1, cuspal+2, cuspal+3) == 5) { + for (i=0; i<4; i++) { + cuspal[i] = vobsub_rgb_to_yuv(cuspal[i]); + if (tridx & (1 << (12-4*i))) + cuspal[i] |= 1 << 31; + } + this->custom = 1; + } + } while ((ptr=strchr(ptr,'\n')) && *++ptr); + + free(buffer); +} + +void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len) +{ + spudec_handle_t *this = calloc(1, sizeof(spudec_handle_t)); + if (this){ + this->orig_frame_height = frame_height; + this->orig_frame_width = frame_width; + // set up palette: + if (palette) + memcpy(this->global_palette, palette, sizeof(this->global_palette)); + else + this->auto_palette = 1; + if (extradata) + spudec_parse_extradata(this, extradata, extradata_len); + /* XXX Although the video frame is some size, the SPU frame is + always maximum size i.e. 720 wide and 576 or 480 high */ + // For HD files in MKV the VobSub resolution can be higher though, + // see largeres_vobsub.mkv + if (this->orig_frame_width <= 720 && this->orig_frame_height <= 576) { + this->orig_frame_width = 720; + if (this->orig_frame_height == 480 || this->orig_frame_height == 240) + this->orig_frame_height = 480; + else + this->orig_frame_height = 576; + } + } + else + mp_msg(MSGT_SPUDEC,MSGL_FATAL, "FATAL: spudec_init: calloc"); + return this; +} + +void *spudec_new(unsigned int *palette) +{ + return spudec_new_scaled(palette, 0, 0, NULL, 0); +} + +void spudec_free(void *this) +{ + spudec_handle_t *spu = this; + if (spu) { + while (spu->queue_head) + spudec_free_packet(spudec_dequeue_packet(spu)); + free(spu->packet); + spu->packet = NULL; + free(spu->scaled_image); + spu->scaled_image = NULL; + free(spu->image); + spu->image = NULL; + spu->aimage = NULL; + free(spu->pal_image); + spu->pal_image = NULL; + spu->image_size = 0; + spu->pal_width = spu->pal_height = 0; + free(spu); + } +} + +#if 0 // R: not necessary +void spudec_set_hw_spu(void *this, const vo_functions_t *hw_spu) +{ + spudec_handle_t *spu = this; + if (!spu) + return; + spu->hw_spu = hw_spu; + hw_spu->control(VOCTRL_SET_SPU_PALETTE,spu->global_palette); +} +#endif + +#define MP_NOPTS_VALUE (-1LL<<63) //both int64_t and double should be able to represent this exactly + +/** + * palette must contain at least 256 32-bit entries, otherwise crashes + * are possible + */ +void spudec_set_paletted(void *this, const uint8_t *pal_img, int pal_stride, + const void *palette, + int x, int y, int w, int h, + double pts, double endpts) +{ + int i; + uint16_t g8a8_pal[256]; + packet_t *packet; + const uint32_t *pal = palette; + spudec_handle_t *spu = this; + uint8_t *img; + uint8_t *aimg; + int stride = (w + 7) & ~7; + if ((unsigned)w >= 0x8000 || (unsigned)h > 0x4000) + return; + packet = calloc(1, sizeof(packet_t)); + packet->is_decoded = 1; + packet->width = w; + packet->height = h; + packet->stride = stride; + packet->start_col = x; + packet->start_row = y; + packet->data_len = 2 * stride * h; + if (packet->data_len) { // size 0 is a special "clear" packet + packet->packet = malloc(packet->data_len); + img = packet->packet; + aimg = packet->packet + stride * h; + for (i = 0; i < 256; i++) { + uint32_t pixel = pal[i]; + int alpha = pixel >> 24; + int gray = (((pixel & 0x000000ff) >> 0) + + ((pixel & 0x0000ff00) >> 7) + + ((pixel & 0x00ff0000) >> 16)) >> 2; + gray = FFMIN(gray, alpha); + g8a8_pal[i] = (-alpha << 8) | gray; + } + pal2gray_alpha(g8a8_pal, pal_img, pal_stride, + img, aimg, stride, w, h); + } + packet->start_pts = 0; + packet->end_pts = 0x7fffffff; + if (pts != MP_NOPTS_VALUE) + packet->start_pts = pts * 90000; + if (endpts != MP_NOPTS_VALUE) + packet->end_pts = endpts * 90000; + spudec_queue_packet(spu, packet); +} + +// R: added to extract data +void spudec_get_data(void *this, const unsigned char **image, size_t *image_size, unsigned *width, unsigned *height, + unsigned *stride, unsigned *start_pts, unsigned *end_pts) +{ + spudec_handle_t *spu = this; + *image = spu->image; + *image_size = spu->image_size; + *width = spu->width; + *height = spu->height; + *stride = spu->stride; + *start_pts = spu->start_pts; + *end_pts = spu->end_pts; +} diff --git a/mplayer/spudec.h b/mplayer/spudec.h new file mode 100644 index 0000000..844aed7 --- /dev/null +++ b/mplayer/spudec.h @@ -0,0 +1,58 @@ +/* + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef MPLAYER_SPUDEC_H +#define MPLAYER_SPUDEC_H + +//#include "libvo/video_out.h" +#include <stdint.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +void spudec_heartbeat(void *self, unsigned int pts100); +void spudec_assemble(void *self, unsigned char *packet, unsigned int len, int pts100); +void spudec_draw(void *self, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)); +void spudec_draw_scaled(void *self, unsigned int dxs, unsigned int dys, void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride)); +int spudec_apply_palette_crop(void *self, uint32_t palette, int sx, int ex, int sy, int ey); +void spudec_update_palette(void *self, unsigned int *palette); +void *spudec_new_scaled(unsigned int *palette, unsigned int frame_width, unsigned int frame_height, uint8_t *extradata, int extradata_len); +void *spudec_new(unsigned int *palette); +void spudec_free(void *self); +void spudec_reset(void *self); // called after seek +int spudec_visible(void *self); // check if spu is visible +void spudec_set_font_factor(void * self, double factor); // sets the equivalent to ffactor +//void spudec_set_hw_spu(void *self, const vo_functions_t *hw_spu); +int spudec_changed(void *self); +void spudec_calc_bbox(void *me, unsigned int dxs, unsigned int dys, unsigned int* bbox); +void spudec_set_forced_subs_only(void * const self, const unsigned int flag); +void spudec_set_paletted(void *self, const uint8_t *pal_img, int stride, + const void *palette, + int x, int y, int w, int h, + double pts, double endpts); +/// call this after spudec_assemble and spudec_heartbeat to get the packet data +void spudec_get_data(void *self, const unsigned char **image, size_t *image_size, unsigned *width, unsigned *height, + unsigned *stride, unsigned *start_pts, unsigned *end_pts); + +#ifdef __cplusplus +} +#endif + +#endif /* MPLAYER_SPUDEC_H */ diff --git a/mplayer/unrar_exec.c b/mplayer/unrar_exec.c new file mode 100644 index 0000000..6de8c59 --- /dev/null +++ b/mplayer/unrar_exec.c @@ -0,0 +1,235 @@ +/* + * List files and extract file from rars by using external executable unrar. + * + * Copyright (C) 2005 Jindrich Makovicka <makovick gmail com> + * Copyright (C) 2007 Ulion <ulion2002 gmail com> + * + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <sys/wait.h> +#include <unistd.h> +#include <fcntl.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <locale.h> +#include "unrar_exec.h" + +#include "mp_msg.h" + +#define UNRAR_LIST 1 +#define UNRAR_EXTRACT 2 + +char* unrar_executable = NULL; + +static FILE* launch_pipe(pid_t *apid, const char *executable, int action, + const char *archive, const char *filename) +{ + if (!executable || access(executable, R_OK | X_OK)) return NULL; + if (access(archive, R_OK)) return NULL; + { + int mypipe[2]; + pid_t pid; + + if (pipe(mypipe)) { + mp_msg(MSGT_GLOBAL, MSGL_ERR, "UnRAR: Cannot create pipe.\n"); + return NULL; + } + + pid = fork(); + if (pid == 0) { + /* This is the child process. Execute the unrar executable. */ + close(mypipe[0]); + // Close MPlayer's stdin, stdout and stderr so the unrar binary + // can not mess them up. + // TODO: Close all other files except the pipe. + close(0); close(1); close(2); + // Assign new stdin, stdout and stderr and check they actually got the + // right descriptors. + if (open("/dev/null", O_RDONLY) != 0 || dup(mypipe[1]) != 1 + || open("/dev/null", O_WRONLY) != 2) + _exit(EXIT_FAILURE); + if (action == UNRAR_LIST) + execl(executable, executable, "v", archive, NULL); + else if (action == UNRAR_EXTRACT) + execl(executable, executable, "p", "-inul", "-p-", + archive,filename,NULL); + mp_msg(MSGT_GLOBAL, MSGL_ERR, "UnRAR: Cannot execute %s\n", executable); + _exit(EXIT_FAILURE); + } + if (pid < 0) { + /* The fork failed. Report failure. */ + mp_msg(MSGT_GLOBAL, MSGL_ERR, "UnRAR: Fork failed\n"); + return NULL; + } + /* This is the parent process. Prepare the pipe stream. */ + close(mypipe[1]); + *apid = pid; + if (action == UNRAR_LIST) + mp_msg(MSGT_GLOBAL, MSGL_V, + "UnRAR: call unrar with command line: %s v %s\n", + executable, archive); + else if (action == UNRAR_EXTRACT) + mp_msg(MSGT_GLOBAL, MSGL_V, + "UnRAR: call unrar with command line: %s p -inul -p- %s %s\n", + executable, archive, filename); + return fdopen(mypipe[0], "r"); + } +} + +#define ALLOC_INCR 1 * 1024 * 1024 +int unrar_exec_get(unsigned char **output, unsigned long *size, + const char *filename, const char *rarfile) +{ + int bufsize = ALLOC_INCR, bytesread; + pid_t pid; + int status = 0; + FILE *rar_pipe; + + rar_pipe=launch_pipe(&pid,unrar_executable,UNRAR_EXTRACT,rarfile,filename); + if (!rar_pipe) return 0; + + *size = 0; + + *output = malloc(bufsize); + + while (*output) { + bytesread=fread(*output+*size, 1, bufsize-*size, rar_pipe); + if (bytesread <= 0) + break; + *size += bytesread; + if (*size == bufsize) { + char *p; + bufsize += ALLOC_INCR; + p = realloc(*output, bufsize); + if (!p) + free(*output); + *output = p; + } + } + fclose(rar_pipe); + pid = waitpid(pid, &status, 0); + if (!*output || !*size || (pid == -1 && errno != ECHILD) || + (pid > 0 && status)) { + free(*output); + *output = NULL; + *size = 0; + return 0; + } + if (bufsize > *size) { + char *p = realloc(*output, *size); + if (p) + *output = p; + } + mp_msg(MSGT_GLOBAL, MSGL_V, "UnRAR: got file %s len %lu\n", filename,*size); + return 1; +} + +#define PARSE_NAME 0 +#define PARSE_PROPS 1 + +int unrar_exec_list(const char *rarfile, ArchiveList_struct **list) +{ + char buf[1024], fname[1024]; + char *p; + pid_t pid; + int status = 0, file_num = -1, ignore_next_line = 0, state = PARSE_NAME; + FILE *rar_pipe; + ArchiveList_struct *alist = NULL, *current = NULL, *new; + + rar_pipe = launch_pipe(&pid, unrar_executable, UNRAR_LIST, rarfile, NULL); + if (!rar_pipe) return -1; + while (fgets(buf, sizeof(buf), rar_pipe)) { + int packsize, unpsize, ratio, day, month, year, hour, min; + int llen = strlen(buf); + // If read nothing, we got a file_num -1. + if (file_num == -1) + file_num = 0; + if (buf[llen-1] != '\n') + // The line is too long, ignore it. + ignore_next_line = 2; + if (ignore_next_line) { + --ignore_next_line; + state = PARSE_NAME; + continue; + } + // Trim the line. + while (llen > 0 && strchr(" \t\n\r\v\f", buf[llen-1])) + --llen; + buf[llen] = '\0'; + p = buf; + while (*p && strchr(" \t\n\r\v\f", *p)) + ++p; + if (!*p) { + state = PARSE_NAME; + continue; + } + + if (state == PARSE_PROPS && sscanf(p, "%d %d %d%% %d-%d-%d %d:%d", + &unpsize, &packsize, &ratio, &day, + &month, &year, &hour, &min) == 8) { + new = calloc(1, sizeof(ArchiveList_struct)); + if (!new) { + file_num = -1; + break; + } + if (!current) + alist = new; + else + current->next = new; + current = new; + current->item.Name = strdup(fname); + state = PARSE_NAME; + if (!current->item.Name) { + file_num = -1; + break; + } + current->item.PackSize = packsize; + current->item.UnpSize = unpsize; + ++file_num; + continue; + } + strcpy(fname, p); + state = PARSE_PROPS; + } + fclose(rar_pipe); + pid = waitpid(pid, &status, 0); + if (file_num < 0 || (pid == -1 && errno != ECHILD) || + (pid > 0 && status)) { + unrar_exec_freelist(alist); + return -1; + } + if (!alist) + return -1; + *list = alist; + mp_msg(MSGT_GLOBAL, MSGL_V, "UnRAR: list got %d files\n", file_num); + return file_num; +} + +void unrar_exec_freelist(ArchiveList_struct *list) +{ + ArchiveList_struct* tmp; + + while (list) { + tmp = list->next; + free(list->item.Name); + free(list); + list = tmp; + } +} diff --git a/mplayer/unrar_exec.h b/mplayer/unrar_exec.h new file mode 100644 index 0000000..ad67f0e --- /dev/null +++ b/mplayer/unrar_exec.h @@ -0,0 +1,62 @@ +/* + * List files and extract file from rars by using external executable unrar. + * + * Copyright (C) 2005 Jindrich Makovicka <makovick gmail com> + * Copyright (C) 2007 Ulion <ulion2002 gmail com> + * + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef MPLAYER_UNRAR_EXEC_H +#define MPLAYER_UNRAR_EXEC_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct RAR_archive_entry +{ + char *Name; + unsigned long PackSize; + unsigned long UnpSize; + unsigned long FileCRC; + unsigned long FileTime; + unsigned char UnpVer; + unsigned char Method; + unsigned long FileAttr; +}; + +typedef struct archivelist +{ + struct RAR_archive_entry item; + struct archivelist *next; +} ArchiveList_struct; + +extern char* unrar_executable; + +int unrar_exec_get(unsigned char **output, unsigned long *size, + const char *filename, const char *rarfile); + +int unrar_exec_list(const char *rarfile, ArchiveList_struct **list); + +void unrar_exec_freelist(ArchiveList_struct *list); + +#ifdef __cplusplus +} +#endif + +#endif /* MPLAYER_UNRAR_EXEC_H */ diff --git a/mplayer/vobsub.c b/mplayer/vobsub.c new file mode 100644 index 0000000..cc962ee --- /dev/null +++ b/mplayer/vobsub.c @@ -0,0 +1,1421 @@ +/* -*- mode: c; c-basic-offset: 4 -*- + * Some code freely inspired from VobSub <URL:http://vobsub.edensrising.com>, + * with kind permission from Gabest <[email protected]> + * + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <ctype.h> +#include <errno.h> +#include <inttypes.h> +#include <limits.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/stat.h> +#include <sys/types.h> + +//#include "config.h" +#define CONFIG_UNRAR_EXEC 1 // moved from config.h +//#include "mpcommon.h" +#include "vobsub.h" +#include "spudec.h" +#include "mp_msg.h" +#include "unrar_exec.h" +#include <libavutil/common.h> // use system's libavutil + +// Record the original -vobsubid set by commandline, since vobsub_id will be +// overridden if slang match any of vobsub streams. +static int vobsubid = -2; + +int vobsub_id = 0; // moved from mpcommon.h/mplayer.c + +/********************************************************************** + * RAR stream handling + * The RAR file must have the same basename as the file to open + **********************************************************************/ +#ifdef CONFIG_UNRAR_EXEC +typedef struct { + FILE *file; + unsigned char *data; + unsigned long size; + unsigned long pos; +} rar_stream_t; + +static rar_stream_t *rar_open(const char *const filename, + const char *const mode) +{ + rar_stream_t *stream; + /* unrar_exec can only read */ + if (strcmp("r", mode) && strcmp("rb", mode)) { + errno = EINVAL; + return NULL; + } + stream = malloc(sizeof(rar_stream_t)); + if (stream == NULL) + return NULL; + /* first try normal access */ + stream->file = fopen(filename, mode); + if (stream->file == NULL) { + char *rar_filename; + const char *p; + int rc; + /* Guess the RAR archive filename */ + rar_filename = NULL; + p = strrchr(filename, '.'); + if (p) { + ptrdiff_t l = p - filename; + rar_filename = malloc(l + 5); + if (rar_filename == NULL) { + free(stream); + return NULL; + } + strncpy(rar_filename, filename, l); + strcpy(rar_filename + l, ".rar"); + } else { + rar_filename = malloc(strlen(filename) + 5); + if (rar_filename == NULL) { + free(stream); + return NULL; + } + strcpy(rar_filename, filename); + strcat(rar_filename, ".rar"); + } + /* get rid of the path if there is any */ + if ((p = strrchr(filename, '/')) == NULL) { + p = filename; + } else { + p++; + } + rc = unrar_exec_get(&stream->data, &stream->size, p, rar_filename); + if (!rc) { + /* There is no matching filename in the archive. However, sometimes + * the files we are looking for have been given arbitrary names in the archive. + * Let's look for a file with an exact match in the extension only. */ + int i, num_files, name_len; + ArchiveList_struct *list, *lp; + num_files = unrar_exec_list(rar_filename, &list); + if (num_files > 0) { + char *demanded_ext; + demanded_ext = strrchr (p, '.'); + if (demanded_ext) { + int demanded_ext_len = strlen (demanded_ext); + for (i = 0, lp = list; i < num_files; i++, lp = lp->next) { + name_len = strlen (lp->item.Name); + if (name_len >= demanded_ext_len && !strcasecmp (lp->item.Name + name_len - demanded_ext_len, demanded_ext)) { + rc = unrar_exec_get(&stream->data, &stream->size, + lp->item.Name, rar_filename); + if (rc) + break; + } + } + } + unrar_exec_freelist(list); + } + if (!rc) { + free(rar_filename); + free(stream); + return NULL; + } + } + + free(rar_filename); + stream->pos = 0; + } + return stream; +} + +static int rar_close(rar_stream_t *stream) +{ + if (stream->file) + return fclose(stream->file); + free(stream->data); + return 0; +} + +static int rar_eof(rar_stream_t *stream) +{ + if (stream->file) + return feof(stream->file); + return stream->pos >= stream->size; +} + +static long rar_tell(rar_stream_t *stream) +{ + if (stream->file) + return ftell(stream->file); + return stream->pos; +} + +static int rar_seek(rar_stream_t *stream, long offset, int whence) +{ + if (stream->file) + return fseek(stream->file, offset, whence); + switch (whence) { + case SEEK_SET: + if (offset < 0) { + errno = EINVAL; + return -1; + } + stream->pos = offset; + break; + case SEEK_CUR: + if (offset < 0 && stream->pos < (unsigned long) -offset) { + errno = EINVAL; + return -1; + } + stream->pos += offset; + break; + case SEEK_END: + if (offset < 0 && stream->size < (unsigned long) -offset) { + errno = EINVAL; + return -1; + } + stream->pos = stream->size + offset; + break; + default: + errno = EINVAL; + return -1; + } + return 0; +} + +static int rar_getc(rar_stream_t *stream) +{ + if (stream->file) + return getc(stream->file); + if (rar_eof(stream)) + return EOF; + return stream->data[stream->pos++]; +} + +static size_t rar_read(void *ptr, size_t size, size_t nmemb, + rar_stream_t *stream) +{ + size_t res; + unsigned long remain; + if (stream->file) + return fread(ptr, size, nmemb, stream->file); + if (rar_eof(stream)) + return 0; + res = size * nmemb; + remain = stream->size - stream->pos; + if (res > remain) + res = remain / size * size; + memcpy(ptr, stream->data + stream->pos, res); + stream->pos += res; + res /= size; + return res; +} + +#else +typedef FILE rar_stream_t; +#define rar_open fopen +#define rar_close fclose +#define rar_eof feof +#define rar_tell ftell +#define rar_seek fseek +#define rar_getc getc +#define rar_read fread +#endif + +/**********************************************************************/ + +static ssize_t vobsub_getline(char **lineptr, size_t *n, rar_stream_t *stream) +{ + size_t res = 0; + int c; + if (*lineptr == NULL) { + *lineptr = malloc(4096); + if (*lineptr) + *n = 4096; + } else if (*n == 0) { + char *tmp = realloc(*lineptr, 4096); + if (tmp) { + *lineptr = tmp; + *n = 4096; + } + } + if (*lineptr == NULL || *n == 0) + return -1; + + for (c = rar_getc(stream); c != EOF; c = rar_getc(stream)) { + if (res + 1 >= *n) { + char *tmp = realloc(*lineptr, *n * 2); + if (tmp == NULL) + return -1; + *lineptr = tmp; + *n *= 2; + } + (*lineptr)[res++] = c; + if (c == '\n') { + (*lineptr)[res] = 0; + return res; + } + } + if (res == 0) + return -1; + (*lineptr)[res] = 0; + return res; +} + +/********************************************************************** + * MPEG parsing + **********************************************************************/ + +typedef struct { + rar_stream_t *stream; + unsigned int pts; + int aid; + unsigned char *packet; + unsigned int packet_reserve; + unsigned int packet_size; + int padding_was_here; + int merge; +} mpeg_t; + +static mpeg_t *mpeg_open(const char *filename) +{ + mpeg_t *res = malloc(sizeof(mpeg_t)); + int err = res == NULL; + if (!err) { + res->pts = 0; + res->aid = -1; + res->packet = NULL; + res->packet_size = 0; + res->packet_reserve = 0; + res->padding_was_here = 1; + res->merge = 0; + res->stream = rar_open(filename, "rb"); + err = res->stream == NULL; + if (err) + perror("fopen Vobsub file failed"); + if (err) + free(res); + } + return err ? NULL : res; +} + +static void mpeg_free(mpeg_t *mpeg) +{ + if (mpeg->packet) + free(mpeg->packet); + if (mpeg->stream) + rar_close(mpeg->stream); + free(mpeg); +} + +static int mpeg_eof(mpeg_t *mpeg) +{ + return rar_eof(mpeg->stream); +} + +static off_t mpeg_tell(mpeg_t *mpeg) +{ + return rar_tell(mpeg->stream); +} + +static int mpeg_run(mpeg_t *mpeg) +{ + unsigned int len, idx, version; + int c; + /* Goto start of a packet, it starts with 0x000001?? */ + const unsigned char wanted[] = { 0, 0, 1 }; + unsigned char buf[5]; + + mpeg->aid = -1; + mpeg->packet_size = 0; + if (rar_read(buf, 4, 1, mpeg->stream) != 1) + return -1; + while (memcmp(buf, wanted, sizeof(wanted)) != 0) { + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + memmove(buf, buf + 1, 3); + buf[3] = c; + } + switch (buf[3]) { + case 0xb9: /* System End Code */ + break; + case 0xba: /* Packet start code */ + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + if ((c & 0xc0) == 0x40) + version = 4; + else if ((c & 0xf0) == 0x20) + version = 2; + else { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Unsupported MPEG version: 0x%02x\n", c); + return -1; + } + if (version == 4) { + if (rar_seek(mpeg->stream, 9, SEEK_CUR)) + return -1; + } else if (version == 2) { + if (rar_seek(mpeg->stream, 7, SEEK_CUR)) + return -1; + } else + abort(); + if (!mpeg->padding_was_here) + mpeg->merge = 1; + break; + case 0xbd: /* packet */ + if (rar_read(buf, 2, 1, mpeg->stream) != 1) + return -1; + mpeg->padding_was_here = 0; + len = buf[0] << 8 | buf[1]; + idx = mpeg_tell(mpeg); + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + if ((c & 0xC0) == 0x40) { /* skip STD scale & size */ + if (rar_getc(mpeg->stream) < 0) + return -1; + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + } + if ((c & 0xf0) == 0x20) { /* System-1 stream timestamp */ + /* Do we need this? */ + abort(); + } else if ((c & 0xf0) == 0x30) { + /* Do we need this? */ + abort(); + } else if ((c & 0xc0) == 0x80) { /* System-2 (.VOB) stream */ + unsigned int pts_flags, hdrlen, dataidx; + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + pts_flags = c; + c = rar_getc(mpeg->stream); + if (c < 0) + return -1; + hdrlen = c; + dataidx = mpeg_tell(mpeg) + hdrlen; + if (dataidx > idx + len) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "Invalid header length: %d (total length: %d, idx: %d, dataidx: %d)\n", + hdrlen, len, idx, dataidx); + return -1; + } + if ((pts_flags & 0xc0) == 0x80) { + if (rar_read(buf, 5, 1, mpeg->stream) != 1) + return -1; + if (!(((buf[0] & 0xf0) == 0x20) && (buf[0] & 1) && (buf[2] & 1) && (buf[4] & 1))) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub PTS error: 0x%02x %02x%02x %02x%02x \n", + buf[0], buf[1], buf[2], buf[3], buf[4]); + mpeg->pts = 0; + } else + mpeg->pts = ((buf[0] & 0x0e) << 29 | buf[1] << 22 | (buf[2] & 0xfe) << 14 + | buf[3] << 7 | (buf[4] >> 1)); + } else /* if ((pts_flags & 0xc0) == 0xc0) */ { + /* what's this? */ + /* abort(); */ + } + rar_seek(mpeg->stream, dataidx, SEEK_SET); + mpeg->aid = rar_getc(mpeg->stream); + if (mpeg->aid < 0) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "Bogus aid %d\n", mpeg->aid); + return -1; + } + mpeg->packet_size = len - ((unsigned int) mpeg_tell(mpeg) - idx); + if (mpeg->packet_reserve < mpeg->packet_size) { + if (mpeg->packet) + free(mpeg->packet); + mpeg->packet = malloc(mpeg->packet_size); + if (mpeg->packet) + mpeg->packet_reserve = mpeg->packet_size; + } + if (mpeg->packet == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); + mpeg->packet_reserve = 0; + mpeg->packet_size = 0; + return -1; + } + if (rar_read(mpeg->packet, mpeg->packet_size, 1, mpeg->stream) != 1) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "fread failure"); + mpeg->packet_size = 0; + return -1; + } + idx = len; + } + break; + case 0xbe: /* Padding */ + if (rar_read(buf, 2, 1, mpeg->stream) != 1) + return -1; + len = buf[0] << 8 | buf[1]; + if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) + return -1; + mpeg->padding_was_here = 1; + break; + default: + if (0xc0 <= buf[3] && buf[3] < 0xf0) { + /* MPEG audio or video */ + if (rar_read(buf, 2, 1, mpeg->stream) != 1) + return -1; + len = buf[0] << 8 | buf[1]; + if (len > 0 && rar_seek(mpeg->stream, len, SEEK_CUR)) + return -1; + } else { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "unknown header 0x%02X%02X%02X%02X\n", + buf[0], buf[1], buf[2], buf[3]); + return -1; + } + } + return 0; +} + +/********************************************************************** + * Packet queue + **********************************************************************/ + +typedef struct { + unsigned int pts100; + off_t filepos; + unsigned int size; + unsigned char *data; +} packet_t; + +typedef struct { + char *id; + packet_t *packets; + unsigned int packets_reserve; + unsigned int packets_size; + unsigned int current_index; +} packet_queue_t; + +static void packet_construct(packet_t *pkt) +{ + pkt->pts100 = 0; + pkt->filepos = 0; + pkt->size = 0; + pkt->data = NULL; +} + +static void packet_destroy(packet_t *pkt) +{ + if (pkt->data) + free(pkt->data); +} + +static void packet_queue_construct(packet_queue_t *queue) +{ + queue->id = NULL; + queue->packets = NULL; + queue->packets_reserve = 0; + queue->packets_size = 0; + queue->current_index = 0; +} + +static void packet_queue_destroy(packet_queue_t *queue) +{ + if (queue->packets) { + while (queue->packets_size--) + packet_destroy(queue->packets + queue->packets_size); + free(queue->packets); + } + return; +} + +/* Make sure there is enough room for needed_size packets in the + packet queue. */ +static int packet_queue_ensure(packet_queue_t *queue, unsigned int needed_size) +{ + if (queue->packets_reserve < needed_size) { + if (queue->packets) { + packet_t *tmp = realloc(queue->packets, 2 * queue->packets_reserve * sizeof(packet_t)); + if (tmp == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_FATAL, "realloc failure"); + return -1; + } + queue->packets = tmp; + queue->packets_reserve *= 2; + } else { + queue->packets = malloc(sizeof(packet_t)); + if (queue->packets == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_FATAL, "malloc failure"); + return -1; + } + queue->packets_reserve = 1; + } + } + return 0; +} + +/* add one more packet */ +static int packet_queue_grow(packet_queue_t *queue) +{ + if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) + return -1; + packet_construct(queue->packets + queue->packets_size); + ++queue->packets_size; + return 0; +} + +/* insert a new packet, duplicating pts from the current one */ +static int packet_queue_insert(packet_queue_t *queue) +{ + packet_t *pkts; + if (packet_queue_ensure(queue, queue->packets_size + 1) < 0) + return -1; + /* XXX packet_size does not reflect the real thing here, it will be updated a bit later */ + memmove(queue->packets + queue->current_index + 2, + queue->packets + queue->current_index + 1, + sizeof(packet_t) * (queue->packets_size - queue->current_index - 1)); + pkts = queue->packets + queue->current_index; + ++queue->packets_size; + ++queue->current_index; + packet_construct(pkts + 1); + pkts[1].pts100 = pkts[0].pts100; + pkts[1].filepos = pkts[0].filepos; + return 0; +} + +/********************************************************************** + * Vobsub + **********************************************************************/ + +typedef struct { + unsigned int palette[16]; + int delay; + unsigned int have_palette; + unsigned int orig_frame_width, orig_frame_height; + unsigned int origin_x, origin_y; + /* index */ + packet_queue_t *spu_streams; + unsigned int spu_streams_size; + unsigned int spu_streams_current; + unsigned int spu_valid_streams_size; +} vobsub_t; + +/* Make sure that the spu stream idx exists. */ +static int vobsub_ensure_spu_stream(vobsub_t *vob, unsigned int index) +{ + if (index >= vob->spu_streams_size) { + /* This is a new stream */ + if (vob->spu_streams) { + packet_queue_t *tmp = realloc(vob->spu_streams, (index + 1) * sizeof(packet_queue_t)); + if (tmp == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: realloc failure"); + return -1; + } + vob->spu_streams = tmp; + } else { + vob->spu_streams = malloc((index + 1) * sizeof(packet_queue_t)); + if (vob->spu_streams == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "vobsub_ensure_spu_stream: malloc failure"); + return -1; + } + } + while (vob->spu_streams_size <= index) { + packet_queue_construct(vob->spu_streams + vob->spu_streams_size); + ++vob->spu_streams_size; + } + } + return 0; +} + +static int vobsub_add_id(vobsub_t *vob, const char *id, size_t idlen, + const unsigned int index) +{ + if (vobsub_ensure_spu_stream(vob, index) < 0) + return -1; + if (id && idlen) { + if (vob->spu_streams[index].id) + free(vob->spu_streams[index].id); + vob->spu_streams[index].id = malloc(idlen + 1); + if (vob->spu_streams[index].id == NULL) { + mp_msg(MSGT_VOBSUB, MSGL_FATAL, "vobsub_add_id: malloc failure"); + return -1; + } + vob->spu_streams[index].id[idlen] = 0; + memcpy(vob->spu_streams[index].id, id, idlen); + } + vob->spu_streams_current = index; + mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VOBSUB_ID=%d\n", index); + if (id && idlen) + mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VSID_%d_LANG=%s\n", index, vob->spu_streams[index].id); + mp_msg(MSGT_VOBSUB, MSGL_V, "[vobsub] subtitle (vobsubid): %d language %s\n", + index, vob->spu_streams[index].id); + return 0; +} + +static int vobsub_add_timestamp(vobsub_t *vob, off_t filepos, int ms) +{ + packet_queue_t *queue; + packet_t *pkt; + if (vob->spu_streams == 0) { + mp_msg(MSGT_VOBSUB, MSGL_WARN, "[vobsub] warning, binning some index entries. Check your index file\n"); + return -1; + } + queue = vob->spu_streams + vob->spu_streams_current; + if (packet_queue_grow(queue) >= 0) { + pkt = queue->packets + (queue->packets_size - 1); + pkt->filepos = filepos; + pkt->pts100 = ms < 0 ? UINT_MAX : (unsigned int)ms * 90; + return 0; + } + return -1; +} + +static int vobsub_parse_id(vobsub_t *vob, const char *line) +{ + // id: xx, index: n + size_t idlen; + const char *p, *q; + p = line; + while (isspace(*p)) + ++p; + q = p; + while (isalpha(*q)) + ++q; + idlen = q - p; + if (idlen == 0) + return -1; + ++q; + while (isspace(*q)) + ++q; + if (strncmp("index:", q, 6)) + return -1; + q += 6; + while (isspace(*q)) + ++q; + if (!isdigit(*q)) + return -1; + return vobsub_add_id(vob, p, idlen, atoi(q)); +} + +static int vobsub_parse_timestamp(vobsub_t *vob, const char *line) +{ + // timestamp: HH:MM:SS.mmm, filepos: 0nnnnnnnnn + int h, m, s, ms; + off_t filepos; + if (sscanf(line, " %02d:%02d:%02d:%03d, filepos: %09"PRIx64"", + &h, &m, &s, &ms, &filepos) != 5) + return -1; + return vobsub_add_timestamp(vob, filepos, vob->delay + ms + 1000 * (s + 60 * (m + 60 * h))); +} + +static int vobsub_parse_origin(vobsub_t *vob, const char *line) +{ + // org: X,Y + unsigned x, y; + + if (sscanf(line, " %u,%u", &x, &y) == 2) { + vob->origin_x = x; + vob->origin_y = y; + return 0; + } + return -1; +} + +unsigned int vobsub_palette_to_yuv(unsigned int pal) +{ + int r, g, b, y, u, v; + // Palette in idx file is not rgb value, it was calculated by wrong formula. + // Here's reversed formula of the one used to generate palette in idx file. + r = pal >> 16 & 0xff; + g = pal >> 8 & 0xff; + b = pal & 0xff; + y = av_clip_uint8( 0.1494 * r + 0.6061 * g + 0.2445 * b); + u = av_clip_uint8( 0.6066 * r - 0.4322 * g - 0.1744 * b + 128); + v = av_clip_uint8(-0.08435 * r - 0.3422 * g + 0.4266 * b + 128); + y = y * 219 / 255 + 16; + return y << 16 | u << 8 | v; +} + +unsigned int vobsub_rgb_to_yuv(unsigned int rgb) +{ + int r, g, b, y, u, v; + r = rgb >> 16 & 0xff; + g = rgb >> 8 & 0xff; + b = rgb & 0xff; + y = ( 0.299 * r + 0.587 * g + 0.114 * b) * 219 / 255 + 16.5; + u = (-0.16874 * r - 0.33126 * g + 0.5 * b) * 224 / 255 + 128.5; + v = ( 0.5 * r - 0.41869 * g - 0.08131 * b) * 224 / 255 + 128.5; + return y << 16 | u << 8 | v; +} + +static int vobsub_parse_delay(vobsub_t *vob, const char *line) +{ + int h, m, s, ms; + int forward = 1; + if (*(line + 7) == '+') { + forward = 1; + line++; + } else if (*(line + 7) == '-') { + forward = -1; + line++; + } + mp_msg(MSGT_SPUDEC, MSGL_V, "forward=%d", forward); + h = atoi(line + 7); + mp_msg(MSGT_VOBSUB, MSGL_V, "h=%d,", h); + m = atoi(line + 10); + mp_msg(MSGT_VOBSUB, MSGL_V, "m=%d,", m); + s = atoi(line + 13); + mp_msg(MSGT_VOBSUB, MSGL_V, "s=%d,", s); + ms = atoi(line + 16); + mp_msg(MSGT_VOBSUB, MSGL_V, "ms=%d", ms); + vob->delay = (ms + 1000 * (s + 60 * (m + 60 * h))) * forward; + return 0; +} + +static int vobsub_set_lang(const char *line) +{ + if (vobsub_id == -1) + vobsub_id = atoi(line + 8); // 8 == strlen("langidx:") + return 0; +} + +static int vobsub_parse_one_line(vobsub_t *vob, rar_stream_t *fd, + unsigned char **extradata, + unsigned int *extradata_len) +{ + ssize_t line_size; + int res = -1; + size_t line_reserve = 0; + char *line = NULL; + unsigned char *tmp; + do { + line_size = vobsub_getline(&line, &line_reserve, fd); + if (line_size < 0 || line_size > 1000000 || + *extradata_len+line_size > 10000000) { + break; + } + + tmp = realloc(*extradata, *extradata_len+line_size+1); + if(!tmp) { + mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR out of memory"); + break; + } + *extradata = tmp; + memcpy(*extradata+*extradata_len, line, line_size); + *extradata_len += line_size; + (*extradata)[*extradata_len] = 0; + + if (*line == 0 || *line == '\r' || *line == '\n' || *line == '#') + continue; + else if (strncmp("langidx:", line, 8) == 0) + res = vobsub_set_lang(line); + else if (strncmp("delay:", line, 6) == 0) + res = vobsub_parse_delay(vob, line); + else if (strncmp("id:", line, 3) == 0) + res = vobsub_parse_id(vob, line + 3); + else if (strncmp("org:", line, 4) == 0) + res = vobsub_parse_origin(vob, line + 4); + else if (strncmp("timestamp:", line, 10) == 0) + res = vobsub_parse_timestamp(vob, line + 10); + else { + //mp_msg(MSGT_VOBSUB, MSGL_V, "vobsub: ignoring %s", line); + /* + size, palette, forced subs: on, and custom colors: ON, tridx are + handled by spudec_parse_extradata in spudec.c + */ + continue; + } + if (res < 0) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "ERROR in %s", line); + break; + } while (1); + if (line) + free(line); + return res; +} + +int vobsub_parse_ifo(void* this, const char *const name, unsigned int *palette, + unsigned int *width, unsigned int *height, int force, + int sid, char *langid) +{ + vobsub_t *vob = this; + int res = -1; + rar_stream_t *fd = rar_open(name, "rb"); + if (fd == NULL) { + //if (force) + //mp_msg(MSGT_VOBSUB, MSGL_WARN, "VobSub: Can't open IFO file\n"); + } else { + // parse IFO header + unsigned char block[0x800]; + const char *const ifo_magic = "DVDVIDEO-VTS"; + if (rar_read(block, sizeof(block), 1, fd) != 1) { + if (force) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO header\n"); + } else if (memcmp(block, ifo_magic, strlen(ifo_magic) + 1)) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Bad magic in IFO header\n"); + else { + unsigned long pgci_sector = block[0xcc] << 24 | block[0xcd] << 16 + | block[0xce] << 8 | block[0xcf]; + int standard = (block[0x200] & 0x30) >> 4; + int resolution = (block[0x201] & 0x0c) >> 2; + *height = standard ? 576 : 480; + *width = 0; + switch (resolution) { + case 0x0: + *width = 720; + break; + case 0x1: + *width = 704; + break; + case 0x2: + *width = 352; + break; + case 0x3: + *width = 352; + *height /= 2; + break; + default: + mp_msg(MSGT_VOBSUB, MSGL_WARN, "Vobsub: Unknown resolution %d \n", resolution); + } + if (langid && 0 <= sid && sid < 32) { + unsigned char *tmp = block + 0x256 + sid * 6 + 2; + langid[0] = tmp[0]; + langid[1] = tmp[1]; + langid[2] = 0; + } + if (rar_seek(fd, pgci_sector * sizeof(block), SEEK_SET) + || rar_read(block, sizeof(block), 1, fd) != 1) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't read IFO PGCI\n"); + else { + unsigned long idx; + unsigned long pgc_offset = block[0xc] << 24 | block[0xd] << 16 + | block[0xe] << 8 | block[0xf]; + for (idx = 0; idx < 16; ++idx) { + unsigned char *p = block + pgc_offset + 0xa4 + 4 * idx; + palette[idx] = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; + } + if (vob) + vob->have_palette = 1; + res = 0; + } + } + rar_close(fd); + } + return res; +} + +void *vobsub_open(const char *const name, const char *const ifo, + const int force, void** spu) +{ + unsigned char *extradata = NULL; + unsigned int extradata_len = 0; + vobsub_t *vob = calloc(1, sizeof(vobsub_t)); + if (spu) + *spu = NULL; + if (vobsubid == -2) + vobsubid = vobsub_id; + if (vob) { + char *buf; + buf = malloc(strlen(name) + 5); + if (buf) { + rar_stream_t *fd; + mpeg_t *mpg; + /* read in the info file */ + if (!ifo) { + strcpy(buf, name); + strcat(buf, ".ifo"); + vobsub_parse_ifo(vob, buf, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); + } else + vobsub_parse_ifo(vob, ifo, vob->palette, &vob->orig_frame_width, &vob->orig_frame_height, force, -1, NULL); + /* read in the index */ + strcpy(buf, name); + strcat(buf, ".idx"); + fd = rar_open(buf, "rb"); + if (fd == NULL) { + if (force) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open IDX file\n"); + else { + free(buf); + free(vob); + return NULL; + } + } else { + while (vobsub_parse_one_line(vob, fd, &extradata, &extradata_len) >= 0) + /* NOOP */ ; + rar_close(fd); + } + if (spu) + *spu = spudec_new_scaled(vob->palette, vob->orig_frame_width, vob->orig_frame_height, extradata, extradata_len); + if (extradata) + free(extradata); + + /* read the indexed mpeg_stream */ + strcpy(buf, name); + strcat(buf, ".sub"); + mpg = mpeg_open(buf); + if (mpg == NULL) { + if (force) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: Can't open SUB file\n"); + else { + free(buf); + free(vob); + return NULL; + } + } else { + long last_pts_diff = 0; + while (!mpeg_eof(mpg)) { + off_t pos = mpeg_tell(mpg); + if (mpeg_run(mpg) < 0) { + if (!mpeg_eof(mpg)) + mp_msg(MSGT_VOBSUB, MSGL_ERR, "VobSub: mpeg_run error\n"); + break; + } + if (mpg->packet_size) { + if ((mpg->aid & 0xe0) == 0x20) { + unsigned int sid = mpg->aid & 0x1f; + if (vobsub_ensure_spu_stream(vob, sid) >= 0) { + packet_queue_t *queue = vob->spu_streams + sid; + /* get the packet to fill */ + if (queue->packets_size == 0 && packet_queue_grow(queue) < 0) + abort(); + while (queue->current_index + 1 < queue->packets_size + && queue->packets[queue->current_index + 1].filepos <= pos) + ++queue->current_index; + if (queue->current_index < queue->packets_size) { + packet_t *pkt; + if (queue->packets[queue->current_index].data) { + /* insert a new packet and fix the PTS ! */ + packet_queue_insert(queue); + queue->packets[queue->current_index].pts100 = + mpg->pts + last_pts_diff; + } + pkt = queue->packets + queue->current_index; + if (pkt->pts100 != UINT_MAX) { + if (queue->packets_size > 1) + last_pts_diff = pkt->pts100 - mpg->pts; + else + pkt->pts100 = mpg->pts; + if (mpg->merge && queue->current_index > 0) { + packet_t *last = &queue->packets[queue->current_index - 1]; + pkt->pts100 = last->pts100; + } + mpg->merge = 0; + /* FIXME: should not use mpg_sub internal informations, make a copy */ + pkt->data = mpg->packet; + pkt->size = mpg->packet_size; + mpg->packet = NULL; + mpg->packet_reserve = 0; + mpg->packet_size = 0; + } + } + } else + mp_msg(MSGT_VOBSUB, MSGL_WARN, "don't know what to do with subtitle #%u\n", sid); + } + } + } + vob->spu_streams_current = vob->spu_streams_size; + while (vob->spu_streams_current-- > 0) { + vob->spu_streams[vob->spu_streams_current].current_index = 0; + if (vobsubid == vob->spu_streams_current || + vob->spu_streams[vob->spu_streams_current].packets_size > 0) + ++vob->spu_valid_streams_size; + } + mpeg_free(mpg); + } + free(buf); + } + } + return vob; +} + +void vobsub_close(void *this) +{ + vobsub_t *vob = this; + if (vob->spu_streams) { + while (vob->spu_streams_size--) + packet_queue_destroy(vob->spu_streams + vob->spu_streams_size); + free(vob->spu_streams); + } + free(vob); +} + +unsigned int vobsub_get_indexes_count(void *vobhandle) +{ + vobsub_t *vob = vobhandle; + return vob->spu_valid_streams_size; +} + +char *vobsub_get_id(void *vobhandle, unsigned int index) +{ + vobsub_t *vob = vobhandle; + return (index < vob->spu_streams_size) ? vob->spu_streams[index].id : NULL; +} + +int vobsub_get_id_by_index(void *vobhandle, unsigned int index) +{ + vobsub_t *vob = vobhandle; + int i, j; + if (vob == NULL) + return -1; + for (i = 0, j = 0; i < vob->spu_streams_size; ++i) + if (i == vobsubid || vob->spu_streams[i].packets_size > 0) { + if (j == index) + return i; + ++j; + } + return -1; +} + +int vobsub_get_index_by_id(void *vobhandle, int id) +{ + vobsub_t *vob = vobhandle; + int i, j; + if (vob == NULL || id < 0 || id >= vob->spu_streams_size) + return -1; + if (id != vobsubid && !vob->spu_streams[id].packets_size) + return -1; + for (i = 0, j = 0; i < id; ++i) + if (i == vobsubid || vob->spu_streams[i].packets_size > 0) + ++j; + return j; +} + +int vobsub_set_from_lang(void *vobhandle, char const *lang) +{ + int i; + vobsub_t *vob= vobhandle; + while (lang && strlen(lang) >= 2) { + for (i = 0; i < vob->spu_streams_size; i++) + if (vob->spu_streams[i].id) + if ((strncmp(vob->spu_streams[i].id, lang, 2) == 0)) { + vobsub_id = i; + mp_msg(MSGT_VOBSUB, MSGL_INFO, "Selected VOBSUB language: %d language: %s\n", i, vob->spu_streams[i].id); + return 0; + } + lang+=2;while (lang[0]==',' || lang[0]==' ') ++lang; + } + mp_msg(MSGT_VOBSUB, MSGL_WARN, "No matching VOBSUB language found!\n"); + return -1; +} + +/// make sure we seek to the first packet of packets having same pts values. +static void vobsub_queue_reseek(packet_queue_t *queue, unsigned int pts100) +{ + int reseek_count = 0; + unsigned int lastpts = 0; + + if (queue->current_index > 0 + && (queue->packets[queue->current_index].pts100 == UINT_MAX + || queue->packets[queue->current_index].pts100 > pts100)) { + // possible pts seek previous, try to check it. + int i = 1; + while (queue->current_index >= i + && queue->packets[queue->current_index-i].pts100 == UINT_MAX) + ++i; + if (queue->current_index >= i + && queue->packets[queue->current_index-i].pts100 > pts100) + // pts seek previous confirmed, reseek from beginning + queue->current_index = 0; + } + while (queue->current_index < queue->packets_size + && queue->packets[queue->current_index].pts100 <= pts100) { + lastpts = queue->packets[queue->current_index].pts100; + ++queue->current_index; + ++reseek_count; + } + while (reseek_count-- && --queue->current_index) { + if (queue->packets[queue->current_index-1].pts100 != UINT_MAX && + queue->packets[queue->current_index-1].pts100 != lastpts) + break; + } +} + +int vobsub_get_packet(void *vobhandle, float pts, void** data, int* timestamp) +{ + vobsub_t *vob = vobhandle; + unsigned int pts100 = 90000 * pts; + if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { + packet_queue_t *queue = vob->spu_streams + vobsub_id; + + vobsub_queue_reseek(queue, pts100); + + while (queue->current_index < queue->packets_size) { + packet_t *pkt = queue->packets + queue->current_index; + if (pkt->pts100 != UINT_MAX) + if (pkt->pts100 <= pts100) { + ++queue->current_index; + *data = pkt->data; + *timestamp = pkt->pts100; + return pkt->size; + } else + break; + else + ++queue->current_index; + } + } + return -1; +} + +int vobsub_get_next_packet(void *vobhandle, void** data, int* timestamp) +{ + vobsub_t *vob = vobhandle; + if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { + packet_queue_t *queue = vob->spu_streams + vobsub_id; + if (queue->current_index < queue->packets_size) { + packet_t *pkt = queue->packets + queue->current_index; + ++queue->current_index; + *data = pkt->data; + *timestamp = pkt->pts100; + return pkt->size; + } + } + return -1; +} + +void vobsub_seek(void * vobhandle, float pts) +{ + vobsub_t * vob = vobhandle; + packet_queue_t * queue; + int seek_pts100 = pts * 90000; + + if (vob->spu_streams && 0 <= vobsub_id && (unsigned) vobsub_id < vob->spu_streams_size) { + /* do not seek if we don't know the id */ + if (vobsub_get_id(vob, vobsub_id) == NULL) + return; + queue = vob->spu_streams + vobsub_id; + queue->current_index = 0; + vobsub_queue_reseek(queue, seek_pts100); + } +} + +void vobsub_reset(void *vobhandle) +{ + vobsub_t *vob = vobhandle; + if (vob->spu_streams) { + unsigned int n = vob->spu_streams_size; + while (n-- > 0) + vob->spu_streams[n].current_index = 0; + } +} + +#if 0 // R: no output needed +/********************************************************************** + * Vobsub output + **********************************************************************/ + +typedef struct { + FILE *fsub; + FILE *fidx; + unsigned int aid; +} vobsub_out_t; + +static void create_idx(vobsub_out_t *me, const unsigned int *palette, + unsigned int orig_width, unsigned int orig_height) +{ + int i; + fprintf(me->fidx, + "# VobSub index file, v7 (do not modify this line!)\n" + "#\n" + "# Generated by %s\n" + "# See <URL:http://www.mplayerhq.hu/> for more information about MPlayer\n" + "# See <URL:http://wiki.multimedia.cx/index.php?title=VOBsub> for more information about Vobsub\n" + "#\n" + "size: %ux%u\n", + mplayer_version, orig_width, orig_height); + if (palette) { + fputs("palette:", me->fidx); + for (i = 0; i < 16; ++i) { + const double y = palette[i] >> 16 & 0xff, + u = (palette[i] >> 8 & 0xff) - 128.0, + v = (palette[i] & 0xff) - 128.0; + if (i) + putc(',', me->fidx); + fprintf(me->fidx, " %02x%02x%02x", + av_clip_uint8(y + 1.4022 * u), + av_clip_uint8(y - 0.3456 * u - 0.7145 * v), + av_clip_uint8(y + 1.7710 * v)); + } + putc('\n', me->fidx); + } + + fprintf(me->fidx, "# ON: displays only forced subtitles, OFF: shows everything\n" + "forced subs: OFF\n"); +} + +void *vobsub_out_open(const char *basename, const unsigned int *palette, + unsigned int orig_width, unsigned int orig_height, + const char *id, unsigned int index) +{ + vobsub_out_t *result = NULL; + char *filename; + filename = malloc(strlen(basename) + 5); + if (filename) { + result = malloc(sizeof(vobsub_out_t)); + if (result) { + result->aid = index; + strcpy(filename, basename); + strcat(filename, ".sub"); + result->fsub = fopen(filename, "ab"); + if (result->fsub == NULL) + perror("Error: vobsub_out_open subtitle file open failed"); + strcpy(filename, basename); + strcat(filename, ".idx"); + result->fidx = fopen(filename, "ab"); + if (result->fidx) { + if (ftell(result->fidx) == 0) { + create_idx(result, palette, orig_width, orig_height); + /* Make the selected language the default language */ + fprintf(result->fidx, "\n# Language index in use\nlangidx: %u\n", index); + } + fprintf(result->fidx, "\nid: %s, index: %u\n", id ? id : "xx", index); + /* So that we can check the file now */ + fflush(result->fidx); + } else + perror("Error: vobsub_out_open index file open failed"); + free(filename); + } + } + return result; +} + +void vobsub_out_close(void *me) +{ + vobsub_out_t *vob = me; + if (vob->fidx) + fclose(vob->fidx); + if (vob->fsub) + fclose(vob->fsub); + free(vob); +} + +void vobsub_out_output(void *me, const unsigned char *packet, + int len, double pts) +{ + static double last_pts; + static int last_pts_set = 0; + vobsub_out_t *vob = me; + if (vob->fsub) { + /* Windows' Vobsub require that every packet is exactly 2kB long */ + unsigned char buffer[2048]; + unsigned char *p; + int remain = 2048; + /* Do not output twice a line with the same timestamp, this + breaks Windows' Vobsub */ + if (vob->fidx && (!last_pts_set || last_pts != pts)) { + static unsigned int last_h = 9999, last_m = 9999, last_s = 9999, last_ms = 9999; + unsigned int h, m, ms; + double s; + s = pts; + h = s / 3600; + s -= h * 3600; + m = s / 60; + s -= m * 60; + ms = (s - (unsigned int) s) * 1000; + if (ms >= 1000) /* prevent overflows or bad float stuff */ + ms = 0; + if (h != last_h || m != last_m || (unsigned int) s != last_s || ms != last_ms) { + fprintf(vob->fidx, "timestamp: %02u:%02u:%02u:%03u, filepos: %09lx\n", + h, m, (unsigned int) s, ms, ftell(vob->fsub)); + last_h = h; + last_m = m; + last_s = (unsigned int) s; + last_ms = ms; + } + } + last_pts = pts; + last_pts_set = 1; + + /* Packet start code: Windows' Vobsub needs this */ + p = buffer; + *p++ = 0; /* 0x00 */ + *p++ = 0; + *p++ = 1; + *p++ = 0xba; + *p++ = 0x40; + memset(p, 0, 9); + p += 9; + { /* Packet */ + static unsigned char last_pts[5] = { 0, 0, 0, 0, 0}; + unsigned char now_pts[5]; + int pts_len, pad_len, datalen = len; + pts *= 90000; + now_pts[0] = 0x21 | (((unsigned long)pts >> 29) & 0x0e); + now_pts[1] = ((unsigned long)pts >> 22) & 0xff; + now_pts[2] = 0x01 | (((unsigned long)pts >> 14) & 0xfe); + now_pts[3] = ((unsigned long)pts >> 7) & 0xff; + now_pts[4] = 0x01 | (((unsigned long)pts << 1) & 0xfe); + pts_len = memcmp(last_pts, now_pts, sizeof(now_pts)) ? sizeof(now_pts) : 0; + memcpy(last_pts, now_pts, sizeof(now_pts)); + + datalen += 3; /* Version, PTS_flags, pts_len */ + datalen += pts_len; + datalen += 1; /* AID */ + pad_len = 2048 - (p - buffer) - 4 /* MPEG ID */ - 2 /* payload len */ - datalen; + /* XXX - Go figure what should go here! In any case the + packet has to be completely filled. If I can fill it + with padding (0x000001be) latter I'll do that. But if + there is only room for 6 bytes then I can not write a + padding packet. So I add some padding in the PTS + field. This looks like a dirty kludge. Oh well... */ + if (pad_len < 0) { + /* Packet is too big. Let's try omitting the PTS field */ + datalen -= pts_len; + pts_len = 0; + pad_len = 0; + } else if (pad_len > 6) + pad_len = 0; + datalen += pad_len; + + *p++ = 0; /* 0x0e */ + *p++ = 0; + *p++ = 1; + *p++ = 0xbd; + + *p++ = (datalen >> 8) & 0xff; /* length of payload */ + *p++ = datalen & 0xff; + *p++ = 0x80; /* System-2 (.VOB) stream */ + *p++ = pts_len ? 0x80 : 0x00; /* pts_flags */ + *p++ = pts_len + pad_len; + memcpy(p, now_pts, pts_len); + p += pts_len; + memset(p, 0, pad_len); + p += pad_len; + } + *p++ = 0x20 | vob->aid; /* aid */ + if (fwrite(buffer, p - buffer, 1, vob->fsub) != 1 + || fwrite(packet, len, 1, vob->fsub) != 1) + perror("ERROR: vobsub write failed"); + else + remain -= p - buffer + len; + + /* Padding */ + if (remain >= 6) { + p = buffer; + *p++ = 0x00; + *p++ = 0x00; + *p++ = 0x01; + *p++ = 0xbe; + *p++ = (remain - 6) >> 8; + *p++ = (remain - 6) & 0xff; + /* for better compression, blank this */ + memset(buffer + 6, 0, remain - (p - buffer)); + if (fwrite(buffer, remain, 1, vob->fsub) != 1) + perror("ERROR: vobsub padding write failed"); + } else if (remain > 0) { + /* I don't know what to output. But anyway the block + needs to be 2KB big */ + memset(buffer, 0, remain); + if (fwrite(buffer, remain, 1, vob->fsub) != 1) + perror("ERROR: vobsub blank padding write failed"); + } else if (remain < 0) + fprintf(stderr, + "\nERROR: wrong thing happened...\n" + " I wrote a %i data bytes spu packet and that's too long\n", len); + } +} +#endif diff --git a/mplayer/vobsub.h b/mplayer/vobsub.h new file mode 100644 index 0000000..12dd466 --- /dev/null +++ b/mplayer/vobsub.h @@ -0,0 +1,59 @@ +/* + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef MPLAYER_VOBSUB_H +#define MPLAYER_VOBSUB_H + +#ifdef __cplusplus +extern "C" { +#endif + +extern int vobsub_id; // R: moved from mpcommon.h + +void *vobsub_open(const char *subname, const char *const ifo, const int force, void** spu); +void vobsub_reset(void *vob); +int vobsub_parse_ifo(void* self, const char *const name, unsigned int *palette, unsigned int *width, unsigned int *height, int force, int sid, char *langid); +int vobsub_get_packet(void *vobhandle, float pts,void** data, int* timestamp); +int vobsub_get_next_packet(void *vobhandle, void** data, int* timestamp); +void vobsub_close(void *self); +unsigned int vobsub_get_indexes_count(void * /* vobhandle */); +char *vobsub_get_id(void * /* vobhandle */, unsigned int /* index */); + +/// Get vobsub id by its index in the valid streams. +int vobsub_get_id_by_index(void *vobhandle, unsigned int index); +/// Get index in the valid streams by vobsub id. +int vobsub_get_index_by_id(void *vobhandle, int id); + +/// Convert palette value in idx file to yuv. +unsigned int vobsub_palette_to_yuv(unsigned int pal); +/// Convert rgb value to yuv. +unsigned int vobsub_rgb_to_yuv(unsigned int rgb); + +#if 0 // R: no output needed +void *vobsub_out_open(const char *basename, const unsigned int *palette, unsigned int orig_width, unsigned int orig_height, const char *id, unsigned int index); +void vobsub_out_output(void *me, const unsigned char *packet, int len, double pts); +void vobsub_out_close(void *me); +#endif +int vobsub_set_from_lang(void *vobhandle, char const *lang); // R: changed lang from unsigned char* +void vobsub_seek(void * vobhandle, float pts); + +#ifdef __cplusplus +} +#endif + +#endif /* MPLAYER_VOBSUB_H */ diff --git a/packaging/vobsub2srt-9999.ebuild b/packaging/vobsub2srt-9999.ebuild new file mode 100644 index 0000000..53826dd --- /dev/null +++ b/packaging/vobsub2srt-9999.ebuild @@ -0,0 +1,33 @@ +# -*- mode:sh; -*- +# Copyright 1999-2012 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: /media-video/vobsub2srt/ChangeLog,v 0.1 2012/01/06 19:15:04 thawn Exp $ + +EAPI="4" + +EGIT_REPO_URI="git://github.com/ruediger/VobSub2SRT.git" + +inherit git-2 + +IUSE="" + +DESCRIPTION="Converts image subtitles created by VobSub (.sub/.idx) to .srt textual subtitles using tesseract OCR engine" +HOMEPAGE="https://github.com/ruediger/VobSub2SRT" + +LICENSE="GPL-3" +SLOT="0" +KEYWORDS="~amd64 ~x86" + +RDEPEND=">=app-text/tesseract-2.04-r1 + >=virtual/ffmpeg-0.6.90" +DEPEND="${RDEPEND}" +src_configure() { + econf +} +src_compile() { + emake || die +} + +src_install() { + emake DESTDIR="${D}" install || die +} diff --git a/packaging/vobsub2srt.rb b/packaging/vobsub2srt.rb new file mode 100644 index 0000000..9181385 --- /dev/null +++ b/packaging/vobsub2srt.rb @@ -0,0 +1,18 @@ +# Homebrew Formula for VobSub2SRT +# Usage: brew install https://github.com/ruediger/VobSub2SRT/raw/master/vobsub2srt.rb + +require 'formula' + +class Vobsub2srt < Formula + head 'git://github.com/ruediger/VobSub2SRT.git', :using => :git + homepage 'https://github.com/ruediger/VobSub2SRT' + + depends_on 'cmake' + depends_on 'tesseract' + depends_on 'ffmpeg' + + def install + system "./configure #{std_cmake_parameters}" + system "cd build; make install" + end +end diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..9eac1ad --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,22 @@ +include_directories(${vobsub2srt_SOURCE_DIR}/mplayer) + +link_directories(${Libavutil_LIBRARY_DIRS}) +include_directories(${Libavutil_INCLUDE_DIRS}) +include_directories(${Tesseract_INCLUDE_DIR}) + +set(vobsub2srt_sources + vobsub2srt.c++ + langcodes.h++ + langcodes.c++ + cmd_options.h++ + cmd_options.c++) + +add_executable(vobsub2srt ${vobsub2srt_sources}) +if(BUILD_STATIC) + set_target_properties(vobsub2srt PROPERTIES + LINK_SEARCH_END_STATIC ON + LINK_FLAGS -static) +endif() +target_link_libraries(vobsub2srt mplayer ${Libavutil_LIBRARIES} ${Tesseract_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) + +install(TARGETS vobsub2srt RUNTIME DESTINATION ${INSTALL_EXECUTABLES_PATH}) diff --git a/src/cmd_options.c++ b/src/cmd_options.c++ new file mode 100644 index 0000000..70b2c86 --- /dev/null +++ b/src/cmd_options.c++ @@ -0,0 +1,190 @@ +/* + * This file is part of vobsub2srt + * + * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "cmd_options.h++" +#include <iostream> +#include <cstring> +#include <cstdlib> +#include <vector> +#include <string> +using namespace std; + +namespace { +struct option { + enum arg_type { Bool, String, Int } type; + union { + bool *flag; + std::string *str; + int *i; + } ref; + char const *name; + char const *description; + char short_name; + + template<typename T> + option(char const *name, arg_type type, T &r, char const *description, char short_name) + : type(type), name(name), description(description), short_name(short_name) + { + switch(type) { + case Bool: + ref.flag = reinterpret_cast<bool*>(&r); + break; + case String: + ref.str = reinterpret_cast<std::string*>(&r); + break; + case Int: + ref.i = reinterpret_cast<int*>(&r); + break; + } + } +}; + +struct unnamed { + std::string *str; + char const *name; + char const *description; + unnamed(std::string &s, char const *name, char const *description) + : str(&s), name(name), description(description) + { } +}; + +} + +struct cmd_options::impl { + std::vector<option> options; + std::vector<unnamed> unnamed_args; +}; + +cmd_options::cmd_options(bool handle_help) + : exit(false), handle_help(handle_help), pimpl(new impl) +{ + pimpl->options.reserve(10); // reserve a default amount of options here to save some reallocations +} + +cmd_options::~cmd_options() { + delete pimpl; +} + +cmd_options &cmd_options::add_option(char const *name, bool &val, char const *description, char short_name) { + pimpl->options.push_back(option(name, option::Bool, val, description, short_name)); + return *this; +} +cmd_options &cmd_options::add_option(char const *name, std::string &val, char const *description, char short_name) { + pimpl->options.push_back(option(name, option::String, val, description, short_name)); + return *this; +} +cmd_options &cmd_options::add_option(char const *name, int &val, char const *description, char short_name) { + pimpl->options.push_back(option(name, option::Int, val, description, short_name)); + return *this; +} + +cmd_options &cmd_options::add_unnamed(std::string &val, char const *help_name, char const *description) { + pimpl->unnamed_args.push_back(unnamed(val, help_name, description)); + return *this; +} + +bool cmd_options::parse_cmd(int argc, char **argv) const { + size_t current_unnamed = 0; + bool parse_options = true; // set to false after -- + for(int i = 1; i < argc; ++i) { + if(parse_options and argv[i][0] == '-') { + unsigned offset = 1; + if(argv[i][1] == '-') { + if(argv[i][2] == '\0') { + // "--" stops option parsing and handles only unnamed args (to allow e.g. files starting with -) + parse_options = false; + } + offset = 2; + } + if(handle_help and (strcmp(argv[i]+offset, "help") == 0 or strcmp(argv[i]+offset, "h") == 0)) { + help(argv[0]); + continue; + } + for(std::vector<option>::const_iterator j = pimpl->options.begin(); j != pimpl->options.end(); ++j) { + if(strcmp(argv[i]+offset, j->name) == 0 or + (j->short_name != '\0' and argv[i][offset+1] == j->short_name and argv[i][offset+1] == '\0')) { + if(j->type == option::Bool) { + *j->ref.flag = true; + break; + } + + if(i+1 >= argc or argv[i+1][0] == '-') { // Check if next argv is an option or argument + cerr << "option " << argv[i] << " is missing an argument\n"; + exit = true; + return false; + } + ++i; + + if(j->type == option::String) { + *j->ref.str = argv[i]; + } + else if(j->type == option::Int) { + char *endptr; + *j->ref.i = strtol(argv[i], &endptr, 10); + if(*endptr != '\0') { + cerr << "option " << argv[i] << " expects a number as argument but got '" << argv[i] << "'\n"; + exit = true; + return false; + } + } + break; + } + } + } + else if(pimpl->unnamed_args.size() > current_unnamed) { + *pimpl->unnamed_args[current_unnamed].str = argv[i]; + ++current_unnamed; + } + else { + help(argv[0]); + } + } + return not exit; +} + +void cmd_options::help(char const *progname) const { + cerr << "usage: " << progname; + for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { + cerr << " --" << i->name; + } + if(handle_help) { + cerr << " --help"; + } + for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { + cerr << " <" << i->name << '>'; + } + cerr << "\n\n"; + for(std::vector<option>::const_iterator i = pimpl->options.begin(); i != pimpl->options.end(); ++i) { + cerr << "\t--" << i->name; + if(i->type != option::Bool) { + cerr << " <arg>"; + } + if(i->short_name != '\0') { + cerr << " (or -" << i->short_name << ')'; + } + cerr << "\t... " << i->description << '\n'; + } + if(handle_help) { + cerr << "\t--help (or -h)\t... show help information\n"; + } + for(std::vector<unnamed>::const_iterator i = pimpl->unnamed_args.begin(); i != pimpl->unnamed_args.end(); ++i) { + cerr << "\t<" << i->name << ">\t... " << i->description << '\n'; + } + exit = true; +} diff --git a/src/cmd_options.h++ b/src/cmd_options.h++ new file mode 100644 index 0000000..bc51c00 --- /dev/null +++ b/src/cmd_options.h++ @@ -0,0 +1,55 @@ +/* + * This file is part of vobsub2srt + * + * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef CMD_OPTIONS_HXX +#define CMD_OPTIONS_HXX + +#include <string> // string_fwd in C++0x + +/// Handle argc/argv +struct cmd_options { + cmd_options(bool handle_help = true); + ~cmd_options(); + + cmd_options &add_option(char const *name, bool &val, char const *description, char short_name = '\0'); + cmd_options &add_option(char const *name, std::string &val, char const *description, char short_name = '\0'); + cmd_options &add_option(char const *name, int &val, char const *description, char short_name = '\0'); + + cmd_options &add_unnamed(std::string &val, char const *help_name, char const *description); + + bool parse_cmd(int argc, char **argv) const; + + /// returns true if an error occurred and the program should exit + bool should_exit() const { + return exit; + } +private: + mutable bool exit; + void help(char const *progname) const; + bool handle_help; + + struct impl; + impl *pimpl; // this should be a scoped_ptr + + // noncopyable + cmd_options(cmd_options const&); + cmd_options &operator=(cmd_options const&); +}; + +#endif diff --git a/src/gen_langcodes.pl b/src/gen_langcodes.pl new file mode 100755 index 0000000..5ba36ef --- /dev/null +++ b/src/gen_langcodes.pl @@ -0,0 +1,62 @@ +#!/usr/bin/perl +# +# This file is part of vobsub2srt +# +# Copyright (C) 2012 Rüdiger Sonderfeld <[email protected]> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +## Comment: +# +# This script was used to generate parts of langcodes.c++. Get the list of codes +# from http://www.sil.org/iso639-3/download.asp +# e.g. wget http://www.sil.org/iso639-3/iso-639-3_20110525.tab +# +# I'm not a big Perl hacker and this implementation probably sucks. Last time I +# used emacs keyboard macros. But this is no good if you have to repeat the +# procedure a while later. So I wanted to write a script. I hadn't done anything +# in Perl in a long time (~10 years?) so I figured I use Perl to do the job +# (instead of Bash or Python). +# +# Thanks to Aristid Breitkreuz for helping me to improve the script and my Perl style. +# +use warnings; +use strict; + +my $filename = 'iso-639-3_20110525.tab'; +my @iso639; + +open FH, $filename or die $!; +<FH>; # skip first line +while(<FH>) { + my ($iso3, undef, undef, $iso1) = split /\t/; + if($iso1 ne '') { + push(@iso639, [$iso1, $iso3] ); + } +} + +# keep sorted for binary search +my @iso639_sorted = sort {@{$a}[0] cmp @{$b}[0] } @iso639; + +print 'static char const *const iso639_1[] = {',"\n"; +foreach (@iso639_sorted) { + print ' "',$_->[0],"\",\n"; +} +print "};\n\n"; + +print 'static char const *const iso639_3[] = {',"\n"; +foreach (@iso639_sorted) { + print ' "',$_->[1],"\",\n"; +} +print "};\n"; diff --git a/src/langcodes.c++ b/src/langcodes.c++ new file mode 100644 index 0000000..4b0d73f --- /dev/null +++ b/src/langcodes.c++ @@ -0,0 +1,418 @@ +/* + * This file is part of vobsub2srt + * + * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "langcodes.h++" +#include <functional> +#include <algorithm> +#include <cstring> +#include <cassert> + +namespace { + +static char const *const iso639_1[] = { + "aa", + "ab", + "ae", + "af", + "ak", + "am", + "an", + "ar", + "as", + "av", + "ay", + "az", + "ba", + "be", + "bg", + "bi", + "bm", + "bn", + "bo", + "br", + "bs", + "ca", + "ce", + "ch", + "co", + "cr", + "cs", + "cu", + "cv", + "cy", + "da", + "de", + "dv", + "dz", + "ee", + "el", + "en", + "eo", + "es", + "et", + "eu", + "fa", + "ff", + "fi", + "fj", + "fo", + "fr", + "fy", + "ga", + "gd", + "gl", + "gn", + "gu", + "gv", + "ha", + "he", + "hi", + "ho", + "hr", + "ht", + "hu", + "hy", + "hz", + "ia", + "id", + "ie", + "ig", + "ii", + "ik", + "io", + "is", + "it", + "iu", + "ja", + "jv", + "ka", + "kg", + "ki", + "kj", + "kk", + "kl", + "km", + "kn", + "ko", + "kr", + "ks", + "ku", + "kv", + "kw", + "ky", + "la", + "lb", + "lg", + "li", + "ln", + "lo", + "lt", + "lu", + "lv", + "mg", + "mh", + "mi", + "mk", + "ml", + "mn", + "mr", + "ms", + "mt", + "my", + "na", + "nb", + "nd", + "ne", + "ng", + "nl", + "nn", + "no", + "nr", + "nv", + "ny", + "oc", + "oj", + "om", + "or", + "os", + "pa", + "pi", + "pl", + "ps", + "pt", + "qu", + "rm", + "rn", + "ro", + "ru", + "rw", + "sa", + "sc", + "sd", + "se", + "sg", + "sh", + "si", + "sk", + "sl", + "sm", + "sn", + "so", + "sq", + "sr", + "ss", + "st", + "su", + "sv", + "sw", + "ta", + "te", + "tg", + "th", + "ti", + "tk", + "tl", + "tn", + "to", + "tr", + "ts", + "tt", + "tw", + "ty", + "ug", + "uk", + "ur", + "uz", + "ve", + "vi", + "vo", + "wa", + "wo", + "xh", + "yi", + "yo", + "za", + "zh", + "zu" }; +static char const *const *const iso639_1_end = iso639_1 + sizeof(iso639_1)/sizeof(iso639_1[0]); + +static char const *const iso639_3[] = { + "aar", + "abk", + "ave", + "afr", + "aka", + "amh", + "arg", + "ara", + "asm", + "ava", + "aym", + "aze", + "bak", + "bel", + "bul", + "bis", + "bam", + "ben", + "bod", + "bre", + "bos", + "cat", + "che", + "cha", + "cos", + "cre", + "ces", + "chu", + "chv", + "cym", + "dan", + "deu", + "div", + "dzo", + "ewe", + "ell", + "eng", + "epo", + "spa", + "est", + "eus", + "fas", + "ful", + "fin", + "fij", + "fao", + "fra", + "fry", + "gle", + "gla", + "glg", + "grn", + "guj", + "glv", + "hau", + "heb", + "hin", + "hmo", + "hrv", + "hat", + "hun", + "hye", + "her", + "ina", + "ind", + "ile", + "ibo", + "iii", + "ipk", + "ido", + "isl", + "ita", + "iku", + "jpn", + "jav", + "kat", + "kon", + "kik", + "kua", + "kaz", + "kal", + "khm", + "kan", + "kor", + "kau", + "kas", + "kur", + "kom", + "cor", + "kir", + "lat", + "ltz", + "lug", + "lim", + "lin", + "lao", + "lit", + "lub", + "lav", + "mlg", + "mah", + "mri", + "mkd", + "mal", + "mon", + "mar", + "msa", + "mlt", + "mya", + "nau", + "nob", + "nde", + "nep", + "ndo", + "nld", + "nno", + "nor", + "nbl", + "nav", + "nya", + "oci", + "oji", + "orm", + "ori", + "oss", + "pan", + "pli", + "pol", + "pus", + "por", + "que", + "roh", + "run", + "ron", + "rus", + "kin", + "san", + "srd", + "snd", + "sme", + "sag", + "hbs", + "sin", + "slk", + "slv", + "smo", + "sna", + "som", + "sqi", + "srp", + "ssw", + "sot", + "sun", + "swe", + "swa", + "tam", + "tel", + "tgk", + "tha", + "tir", + "tuk", + "tgl", + "tsn", + "ton", + "tur", + "tso", + "tat", + "twi", + "tah", + "uig", + "ukr", + "urd", + "uzb", + "ven", + "vie", + "vol", + "wln", + "wol", + "xho", + "yid", + "yor", + "zha", + "zho", + "zul" }; +static char const *const *const iso639_3_end = iso639_3 + sizeof(iso639_3)/sizeof(iso639_3[0]); + +static bool compare(char const *lhs, char const *rhs) { + return std::strcmp(lhs, rhs) < 0; +} + +} + +char const *iso639_1_to_639_3(char const *lang) { + assert(sizeof(iso639_1) == sizeof(iso639_3)); + char const *const * i = std::lower_bound(iso639_1, iso639_1_end, lang, compare); // binary search + if(i == iso639_1_end) { + return 0x0; + } + else { + return iso639_3[i - iso639_1]; + } +} diff --git a/src/langcodes.h++ b/src/langcodes.h++ new file mode 100644 index 0000000..d60f95d --- /dev/null +++ b/src/langcodes.h++ @@ -0,0 +1,26 @@ +/* + * This file is part of vobsub2srt + * + * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef LANGCODES_HXX +#define LANGCODES_HXX + +/// Converts ISO 639-1 language code (two letter) to ISO 639-3 language code (three letter) +char const *iso639_1_to_639_3(char const *lang); + +#endif diff --git a/src/vobsub2srt.c++ b/src/vobsub2srt.c++ new file mode 100644 index 0000000..9f4768d --- /dev/null +++ b/src/vobsub2srt.c++ @@ -0,0 +1,233 @@ +/* + * VobSub2SRT is a simple command line program to convert .idx/.sub subtitles + * into .srt text subtitles by using OCR (tesseract). See README. + * + * Copyright (C) 2010 Rüdiger Sonderfeld <[email protected]> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// MPlayer stuff +#include "mp_msg.h" // mplayer message framework +#include "vobsub.h" +#include "spudec.h" + +// Tesseract OCR +#include "tesseract/baseapi.h" + +#include <iostream> +#include <string> +#include <cstdio> +using namespace std; + +#include "langcodes.h++" +#include "cmd_options.h++" + +typedef void* vob_t; +typedef void* spu_t; + +/** Converts time stamp in pts format to a string containing the time stamp for the srt format + * + * pts (presentation time stamp) is given with a 90kHz resolution (1/90 ms). srt expects a time stamp as HH:MM:SS:MSS. + */ +std::string pts2srt(unsigned pts) { + unsigned ms = pts/90; + unsigned const h = ms / (3600 * 1000); + ms -= h * 3600 * 1000; + unsigned const m = ms / (60 * 1000); + ms -= m * 60 * 1000; + unsigned const s = ms / 1000; + ms %= 1000; + + enum { length = 13 }; // HH:MM:SS:MSS\0 + char buf[length]; + snprintf(buf, length, "%02d:%02d:%02d,%03d", h, m, s, ms); + return std::string(buf); +} + +/// Dumps the image data to <subtitlename>-<subtitleid>.pgm in Netbpm PGM format +void dump_pgm(std::string const &filename, unsigned counter, unsigned width, unsigned height, + unsigned char const *image, size_t image_size) { + + char buf[500]; + snprintf(buf, sizeof(buf), "%s-%03u.pgm", filename.c_str(), counter); + FILE *pgm = fopen(buf, "wb"); + if(pgm) { + fprintf(pgm, "P5\n%u %u %u\n", width, height, 255u); + fwrite(image, 1, image_size, pgm); + fclose(pgm); + } +} + +#ifdef CONFIG_TESSERACT_NAMESPACE +using namespace tesseract; +#endif + +#ifndef TESSERACT_DATA_PATH +#define TESSERACT_DATA_PATH "/usr/share/tesseract-ocr/tessdata" // TODO check this in cmake +#endif + +int main(int argc, char **argv) { + bool dump_images = false; + bool verb = false; + bool list_languages = false; + std::string ifo_file; + std::string subname; + std::string lang; + std::string blacklist; + std::string tesseract_data_path = TESSERACT_DATA_PATH; + + { + cmd_options opts; + opts. + add_option("dump-images", dump_images, "dump subtitles as image files (<subname>-<number>.pgm)."). + add_option("verbose", verb, "extra verbosity"). + add_option("ifo", ifo_file, "name of the ifo file. default: tries to open <subname>.ifo. ifo file is optional!"). + add_option("lang", lang, "language to select", 'l'). + add_option("langlist", list_languages, "list languages and exit"). + add_option("tesseract-data", tesseract_data_path, "path to tesseract data (Default: " TESSERACT_DATA_PATH ")"). + add_option("blacklist", blacklist, "Character blacklist to improve the OCR (e.g. \"|\\/`_~<>\")"). + add_unnamed(subname, "subname", "name of the subtitle files WITHOUT .idx/.sub ending! (REQUIRED)"); + if(not opts.parse_cmd(argc, argv) or subname.empty()) { + return 1; + } + } + + // Init the mplayer part + verbose = verb; // mplayer verbose level + mp_msg_init(); + + // Open the sub/idx subtitles + spu_t spu; + vob_t vob = vobsub_open(subname.c_str(), ifo_file.empty() ? 0x0 : ifo_file.c_str(), 1, &spu); + if(not vob or vobsub_get_indexes_count(vob) == 0) { + cerr << "Couldn't open VobSub files '" << subname << ".idx/.sub'\n"; + return 1; + } + + // list languages and exit + if(list_languages) { + cout << "Languages:\n"; + for(size_t i = 0; i < vobsub_get_indexes_count(vob); ++i) { + cout << i << ": " << vobsub_get_id(vob, i) << '\n'; + } + return 0; + } + + // Handle stream Ids and language + + char const *tess_lang = "eng"; // default english + if(not lang.empty()) { + if(vobsub_set_from_lang(vob, lang.c_str()) < 0) { + cerr << "No matching language for '" << lang << "' found! (Trying to use default)\n"; + } + else { + // convert two letter lang code into three letter lang code (required by tesseract) + char const *const lang3 = iso639_1_to_639_3(lang.c_str()); + if(lang3) { + tess_lang = lang3; + } + } + } + else if(vobsub_id >= 0) { // try to set correct tesseract lang for default stream + char const *const lang1 = vobsub_get_id(vob, vobsub_id); + if(lang1) { + char const *const lang3 = iso639_1_to_639_3(lang1); + if(lang3) { + tess_lang = lang3; + } + } + } + + // Init Tesseract +#ifdef CONFIG_TESSERACT_NAMESPACE + TessBaseAPI tess_base_api; + tess_base_api.Init(tesseract_data_path.c_str(), tess_lang); + if(not blacklist.empty()) { + tess_base_api.SetVariable("tessedit_char_blacklist", blacklist.c_str()); + } +#else + TessBaseAPI::SimpleInit(tesseract_data_path.c_str(), tess_lang, false); // TODO params + if(not blacklist.empty()) { + TessBaseAPI::SetVariable("tessedit_char_blacklist", blacklist.c_str()); + } +#endif + + // Open srt output file + string const srt_filename = subname + ".srt"; + FILE *srtout = fopen(srt_filename.c_str(), "w"); + if(not srtout) { + perror("could not open .srt file"); + return 1; + } + + // Read subtitles and convert + void *packet; + int timestamp; // pts100 + int len; + unsigned last_start_pts = 0; + unsigned sub_counter = 1; + while( (len = vobsub_get_next_packet(vob, &packet, &timestamp)) > 0) { + if(timestamp >= 0) { + spudec_assemble(spu, reinterpret_cast<unsigned char*>(packet), len, timestamp); + spudec_heartbeat(spu, timestamp); + unsigned char const *image; + size_t image_size; + unsigned width, height, stride, start_pts, end_pts; + spudec_get_data(spu, &image, &image_size, &width, &height, &stride, &start_pts, &end_pts); + + // skip this packet if it is another packet of a subtitle that + // was decoded from multiple mpeg packets. + if (start_pts == last_start_pts) { + continue; + } + last_start_pts = start_pts; + + if(verbose > 0 and static_cast<unsigned>(timestamp) != start_pts) { + cerr << sub_counter << ": time stamp from .idx (" << timestamp << ") doesn't match time stamp from .sub (" + << start_pts << ")\n"; + } + + if(dump_images) { + dump_pgm(subname, sub_counter, width, height, image, image_size); + } + +#ifdef CONFIG_TESSERACT_NAMESPACE + char *text = tess_base_api.TesseractRect(image, 1, stride, 0, 0, width, height); +#else + char *text = TessBaseAPI::TesseractRect(image, 1, stride, 0, 0, width, height); +#endif + if(not text) { + cerr << "ERROR: OCR failed for " << sub_counter << '\n'; + continue; + } + if(verb) { + cout << sub_counter << " Text: " << text << endl; + } + fprintf(srtout, "%u\n%s --> %s\n%s\n\n", sub_counter, pts2srt(start_pts).c_str(), pts2srt(end_pts).c_str(), text); + delete[]text; + ++sub_counter; + } + } + +#ifdef CONFIG_TESSERACT_NAMESPACE + tess_base_api.End(); +#else + TessBaseAPI::End(); +#endif + fclose(srtout); + cout << "Wrote Subtitles to '" << srt_filename << "'\n"; + vobsub_close(vob); + spudec_free(spu); +}
razerbeans/webri
6e739d57b5cdc2a9ce9e7167a74a5def7ce210e8
redfish template highlight c/c++ in addition to ruby code
diff --git a/lib/webri/generators/redfish/static/assets/main.js b/lib/webri/generators/redfish/static/assets/main.js index f408967..5a5206b 100644 --- a/lib/webri/generators/redfish/static/assets/main.js +++ b/lib/webri/generators/redfish/static/assets/main.js @@ -1,113 +1,113 @@ /** * * Darkfish Page Functions * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Provide console simulation for firebug-less environments */ if (!("console" in window) || !("firebug" in console)) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; }; /** * Unwrap the first element that matches the given @expr@ from the targets and return them. */ $.fn.unwrap = function( expr ) { return this.each( function() { $(this).parents( expr ).eq( 0 ).after( this ).remove(); }); }; function showSource( e ) { var target = e.target; var codeSections = $(target). parents('.method-detail'). find('.method-source-code'); $(target). parents('.method-detail'). find('.method-source-code'). slideToggle(); }; function hookSourceViews() { $('.method-description,.method-heading').click( showSource ); }; function toggleDebuggingSection() { $('.debugging-section').slideToggle(); }; function hookDebuggingToggle() { $('#debugging-toggle img').click( toggleDebuggingSection ); }; function hookQuickSearch() { $('.quicksearch-field').each( function() { var searchElems = $(this).parents('.section').find( 'li' ); var toggle = $(this).parents('.section').find('h3 .search-toggle'); // console.debug( "Toggle is: %o", toggle ); var qsbox = $(this).parents('form').get( 0 ); $(this).quicksearch( this, searchElems, { noSearchResultsIndicator: 'no-class-search-results', focusOnLoad: false }); $(toggle).click( function() { // console.debug( "Toggling qsbox: %o", qsbox ); $(qsbox).toggle(); }); }); }; function highlightTarget( anchor ) { console.debug( "Highlighting target '%s'.", anchor ); $("a[name=" + anchor + "]").each( function() { if ( !$(this).parent().parent().hasClass('target-section') ) { console.debug( "Wrapping the target-section" ); $('div.method-detail').unwrap( 'div.target-section' ); $(this).parent().wrap( '<div class="target-section"></div>' ); } else { console.debug( "Already wrapped." ); } }); }; function highlightLocationTarget() { console.debug( "Location hash: %s", window.location.hash ); if ( ! window.location.hash || window.location.hash.length == 0 ) return; var anchor = window.location.hash.substring(1); console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" ); highlightTarget( anchor ); }; function highlightClickTarget( event ) { console.debug( "Highlighting click target for event %o", event.target ); try { var anchor = $(event.target).attr( 'href' ).substring(1); console.debug( "Found target anchor: %s", anchor ); highlightTarget( anchor ); } catch ( err ) { console.error( "Exception while highlighting: %o", err ); }; }; function hookHighlightSyntax() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; - hljs.initHighlightingOnLoad('ruby'); + hljs.initHighlightingOnLoad('ruby','cpp'); };
razerbeans/webri
39b78b321b908fa2d98284bdfe023d8506a416d0
add prettify component and add to longfish template
diff --git a/lib/webri/components/prettify.rb b/lib/webri/components/prettify.rb new file mode 100644 index 0000000..2b708d1 --- /dev/null +++ b/lib/webri/components/prettify.rb @@ -0,0 +1 @@ +require 'webri/components/prettify/component'
razerbeans/webri
c5483df802ca5137e77d2f344a1fcd58dac752a6
add prettify component and add to longfish template
diff --git a/lib/webri/components/prettify/component.rb b/lib/webri/components/prettify/component.rb new file mode 100644 index 0000000..bf01e65 --- /dev/null +++ b/lib/webri/components/prettify/component.rb @@ -0,0 +1,15 @@ +require 'webri/components/abstract' + +module WebRI + + # The Prettify component provides a Google's universal + # syntax highlighter (http://code.google.com/p/google-code-prettify/). + # + # This is an alternative to the Highlight plugin, which is good, but + # limited in ability to be applied to selected elements. + + class Prettify < Component + end + +end + diff --git a/lib/webri/components/prettify/static/assets/prettify.css b/lib/webri/components/prettify/static/assets/prettify.css new file mode 100644 index 0000000..0f1ed75 --- /dev/null +++ b/lib/webri/components/prettify/static/assets/prettify.css @@ -0,0 +1 @@ +.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun{color:#660}.pln{color:#000}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec{color:#606}pre.prettyprint{padding:2px;border:1px solid #888}@media print{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun{color:#440}.pln{color:#000}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}} \ No newline at end of file diff --git a/lib/webri/components/prettify/static/assets/prettify.js b/lib/webri/components/prettify/static/assets/prettify.js new file mode 100644 index 0000000..8fc4c93 --- /dev/null +++ b/lib/webri/components/prettify/static/assets/prettify.js @@ -0,0 +1,23 @@ +function H(){var x=navigator&&navigator.userAgent&&/\bMSIE 6\./.test(navigator.userAgent);H=function(){return x};return x}(function(){function x(b){b=b.split(/ /g);var a={};for(var c=b.length;--c>=0;){var d=b[c];if(d)a[d]=null}return a}var y="break continue do else for if return while ",U=y+"auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile ",D=U+"catch class delete false import new operator private protected public this throw true try ", +I=D+"alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename typeof using virtual wchar_t where ",J=D+"boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient ",V=J+"as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var ", +K=D+"debugger eval export function get null set undefined var with Infinity NaN ",L="caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END ",M=y+"and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None ",N=y+"alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END ", +O=y+"case done elif esac eval fi function in local set then until ",W=I+V+K+L+M+N+O;function X(b){return b>="a"&&b<="z"||b>="A"&&b<="Z"}function u(b,a,c,d){b.unshift(c,d||0);try{a.splice.apply(a,b)}finally{b.splice(0,2)}}var Y=(function(){var b=["!","!=","!==","#","%","%=","&","&&","&&=","&=","(","*","*=","+=",",","-=","->","/","/=",":","::",";","<","<<","<<=","<=","=","==","===",">",">=",">>",">>=",">>>",">>>=","?","@","[","^","^=","^^","^^=","{","|","|=","||","||=","~","break","case","continue", +"delete","do","else","finally","instanceof","return","throw","try","typeof"],a="(?:(?:(?:^|[^0-9.])\\.{1,3})|(?:(?:^|[^\\+])\\+)|(?:(?:^|[^\\-])-)";for(var c=0;c<b.length;++c){var d=b[c];a+=X(d.charAt(0))?"|\\b"+d:"|"+d.replace(/([^=<>:&])/g,"\\$1")}a+="|^)\\s*$";return new RegExp(a)})(),P=/&/g,Q=/</g,R=/>/g,Z=/\"/g;function $(b){return b.replace(P,"&amp;").replace(Q,"&lt;").replace(R,"&gt;").replace(Z,"&quot;")}function E(b){return b.replace(P,"&amp;").replace(Q,"&lt;").replace(R,"&gt;")}var aa= +/&lt;/g,ba=/&gt;/g,ca=/&apos;/g,da=/&quot;/g,ea=/&amp;/g,fa=/&nbsp;/g;function ga(b){var a=b.indexOf("&");if(a<0)return b;for(--a;(a=b.indexOf("&#",a+1))>=0;){var c=b.indexOf(";",a);if(c>=0){var d=b.substring(a+3,c),g=10;if(d&&d.charAt(0)==="x"){d=d.substring(1);g=16}var e=parseInt(d,g);if(!isNaN(e))b=b.substring(0,a)+String.fromCharCode(e)+b.substring(c+1)}}return b.replace(aa,"<").replace(ba,">").replace(ca,"'").replace(da,'"').replace(ea,"&").replace(fa," ")}function S(b){return"XMP"===b.tagName} +function z(b,a){switch(b.nodeType){case 1:var c=b.tagName.toLowerCase();a.push("<",c);for(var d=0;d<b.attributes.length;++d){var g=b.attributes[d];if(!g.specified)continue;a.push(" ");z(g,a)}a.push(">");for(var e=b.firstChild;e;e=e.nextSibling)z(e,a);if(b.firstChild||!/^(?:br|link|img)$/.test(c))a.push("</",c,">");break;case 2:a.push(b.name.toLowerCase(),'="',$(b.value),'"');break;case 3:case 4:a.push(E(b.nodeValue));break}}var F=null;function ha(b){if(null===F){var a=document.createElement("PRE"); +a.appendChild(document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));F=!/</.test(a.innerHTML)}if(F){var c=b.innerHTML;if(S(b))c=E(c);return c}var d=[];for(var g=b.firstChild;g;g=g.nextSibling)z(g,d);return d.join("")}function ia(b){var a=0;return function(c){var d=null,g=0;for(var e=0,h=c.length;e<h;++e){var f=c.charAt(e);switch(f){case "\t":if(!d)d=[];d.push(c.substring(g,e));var i=b-a%b;a+=i;for(;i>=0;i-=" ".length)d.push(" ".substring(0,i));g=e+1;break; +case "\n":a=0;break;default:++a}}if(!d)return c;d.push(c.substring(g));return d.join("")}}var ja=/(?:[^<]+|<!--[\s\S]*?--\>|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g,ka=/^<!--/,la=/^<\[CDATA\[/,ma=/^<br\b/i;function na(b){var a=b.match(ja),c=[],d=0,g=[];if(a)for(var e=0,h=a.length;e<h;++e){var f=a[e];if(f.length>1&&f.charAt(0)==="<"){if(ka.test(f))continue;if(la.test(f)){c.push(f.substring(9,f.length-3));d+=f.length-12}else if(ma.test(f)){c.push("\n");++d}else g.push(d,f)}else{var i=ga(f); +c.push(i);d+=i.length}}return{source:c.join(""),tags:g}}function v(b,a){var c={};(function(){var g=b.concat(a);for(var e=g.length;--e>=0;){var h=g[e],f=h[3];if(f)for(var i=f.length;--i>=0;)c[f.charAt(i)]=h}})();var d=a.length;return function(g,e){e=e||0;var h=[e,"pln"],f="",i=0,j=g;while(j.length){var o,m=null,k,l=c[j.charAt(0)];if(l){k=j.match(l[1]);m=k[0];o=l[0]}else{for(var n=0;n<d;++n){l=a[n];var p=l[2];if(p&&!p.test(f))continue;k=j.match(l[1]);if(k){m=k[0];o=l[0];break}}if(!m){o="pln";m=j.substring(0, +1)}}h.push(e+i,o);i+=m.length;j=j.substring(m.length);if(o!=="com"&&/\S/.test(m))f=m}return h}}var oa=v([],[["pln",/^[^<]+/,null],["dec",/^<!\w[^>]*(?:>|$)/,null],["com",/^<!--[\s\S]*?(?:--\>|$)/,null],["src",/^<\?[\s\S]*?(?:\?>|$)/,null],["src",/^<%[\s\S]*?(?:%>|$)/,null],["src",/^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i,null],["tag",/^<\/?\w[^<>]*>/,null]]);function pa(b){var a=oa(b);for(var c=0;c<a.length;c+=2)if(a[c+1]==="src"){var d,g;d=a[c];g=c+2<a.length?a[c+2]:b.length;var e=b.substring(d, +g),h=e.match(/^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/);if(h)a.splice(c,2,d,"tag",d+h[1].length,"src",d+h[1].length+(h[2]||"").length,"tag")}return a}var qa=v([["atv",/^\'[^\']*(?:\'|$)/,null,"'"],["atv",/^\"[^\"]*(?:\"|$)/,null,'"'],["pun",/^[<>\/=]+/,null,"<>/="]],[["tag",/^[\w:\-]+/,/^</],["atv",/^[\w\-]+/,/^=/],["atn",/^[\w:\-]+/,null],["pln",/^\s+/,null," \t\r\n"]]);function ra(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d==="tag"){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=b.substring(g, +e),f=qa(h,g);u(f,a,c,2);c+=f.length-2}}return a}function r(b){var a=[],c=[];if(b.tripleQuotedStrings)a.push(["str",/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""]);else if(b.multiLineStrings)a.push(["str",/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"]);else a.push(["str",/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, +null,"\"'"]);c.push(["pln",/^(?:[^\'\"\`\/\#]+)/,null," \r\n"]);if(b.hashComments)a.push(["com",/^#[^\r\n]*/,null,"#"]);if(b.cStyleComments)c.push(["com",/^\/\/[^\r\n]*/,null]);if(b.regexLiterals)c.push(["str",/^\/(?:[^\\\*\/\[]|\\[\s\S]|\[(?:[^\]\\]|\\.)*(?:\]|$))+(?:\/|$)/,Y]);if(b.cStyleComments)c.push(["com",/^\/\*[\s\S]*?(?:\*\/|$)/,null]);var d=x(b.keywords);b=null;var g=v(a,c),e=v([],[["pln",/^\s+/,null," \r\n"],["pln",/^[a-z_$@][a-z_$@0-9]*/i,null],["lit",/^0x[a-f0-9]+[a-z]/i,null],["lit", +/^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i,null,"123456789"],["pun",/^[^\s\w\.$@]+/,null]]);function h(f,i){for(var j=0;j<i.length;j+=2){var o=i[j+1];if(o==="pln"){var m,k,l,n;m=i[j];k=j+2<i.length?i[j+2]:f.length;l=f.substring(m,k);n=e(l,m);for(var p=0,t=n.length;p<t;p+=2){var w=n[p+1];if(w==="pln"){var A=n[p],B=p+2<t?n[p+2]:l.length,s=f.substring(A,B);if(s===".")n[p+1]="pun";else if(s in d)n[p+1]="kwd";else if(/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(s))n[p+1]=s.charAt(0)==="@"?"lit": +"typ"}}u(n,i,j,2);j+=n.length-2}}return i}return function(f){var i=g(f);i=h(f,i);return i}}var G=r({keywords:W,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function sa(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d==="src"){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=G(b.substring(g,e));for(var f=0,i=h.length;f<i;f+=2)h[f]+=g;u(h,a,c,2);c+=h.length-2}}return a}function ta(b,a){var c=false;for(var d=0;d<a.length;d+=2){var g=a[d+1],e,h;if(g==="atn"){e= +a[d];h=d+2<a.length?a[d+2]:b.length;c=/^on|^style$/i.test(b.substring(e,h))}else if(g==="atv"){if(c){e=a[d];h=d+2<a.length?a[d+2]:b.length;var f=b.substring(e,h),i=f.length,j=i>=2&&/^[\"\']/.test(f)&&f.charAt(0)===f.charAt(i-1),o,m,k;if(j){m=e+1;k=h-1;o=f}else{m=e+1;k=h-1;o=f.substring(1,f.length-1)}var l=G(o);for(var n=0,p=l.length;n<p;n+=2)l[n]+=m;if(j){l.push(k,"atv");u(l,a,d+2,0)}else u(l,a,d,2)}c=false}}return a}function ua(b){var a=pa(b);a=ra(b,a);a=sa(b,a);a=ta(b,a);return a}function va(b, +a,c){var d=[],g=0,e=null,h=null,f=0,i=0,j=ia(8);function o(k){if(k>g){if(e&&e!==h){d.push("</span>");e=null}if(!e&&h){e=h;d.push('<span class="',e,'">')}var l=E(j(b.substring(g,k))).replace(/(\r\n?|\n| ) /g,"$1&nbsp;").replace(/\r\n?|\n/g,"<br />");d.push(l);g=k}}while(true){var m;m=f<a.length?(i<c.length?a[f]<=c[i]:true):false;if(m){o(a[f]);if(e){d.push("</span>");e=null}d.push(a[f+1]);f+=2}else if(i<c.length){o(c[i]);h=c[i+1];i+=2}else break}o(b.length);if(e)d.push("</span>");return d.join("")} +var C={};function q(b,a){for(var c=a.length;--c>=0;){var d=a[c];if(!C.hasOwnProperty(d))C[d]=b;else if("console"in window)console.log("cannot override language handler %s",d)}}q(G,["default-code"]);q(ua,["default-markup","html","htm","xhtml","xml","xsl"]);q(r({keywords:I,hashComments:true,cStyleComments:true}),["c","cc","cpp","cs","cxx","cyc"]);q(r({keywords:J,cStyleComments:true}),["java"]);q(r({keywords:O,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);q(r({keywords:M,hashComments:true, +multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);q(r({keywords:L,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);q(r({keywords:N,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);q(r({keywords:K,cStyleComments:true,regexLiterals:true}),["js"]);function T(b,a){try{var c=na(b),d=c.source,g=c.tags;if(!C.hasOwnProperty(a))a=/^\s*</.test(d)?"default-markup":"default-code";var e=C[a].call({},d);return va(d,g,e)}catch(h){if("console"in window){console.log(h); +console.trace()}return b}}function wa(b){var a=H(),c=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],d=[];for(var g=0;g<c.length;++g)for(var e=0;e<c[g].length;++e)d.push(c[g][e]);c=null;var h=0;function f(){var i=(new Date).getTime()+250;for(;h<d.length&&(new Date).getTime()<i;h++){var j=d[h];if(j.className&&j.className.indexOf("prettyprint")>=0){var o=j.className.match(/\blang-(\w+)\b/);if(o)o=o[1];var m=false;for(var k=j.parentNode;k;k= +k.parentNode)if((k.tagName==="pre"||k.tagName==="code"||k.tagName==="xmp")&&k.className&&k.className.indexOf("prettyprint")>=0){m=true;break}if(!m){var l=ha(j);l=l.replace(/(?:\r\n?|\n)$/,"");var n=T(l,o);if(!S(j))j.innerHTML=n;else{var p=document.createElement("PRE");for(var t=0;t<j.attributes.length;++t){var w=j.attributes[t];if(w.specified)p.setAttribute(w.name,w.value)}p.innerHTML=n;j.parentNode.replaceChild(p,j);p=j}if(a&&j.tagName==="PRE"){var A=j.getElementsByTagName("br");for(var B=A.length;--B>= +0;){var s=A[B];s.parentNode.replaceChild(document.createTextNode("\r\n"),s)}}}}}if(h<d.length)setTimeout(f,250);else if(b)b()}f()}window.PR_normalizedHtml=z;window.prettyPrintOne=T;window.prettyPrint=wa;window.PR={createSimpleLexer:v,registerLangHandler:q,sourceDecorator:r,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})(); diff --git a/lib/webri/generators/longfish/generator.rb b/lib/webri/generators/longfish/generator.rb index 1d4de16..a2f0e92 100644 --- a/lib/webri/generators/longfish/generator.rb +++ b/lib/webri/generators/longfish/generator.rb @@ -1,78 +1,80 @@ require 'webri/generators/abstract' +require 'webri/components/prettify' #require 'webri/components/subversion' require 'webri/components/github' module WebRI # = Longfish Template # # The Longfish tempolate is based on John Long's design # of the ruby-lang.org website. It was built to supply # Ruby core and stadard documentation with an "offical" # look, but there's no reason you can't use it for your # project too, if you prefer it. # class Longfish < Generator #include Subversion + include Prettify include GitHub # def path @path ||= Pathname.new(__FILE__).parent end # def site_homepage metadata.homepage end # def site_community metadata.mailinglist || metadata.wiki end # def site_repository metadata.development end # def site_news metadata.blog end # def index_title @index_title ||= parse_index_header[0] end # def index_description @index_description ||= parse_index_header[1] end # TODO: Generalize for all generators (?) def parse_index_header if options.main_page && main_page = files_toplevel.find { |f| f.full_name == options.main_page } desc = main_page.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) title = md[1] desc = md.post_match else title = options.main_page end else title = options.title desc = "This is the API documentation for '#{title}'." end return title, desc end end end diff --git a/lib/webri/generators/longfish/static/assets/favicon.ico b/lib/webri/generators/longfish/static/assets/favicon.ico new file mode 100644 index 0000000..98f440b Binary files /dev/null and b/lib/webri/generators/longfish/static/assets/favicon.ico differ diff --git a/lib/webri/generators/longfish/static/assets/long/css/high.css b/lib/webri/generators/longfish/static/assets/long/css/high.css index 084ccb4..474ef52 100644 --- a/lib/webri/generators/longfish/static/assets/long/css/high.css +++ b/lib/webri/generators/longfish/static/assets/long/css/high.css @@ -1,515 +1,521 @@ /* high.css - styles for modern browsers */ body { background-color: #213449; color: white; margin: 0; padding: 0; text-align: center; } +fieldset { + border: none; + color: white; +} .site-links { background-image: url(../img/site-links-background.gif); background-position: bottom; background-repeat: repeat-x; } .site-links a, .site-links a:visited, .site-links strong { color: white; text-decoration: none; display: block; padding: 8px; padding-left: 6px; padding-right: 6px; margin-left: 4px; float: left; } .site-links a:hover { color: white; text-decoration: underline; } .site-links strong a, .site-links strong a:visited { padding: 0; margin: 0; display: inline; } #page { background-image: url(../img/shadow.jpg); background-position: center; background-repeat: repeat-y; } #logo { background-image: url(../img/logo-background.jpg); background-position: top left; background-repeat: no-repeat; padding-top: 14px; } #logo img { position: relative; z-index: 1; } #header, #main-wrapper { background: white; text-align: left; margin-left: auto; margin-right: auto; width: 766px; } #header { background-image: url(../img/header-background.jpg); background-position: right; background-repeat: repeat-y; } #header .site-links { float: left; width: 100%; } #main { color: black; background-color: white; background-image: url(../img/columns.jpg); background-position: right; background-repeat: repeat-y; float: left; } #main .site-links { width: 766px; float: left; clear: both; margin-left: auto; margin-right: auto; text-align: center; } #content-wrapper { float: left; width: 766px; margin-right: -400px; } #head-wrapper-1 { background-color: #346090; background-image: url(../img/blue-columns.jpg); background-repeat: repeat-y; background-position: center; margin-left: 0px; margin-bottom: 24px; color: white; float: left; width: 100%; } #head-wrapper-2 { float: left; width: 100%; } #head { float: left; padding-top: 24px; padding-bottom: 24px; width: 100%; } #head h1 { font-size: 240%; padding-left: 32px; margin: 0; margin-top: 18px; margin-right: 269px; } #head a { color: white; } #intro, #code { display: inline; float: left; } #intro { color: #d3dce6; font-size: 95%; padding-left: 32px; padding-right: 23px; padding-bottom: 10px; width: 202px; } #intro h1 { background-image: url(../img/dotted-underline.gif); background-position: bottom; background-repeat: repeat-x; color: white; font-size: 240%; margin: 0; margin-bottom: .5em; padding: 0; padding-top: 4px; padding-bottom: 4px; } #intro p { line-height: 150%; margin-top: 0; margin-bottom: 1em; } #code { color: white; display: block; font-size: 95%; line-height: 110%; padding-top: 24px; width: 244px; } #code div { display: block; font-family: "Lucida Console", Monaco, monospace; padding-left: 24px; padding-right: 24px; } #code .keyword { color: #f9bb00; } #code .comment { color: #428bdd; } #code .string { color: #00cc00; } #code .blank-line { line-height: 70%; } #head .multi-page { float: right; font-weight: normal; margin-top: 18px; margin-right: 269px; padding-top: 1em; } #head .multi-page .separator { display: none; } #head .multi-page a, #head .multi-page strong { padding: 3px; padding-left: 6px; padding-right: 6px; } #head .multi-page strong { border: 2px solid #b0c5dd; } #content { margin-right: 239px; padding: 32px; padding-top: 1px; line-height: 160%; } #content h3 { background-image: url(../img/dotted-underline.gif); background-position: bottom; background-repeat: repeat-x; padding-bottom: 8px; } #content h3 a { color: #c61a1a; text-decoration: none; } #content h3 a:hover, #content h3 a:visited:hover { color: #e85353; } #content #news ul { float: left; list-style: none; margin: 0; margin-right: 10px; line-height: 120%; padding: 0; width: 220px; } #content #news ul li { background-image: url(../img/bullet.gif); background-position: left top; background-repeat: no-repeat; display: block; list-style: none; margin: 0; margin-top: .25em; margin-bottom: .75em; padding: 0; padding-left: 12px; } #content #news ul a { display: block; font-family: Georgia, Palatino, "Times New Roman", Times, serif; font-size: 125%; line-height: 110%; text-decoration: none; } #content #news ul a:hover, #content #news ul a:visited:hover { text-decoration: underline; } #content #news .more { clear: both; margin-top: 1em; } #content pre { overflow: auto; + letter-spacing: 0; + font-family: monospace; } #content pre.code { background-color: #213449; background-image: url(../img/code-box-top-left.gif); background-position: top left; background-repeat: no-repeat; color: white; display: block; width: 100%; } #content pre.code code { background-image: url(../img/code-box-bottom-right.gif); background-position: bottom right; background-repeat: no-repeat; display: block; overflow: auto; - font-family: "Lucida Console", Monaco, monospace; - font-size: 115%; + font-family: monospace; /* "Lucida Console", Monaco, monospace; */ + font-size: 100%; line-height: 135%; - padding: 15px; + padding: 10px; } #content pre.code .comment, .ruby-comment, .cmt { color: #428bdd; } #content pre.code .keyword, .ruby-keyword, .kw { color: #f9bb00; } #content pre.code .method, .ruby-node { color: #fff; } #content pre.code .class, .ruby-constant { color: #fff; } #content pre.code .module { color: #050; } #content pre.code .punct { color: #8aa6c1; } #content pre.code .symbol { color: #b53b3c; } #content pre.code .number, .ruby-value { color: #eddd3d; } #content pre.code .string, .str { color: #00cc00; } #content pre.code .ruby-value .str { color: #00cc00; } #content pre.code .char { color: #f07; } #content pre.code .ident, .ruby-identifier { color: #fff; } #content pre.code .constant, .ruby-constant { color: #8aa6c1; } #content pre.code .regex, .ruby-regexp { color: #ca4344; } #content pre.code .global { color: #fff; } #content pre.code .expr, .ruby-operator { color: #fff; } #content pre.code .escape { color: #eddd3d; } #content pre.code .attribute, .ruby-ivar { color: #8aa6c1; } #content pre.code.xml-code .string { color: #fff; } #content dl dt { font-family: Georgia, Palatino, "Times New Roman", Times, serif; font-weight: bold; font-size: 120%; margin-top: 1em; } #content dl dd { - margin-left: 1.5em; + margin-left: 0.1em; } #content .error { color: red; } #content .fieldset { border-top: 3px solid #39618b; background: #e2ebf6; background: #e2eff6; width: 100%; } #subscriptions-form .fieldset td { background-image: url(../img/dark-dotted-underline.gif); background-position: bottom; background-repeat: repeat-x; padding: 5px; padding-left: 15px; } #content .fieldset td.label { text-align: right; } #content .buttons { margin-top: 1.5em; } #content .buttons input[type=submit] { font-size: 130%; } #sidebar-wrapper { float: right; width: 237px; } #sidebar { font-size: 85%; margin-top: 26px; padding-left: 20px; padding-right: 20px; padding-bottom: 20px; } #sidebar h3 { background-image: url(../img/dotted-underline.gif); background-position: bottom; background-repeat: repeat-x; color: #333333; font-size: 130%; margin-top: 2.5em; margin-bottom: .5em; padding-bottom: 4px; } #sidebar ul, #sidebar ul li { margin-left: .75em; margin-top: 0; padding-left: 0; } #sidebar ul li { margin-bottom: .25em; } #sidebar .navigation { margin-bottom: 22px; overflow: hidden; background-color: #cbdff6; } #sidebar .navigation ul { padding-top: 4px; padding-bottom: 4px; } #sidebar .navigation h3, #sidebar .navigation ul li, #sidebar .navigation .more { margin: 0; padding: 4px; padding-left: 8px; padding-right: 8px; } #sidebar .navigation h3 { font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: 100%; font-weight: normal; background: #1a4676; color: white; margin: 0; padding-bottom: 5px; } #sidebar .navigation h3 strong { font-family: Georgia, Palatino, "Times New Roman", Times, serif; font-size: 130%; } #sidebar .navigation ul, #sidebar .navigation ul li { list-style: none; margin: 0; } #sidebar .navigation ul li { background-color: #cbdff6; background-image: url(../img/dark-dotted-underline.gif); background-position: bottom; background-repeat: repeat-x; padding-bottom: 4px; color: #555; } #sidebar .navigation .more { padding-bottom: 8px; } #sidebar .navigation .menu a, #sidebar .navigation .more a { text-decoration: none; } #sidebar .navigation .menu a:hover, #sidebar .navigation .menu a:visited:hover, #sidebar .navigation .more a:hover, #sidebar .navigation .more a:visited:hover { text-decoration: underline; } #search-box { clear: both; margin-left: auto; margin-right: auto; text-align: left; width: 738px; } #search-form { position: absolute; top: 57px; width: 738px; } #search-box .fieldset { float: right; } #search-form .field { width: 214px; height: 20px; } #search-form .button { width: 74px; height: 24px; } #foot { clear: both; } #footer p { color: #8D959F; font-size: 85%; margin: auto; margin-top: 0; margin-bottom: .75em; padding: 14px; padding-top: 0; padding-bottom: 0; text-align: left; width: 738px; } #footer a, #footer a:visited { color: #B6BCC2; } #footer a:hover, #footer a:visited:hover { color: white; } #footer .fine-print { background-color: #213449; background-image: url(../img/footer-background.jpg); background-position: top; background-repeat: no-repeat; clear: both; line-height: 140%; padding-top: 10px; } /* layouts */ #home-page-layout #head-wrapper-1 { background-image: url(../img/blue-columns-home-page.jpg); margin-bottom: -5px; } #home-page-layout #head-wrapper-1:first-child { margin-bottom: 24px; } #home-page-layout #head-wrapper-2 { background-image: url(../img/blue-columns-top-home-page.jpg); background-repeat: no-repeat; background-position: top; } #home-page-layout #head { background-image: url(../img/blue-columns-bottom-home-page.jpg); background-repeat: no-repeat; background-position: bottom; } diff --git a/lib/webri/generators/longfish/static/assets/long/img/rb.png b/lib/webri/generators/longfish/static/assets/long/img/rb.png new file mode 100644 index 0000000..4a32a5e Binary files /dev/null and b/lib/webri/generators/longfish/static/assets/long/img/rb.png differ diff --git a/lib/webri/generators/longfish/static/assets/main.js b/lib/webri/generators/longfish/static/assets/main.js index 617c6f3..81e63e1 100644 --- a/lib/webri/generators/longfish/static/assets/main.js +++ b/lib/webri/generators/longfish/static/assets/main.js @@ -1,34 +1,44 @@ function toggleSource( id ) { var elem var link if( document.getElementById ) { elem = document.getElementById( id ) link = document.getElementById( "l_" + id ) } else if ( document.all ) { elem = eval( "document.all." + id ) link = eval( "document.all.l_" + id ) } else return false; if( elem.style.display == "block" ) { elem.style.display = "none" // link.innerHTML = "show" } else { elem.style.display = "block" // link.innerHTML = "hide" } } function openCode( url ) { window.open( url, "SOURCE_CODE", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=480,width=750" ).focus(); } + +function hookHighlightSyntax() { + /* TODO: wrap code if not present? */ + $('pre:not(.code)').wrapInner('<code class="prettyprint"></code>'); + // $('pre.code').wrapInner('<code></code>'); +/* hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby', 'cpp'); */ + prettyPrint(); +}; + diff --git a/lib/webri/generators/longfish/static/assets/prettify.css b/lib/webri/generators/longfish/static/assets/prettify.css new file mode 100644 index 0000000..734e5b9 --- /dev/null +++ b/lib/webri/generators/longfish/static/assets/prettify.css @@ -0,0 +1,50 @@ +.str{color:#00cc00;} +.kwd{color:#f9bb00;} +.com{color:#428bdd;} +.typ{color:#b53b3c;} +.lit{color:#eddd3d;} +.pun{color:#8aa6c1;} +.pln{color:#ffffff} +.tag{color:#8aa6c1;} +.atn{color:#8aa6c1;} +.atv{color:#00cc00;} +.dec{color:#b53b3c;} + +/* pre.prettyprint{padding:2px;border:1px solid #888} */ + +@media print{ + .str{color:#060} + .kwd{color:#006;font-weight:bold} + .com{color:#600;font-style:italic} + .typ{color:#404;font-weight:bold} + .lit{color:#044} + .pun{color:#440} + .pln{color:#000} + .tag{color:#006;font-weight:bold} + .atn{color:#404} + .atv{color:#060} +} + +#content pre { + background-color: #213449; + background-image: url(long/img/code-box-top-left.gif); + background-position: top left; + background-repeat: no-repeat; + color: white; + display: block; + width: 100%; +} + +#content pre code.prettyprint { + background-image: url(long/img/code-box-bottom-right.gif); + background-position: bottom right; + background-repeat: no-repeat; + display: block; + overflow: auto; + font-family: monospace; /*, "Lucida Console", Monaco, monospace; */ + font-size: 100%; + line-height: 135%; + padding: 10px 0px 10px 5px; + margin-left: -5px; +} + diff --git a/lib/webri/generators/longfish/template/class.rhtml b/lib/webri/generators/longfish/template/class.rhtml index 4a584e4..1d92b13 100644 --- a/lib/webri/generators/longfish/template/class.rhtml +++ b/lib/webri/generators/longfish/template/class.rhtml @@ -1,108 +1,119 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title><%= title %></title> <link rel="shortcut icon" type="image/x-icon" href="<%= rel_prefix %>/assets/favicon.ico" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/low.css" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/screen.css" media="screen" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/print.css" media="print" /> + <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/prettify.css" /> <link rel="alternate stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/low_vision_screen.css" media="screen" title="Low vision" /> - <script src="<%= rel_prefix %>/assets/jquery.js" type="text/javascript" charset="utf-8"></script> - <script src="<%= rel_prefix %>/assets/main.js" type="text/javascript" charset="utf-8"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/jquery.js" ></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/prettify.js"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/quicksearch.js"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/main.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + hookHighlightSyntax(); + hookQuickSearch(); + // $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> </head> <body> <div id="page"> <div id="header"> <div id="logo" style="font-size: 52px; font-family: times, serif; font-style: italic; color: black;"> <img src="<%= rel_prefix %>/assets/long/img/logo.gif" alt="" title="" height="119" align="absmiddle"><%= title %> </div> <div class="site-links"> <a href="<%= rel_prefix %>/index.html">Index</a><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> <hr class="hidden-modern"> <div id="main-wrapper"> <div id="main"> <%= include_template 'class_context.rhtml', {:context => klass, :rel_prefix => rel_prefix} %> <hr class="hidden-modern"> <div class="foot"> <div class="site-links"> <a href="<%= rel_prefix %>/index.html">Index</a><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> </div> </div> <!-- end main-wrapper --> <div id="search-box"> <form id="search-form" action="http://www.google.com/cse"> <table class="fieldset"> <tbody><tr> <td> <input class="field" name="q" size="31" style="background: white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" onfocus="this.style.background='white'" onblur="if (/^\s*$/.test(this.value)) this.style.background='white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) left no-repeat'" type="text"> </td> <td> <input name="cx" value="013598269713424429640:g5orptiw95w" type="hidden"> <input name="ie" value="UTF-8" type="hidden"> <input class="button" name="sa" value="Search" type="submit"> </td> </tr> </tbody></table> </form> </div> <!-- end search-box --> <div id="footer"> <div class="fine-print"> <!-- <p>Content available in <a href="http://www.ruby-lang.org/en/">English</a>, <a href="http://www.ruby-lang.org/fr/">French</a>, <a href="http://www.ruby-lang.org/ja/">Japanese</a>, <a href="http://www.ruby-lang.org/ko/">Korean</a>, <a href="http://www.ruby-lang.org/pl/">Polish</a>, <a href="http://www.ruby-lang.org/es/">Spanish</a>, <a href="http://www.ruby-lang.org/pt/">Portuguese</a>, <a href="http://www.ruby-lang.org/zh_cn/">Simplified Chinese</a>, <a href="http://www.ruby-lang.org/zh_TW/">Traditional Chinese</a>, <a href="http://www.ruby-lang.org/id/">Bahasa Indonesia</a>, <a href="http://www.ruby-lang.org/de/">German</a>, <a href="http://www.ruby-lang.org/it/">Italian</a> and <a href="http://www.ruby-lang.org/bg/">Bulgarian</a>.</p> --> <p>This website is made with Ruby and powered by <a href="http://github.com/proutils/webri">WebRI</a> v<%= WebRI::VERSION %>. It is proudly maintained by <a href="http://rubyidentity.org/">members of the Ruby community</a>. Please contact our <a href="mailto:[email protected]">webmaster</a> for questions or comments concerning this website.</p> </div> </div> </div> <!-- end page --> </body> </html> diff --git a/lib/webri/generators/longfish/template/class_context.rhtml b/lib/webri/generators/longfish/template/class_context.rhtml index 2784357..dfafa18 100644 --- a/lib/webri/generators/longfish/template/class_context.rhtml +++ b/lib/webri/generators/longfish/template/class_context.rhtml @@ -1,307 +1,309 @@ <% desc = context.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) name = md[1] desc = md.post_match else name = context.name end %> <div id="content-wrapper"> <div id="head-wrapper-1"> <div id="head-wrapper-2"> <div id="head"> <h1><%= name %></h1> </div> </div> </div> <div id="content"> <!-- DESCRIPTION --> <% unless desc.empty? %> <div class="description"> <%= desc %> </div> <% end %> <!-- REQUIRES --> <% unless context.requires.empty? %> <h3>Required Files</h3> <ul> <% context.requires.each do |req| %> <li><%= h req.name %></li> <% end %> </ul> <% end %> <!-- CONTENTS --> <% sections = context.sections.select { |section| section.title } %> <% unless sections.empty? %> <h3>Contents</h3> <ul> <% sections.each do |section| %> <li><a href="#<%= section.sequence %>"><%= h section.title %></a></li> <% end %> </ul> <% end %> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> <% end %> <!-- DESCRIPTION (of what?) ---> <% sections.each do |section| %> <h3><a name="<%= h section.sequence %>"><%= h section.title %></a></h3> <% unless (description = section.description).empty? %> <div class="description"> <%= description %> </div> <% end %> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= context.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> <% end %> <!-- CONSTANTS --> <% unless context.constants.empty? %> <h3>Constants</h3> <table border='0' cellpadding='5'> <% context.each_constant do |const| %> <tr valign='top'> <td class="attr-name"><%= h const.name %></td> <td>=</td> <td class="attr-value"><%= h const.value %></td> </tr> <% unless (description = const.description).empty? %> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"><%= description %></td> </tr> <% end %> <% end %> </table> <% end %> <!-- ATTRIBUTES --> <% unless context.attributes.empty? %> <h3>Attributes</h3> <table border='0' cellpadding='5'> <% context.each_attribute do |attrib| %> <tr valign='top'> <td class='attr-rw'> [<%= attrib.rw %>] </td> <td class='attr-name'><%= h attrib.name %></td> <td class='attr-desc'><%= attrib.description.strip %></td> </tr> <% end %> </table> <% end %> <!-- METHODS --> <% context.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? next unless options.show_all || visibility == :public || visibility == :protected || methods.any? {|m| m.force_documentation } %> <h3><%= type.capitalize %> <%= visibility.to_s.capitalize %> methods</h3> <dl> <% methods.each do |method| %> <p class="source-link" style="float: right;"> - <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source"><img src="<%= rel_prefix %>/assets/img/bullet_toggle_plus.png" alt="[+]"></a> + <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source"><img src="<%= rel_prefix %>/assets/long/img/rb.png" alt="[+]"></a> <% if markup =~ /File\s(\S+), line (\d+)/ path = $1 line = $2.to_i end github = github_url(path) if github %> | <a href="<%= "#{github}#L#{line}" %>" target="_blank" class="github_url">on GitHub</a> <% end %> </p> <dt> <% if method.call_seq %> - <a name="<%= method.aref %>"></a><b><%= method.call_seq.gsub(/->/, '&rarr;') %></b> + <% cseq = method.call_seq.gsub(/[-=]>/, '&rarr;').gsub("\n", '<br/>') %> + <a name="<%= method.aref %>"></a><b><%= cseq %></b> <% else %> - <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> + <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> <% end %> </dt> <dd> + <% if method.token_stream %> + <% markup = method.markup_code %> + <div id="<%= method.aref %>_source" style="display: none;"> + <pre class="code"><code><%= method.markup_code %></code></pre> + </div> + <% end %> + <% if (description = method.description).empty? %> Not Documented <% else %> <%# TODO delete this dirty hack when documentation for example for JavaScriptHelper will not be cutted off by <script> tag %> <%= description.gsub('<script>'){ |m| h(m) } %> <% end %> <% unless method.aliases.empty? %> <div class="aka"> This method is also aliased as <% method.aliases.each do |aka| %> <a href="<%= context.aref_to aka.path %>"><%= h aka.name %></a> <% end %> </div> <% end %> - <% if method.token_stream %> - <% markup = method.markup_code %> - <div id="<%= method.aref %>_source" style="display: none;"> - <pre class="code"><code><%= method.markup_code %></code></pre> - </div> - <% end %> </dd> <% end %> <% end %> <% end %> </div> </div> <hr class="hidden-modern" /> <div id="sidebar-wrapper"> <div id="sidebar"> - <div class="navigation"> + <div class="navigation" style="background-color: transparent;"> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" style="width: 95%;" /> </fieldset> </form> </div> <br/><br/> <!-- PARENT --> <% if context.parent %> <div class="navigation"> <h3>Parent</h3> <ul> <li><a href="<%= context.aref_to context.parent.path %>"><%= context.parent.name %></a></li> </ul> </div> <% end %> <!-- SUPERCLASS --> <% if !context.is_a?(RDoc::TopLevel) && context.type == 'class' %> <% if context.superclass %> <div class="navigation"> <h3>Superclass</h3> <ul> <li> <% unless String === context.superclass %> <a href="<%= context.aref_to context.superclass.path %>"><%= context.superclass.full_name %></a> <% else %> <%= context.superclass %> <% end %> </li> </ul> </div> <% end %> <% end %> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <div class="navigation"> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> </div> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <div class="navigation"> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><a href="<%= context.aref_to mod.path %>"><%= mod.full_name.sub(context.full_name+'::', '') %></a></li> <% end %> </ul> </div> <% end %> <!-- METHOD LIST --> <% list = context.method_list unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end %> <% unless list.empty? %> <div class="navigation"> <h3>Methods</h3> - <ul class="menu"> + <ul class="menu quicksearch-target"> <% list.sort{ |a, b| a.name <=> b.name }.each do |method| %> <li><a href="#<%= method.aref %>"><%= method.name %></a></li> <% end %> </ul> </div> <% end %> <!-- IN FILES --> <div class="navigation"> <h3>In Files</h3> <ul> <% context.in_files.each do |tl| %> <li class="file"> <a href="<%= rel_prefix %>/<%= h tl.path %>" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a> </li> <% end %> </ul> </div> </div> </div> diff --git a/lib/webri/generators/longfish/template/file.rhtml b/lib/webri/generators/longfish/template/file.rhtml index 1e7ec59..9741d3f 100644 --- a/lib/webri/generators/longfish/template/file.rhtml +++ b/lib/webri/generators/longfish/template/file.rhtml @@ -1,108 +1,119 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title><%= title %></title> <link rel="shortcut icon" type="image/x-icon" href="<%= rel_prefix %>/assets/favicon.ico" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/low.css" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/screen.css" media="screen" /> <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/print.css" media="print" /> + <link rel="stylesheet" type="text/css" href="<%= rel_prefix %>/assets/prettify.css" /> <link rel="alternate stylesheet" type="text/css" href="<%= rel_prefix %>/assets/long/css/low_vision_screen.css" media="screen" title="Low vision" /> - <script src="<%= rel_prefix %>/assets/jquery.js" type="text/javascript" charset="utf-8"></script> - <script src="<%= rel_prefix %>/assets/main.js" type="text/javascript" charset="utf-8"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/jquery.js" ></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/prettify.js"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/quicksearch.js"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/main.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + hookHighlightSyntax(); + hookQuickSearch(); + // $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> </head> <body> <div id="page"> <div id="header"> <div id="logo" style="font-size: 52px; font-family: times, serif; font-style: italic; color: black;"> <img src="<%= rel_prefix %>/assets/long/img/logo.gif" alt="" title="" height="119" align="absmiddle"><%= title %> </div> <div class="site-links"> <a href="<%= rel_prefix %>/index.html">Index</a><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> <hr class="hidden-modern"> <div id="main-wrapper"> <div id="main"> <%= include_template 'file_context.rhtml', {:context => file, :rel_prefix => rel_prefix} %> <hr class="hidden-modern"> <div class="foot"> <div class="site-links"> <a href="<%= rel_prefix %>/index.html">Index</a><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> </div> </div> <!-- end main-wrapper --> <div id="search-box"> <form id="search-form" action="http://www.google.com/cse"> <table class="fieldset"> <tbody><tr> <td> <input class="field" name="q" size="31" style="background: white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" onfocus="this.style.background='white'" onblur="if (/^\s*$/.test(this.value)) this.style.background='white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) left no-repeat'" type="text"> </td> <td> <input name="cx" value="013598269713424429640:g5orptiw95w" type="hidden"> <input name="ie" value="UTF-8" type="hidden"> <input class="button" name="sa" value="Search" type="submit"> </td> </tr> </tbody></table> </form> </div> <!-- end search-box --> <div id="footer"> <div class="fine-print"> <!-- <p>Content available in <a href="http://www.ruby-lang.org/en/">English</a>, <a href="http://www.ruby-lang.org/fr/">French</a>, <a href="http://www.ruby-lang.org/ja/">Japanese</a>, <a href="http://www.ruby-lang.org/ko/">Korean</a>, <a href="http://www.ruby-lang.org/pl/">Polish</a>, <a href="http://www.ruby-lang.org/es/">Spanish</a>, <a href="http://www.ruby-lang.org/pt/">Portuguese</a>, <a href="http://www.ruby-lang.org/zh_cn/">Simplified Chinese</a>, <a href="http://www.ruby-lang.org/zh_TW/">Traditional Chinese</a>, <a href="http://www.ruby-lang.org/id/">Bahasa Indonesia</a>, <a href="http://www.ruby-lang.org/de/">German</a>, <a href="http://www.ruby-lang.org/it/">Italian</a> and <a href="http://www.ruby-lang.org/bg/">Bulgarian</a>.</p> --> <p>This website is made with Ruby and powered by <a href="http://github.com/proutils/webri">WebRI</a> v<%= WebRI::VERSION %>. It is proudly maintained by <a href="http://rubyidentity.org/">members of the Ruby community</a>. Please contact our <a href="mailto:[email protected]">webmaster</a> for questions or comments concerning this website.</p> </div> </div> </div> <!-- end page --> </body> </html> diff --git a/lib/webri/generators/longfish/template/file_context.rhtml b/lib/webri/generators/longfish/template/file_context.rhtml index 32bdbd1..e29716c 100644 --- a/lib/webri/generators/longfish/template/file_context.rhtml +++ b/lib/webri/generators/longfish/template/file_context.rhtml @@ -1,313 +1,313 @@ <% desc = context.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) name = md[1] desc = md.post_match else name = context.name end %> <div id="content-wrapper"> <div id="head-wrapper-1"> <div id="head-wrapper-2"> <div id="head"> <h1><%= name %></h1> </div> </div> </div> <div id="content"> <!-- DESCRIPTION --> <% unless desc.empty? %> <div class="description"> <%= desc %> </div> <% end %> <!-- REQUIRES --> <% unless context.requires.empty? %> <h3>Required Files</h3> <ul> <% context.requires.each do |req| %> <li><%= h req.name %></li> <% end %> </ul> <% end %> <!-- CONTENTS --> <% sections = context.sections.select { |section| section.title } %> <% unless sections.empty? %> <h3>Contents</h3> <ul> <% sections.each do |section| %> <li><a href="#<%= section.sequence %>"><%= h section.title %></a></li> <% end %> </ul> <% end %> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> <% end %> <!-- DESCRIPTION (of what?) ---> <% sections.each do |section| %> <h3><a name="<%= h section.sequence %>"><%= h section.title %></a></h3> <% unless (description = section.description).empty? %> <div class="description"> <%= description %> </div> <% end %> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= context.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> <% end %> <!-- CONSTANTS --> <% unless context.constants.empty? %> <h3>Constants</h3> <table border='0' cellpadding='5'> <% context.each_constant do |const| %> <tr valign='top'> <td class="attr-name"><%= h const.name %></td> <td>=</td> <td class="attr-value"><%= h const.value %></td> </tr> <% unless (description = const.description).empty? %> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"><%= description %></td> </tr> <% end %> <% end %> </table> <% end %> <!-- ATTRIBUTES --> <% unless context.attributes.empty? %> <h3>Attributes</h3> <table border='0' cellpadding='5'> <% context.each_attribute do |attrib| %> <tr valign='top'> <td class='attr-rw'> [<%= attrib.rw %>] </td> <td class='attr-name'><%= h attrib.name %></td> <td class='attr-desc'><%= attrib.description.strip %></td> </tr> <% end %> </table> <% end %> <!-- METHODS --> <% context.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? next unless options.show_all || visibility == :public || visibility == :protected || methods.any? {|m| m.force_documentation } %> <h3><%= type.capitalize %> <%= visibility.to_s.capitalize %> methods</h3> <dl> <% methods.each do |method| %> <dt> <% if method.call_seq %> <a name="<%= method.aref %>"></a><b><%= method.call_seq.gsub(/->/, '&rarr;') %></b> <% else %> <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> <% end %> </dt> <dd> <% if (description = method.description).empty? %> Not Documented <% else %> <%# TODO delete this dirty hack when documentation for example for JavaScriptHelper will not be cutted off by <script> tag %> <%= description.gsub('<script>'){ |m| h(m) } %> <% end %> <% unless method.aliases.empty? %> <div class="aka"> This method is also aliased as <% method.aliases.each do |aka| %> <a href="<%= context.aref_to aka.path %>"><%= h aka.name %></a> <% end %> </div> <% end %> <% if method.token_stream %> <% markup = method.markup_code %> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source">show</a> <% if markup =~ /File\s(\S+), line (\d+)/ path = $1 line = $2.to_i end github = github_url(path) if github %> | <a href="<%= "#{github}#L#{line}" %>" target="_blank" class="github_url">on GitHub</a> <% end %> </p> <div id="<%= method.aref %>_source" class="dyn-source"> <pre><%= method.markup_code %></pre> </div> </div> <% end %> </dd> <% end %> <% end %> <% end %> </div> </div> <hr class="hidden-modern" /> <div id="sidebar-wrapper"> <div id="sidebar"> - <div class="navigation"> + <div class="navigation" style="background-color: transparent;"> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" style="width: 95%;" /> </fieldset> </form> </div> <br/><br/> <!-- LAST MODIFIED --> <div class="navigation"> <h3>Last Modified</h3> <ul> <li class="modified-date"><%= context.last_modified %></li> </ul> </div> <% if !context.requires.empty? %> <div class="navigation"> <h3>Requires</h3> <ul> <% context.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </div> <% end %> <!-- TODO: GitHub ? --> <!-- Web CVS --> <% if options.webcvs %> <div class="navigation"> <h3 class="scs-url">Trac URL</h3> <ul> <li><a target="_top" href="<%= context.cvs_url %>"><%= context.cvs_url %></a></li> </ul> </div> <% end %> <!-- <!-- PARENT --> <% if context.parent %> <div class="navigation"> <h3>Parent</h3> <ul> <li><a href="<%= context.aref_to context.parent.path %>"><%= context.parent.name %></a></li> </ul> </div> <% end %> --> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <div class="navigation"> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> </div> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <div class="navigation"> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><a href="<%= context.aref_to mod.path %>"><%= mod.full_name.sub(context.full_name+'::', '') %></a></li> <% end %> </ul> </div> <% end %> <!-- METHOD LIST --> <% list = context.method_list unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end %> <% unless list.empty? %> <div class="navigation"> <h3>Methods</h3> - <ul class="menu"> + <ul class="menu quicksearch-target"> <% list.sort{ |a, b| a.name <=> b.name }.each do |method| %> <li><a href="#<%= method.aref %>"><%= method.name %></a></li> <% end %> </ul> </div> <% end %> </div> </div> diff --git a/lib/webri/generators/longfish/template/index.rhtml b/lib/webri/generators/longfish/template/index.rhtml index 02f3dce..f12353b 100644 --- a/lib/webri/generators/longfish/template/index.rhtml +++ b/lib/webri/generators/longfish/template/index.rhtml @@ -1,202 +1,205 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title><%= title %></title> <link rel="shortcut icon" type="image/x-icon" href="assets/favicon.ico" /> <link rel="stylesheet" type="text/css" href="assets/long/css/low.css" /> <link rel="stylesheet" type="text/css" href="assets/long/css/screen.css" media="screen" /> <link rel="stylesheet" type="text/css" href="assets/long/css/print.css" media="print" /> + <link rel="stylesheet" type="text/css" href="assets/prettify.css" /> <link rel="alternate stylesheet" type="text/css" href="assets/long/css/low_vision_screen.css" media="screen" title="Low vision" /> - <script src="assets/jquery.js" type="text/javascript" charset="utf-8"></script> - <script src="assets/main.js" type="text/javascript" charset="utf-8"></script> - <script src="assets/quicksearch.js" type="text/javascript" charset="utf-8"></script> + <script type="text/javascript" src="assets/jquery.js"></script> + <script type="text/javascript" src="<%= rel_prefix %>/assets/prettify.js"></script> + <script type="text/javascript" src="assets/quicksearch.js"></script> + <script type="text/javascript" src="assets/main.js"></script> <script type="text/javascript"> $(document).ready( function() { - // hookHighlightSyntax(); + hookHighlightSyntax(); hookQuickSearch(); // $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body> <div id="page"> <div id="header"> <div id="logo" style="font-size: 52px; font-family: times, serif; font-style: italic; color: black;"> <img src="assets/long/img/logo.gif" alt="Ruby - A Programmer's Best Friend" title="" height="119" align="absmiddle"><%= title %> </div> <div class="site-links"> <span><strong>Index</strong></span><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> <hr class="hidden-modern"> <div id="main-wrapper"> <div id="main"> <div id="content-wrapper"> <div id="head-wrapper-1"> <div id="head-wrapper-2"> <div id="head"> <h1><%= index_title %></h1> </div> </div> </div> <div id="content"> <%= index_description %> </div> </div> <!-- content-wrapper --> <hr class="hidden-modern" /> <div id="sidebar-wrapper"> <div id="sidebar"> <div class="navigation" style="background-color: transparent;"> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" style="width: 95%;"/> </fieldset> </form> </div> <hr class="hidden-modern" /><br/><br/> <!-- TOPLEVEL FILES --> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div class="navigation"> <h3 class="section-header">Information</h3> <ul class="quicksearch-target"> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <!-- CLASS INDEX --> <div class="navigation"> <h3 class="section-header">Class Index</h3> <ul class="quicksearch-target"> - <% classes_salient.each do |index_klass| %> + <% classes.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> - <!-- METHODS --> + <!-- METHOD INDEX --> <div class="navigation"> <h3 class="section-header">Method Index</h3> <ul class="quicksearch-target"> <% methods_all.each do |method| %> - <li class="method" style="clear: both;"> + <li class="method" style="clear: both; overflow:hidden; white-space:nowrap;"> <a href="<%= method.path %>" title="<%= method.parent.full_name %>"> <%= method.pretty_name %> </a> + &nbsp;<span style="font-size: 80%; color: #777;"><%= method.parent.full_name %></span> </li> <% end %> </ul> </div> <!-- FILE INDEX --> <!-- TODO --> </div> </div> <!-- sidebar-wrapper --> <hr class="hidden-modern"> <div class="foot"> <div class="site-links"> <span><strong>Index</strong></span><span class="separator"> | </span> <% if site_homepage %> <a href="<%= site_homepage %>">Home Page</a><span class="separator"> |</span> <% end %> <% if site_community %> <a href="<%= site_community %>">Community</a><span class="separator"> | </span> <% end %> <% if site_news %> <a href="<%= site_news %>">News</a><span class="separator"> | </span> <% end %> <% if site_repository %> <a href="<%= site_repository %>">Repository</a><span class="separator"> | </span> <% end %> <a href="http://www.ruby-lang.org/en/about/">About Ruby</a> </div> </div> </div> </div> <!-- end main-wrapper --> <div id="search-box"> <form id="search-form" action="http://www.google.com/cse"> <table class="fieldset"> <tbody><tr> <td> <input class="field" name="q" size="31" style="background: white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" onfocus="this.style.background='white'" onblur="if (/^\s*$/.test(this.value)) this.style.background='white url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) left no-repeat'" type="text"> </td> <td> <input name="cx" value="013598269713424429640:g5orptiw95w" type="hidden"> <input name="ie" value="UTF-8" type="hidden"> <input class="button" name="sa" value="Search" type="submit"> </td> </tr> </tbody></table> </form> </div> <!-- end search-box --> <div id="footer"> <div class="fine-print"> <!-- <p>Content available in <a href="http://www.ruby-lang.org/en/">English</a>, <a href="http://www.ruby-lang.org/fr/">French</a>, <a href="http://www.ruby-lang.org/ja/">Japanese</a>, <a href="http://www.ruby-lang.org/ko/">Korean</a>, <a href="http://www.ruby-lang.org/pl/">Polish</a>, <a href="http://www.ruby-lang.org/es/">Spanish</a>, <a href="http://www.ruby-lang.org/pt/">Portuguese</a>, <a href="http://www.ruby-lang.org/zh_cn/">Simplified Chinese</a>, <a href="http://www.ruby-lang.org/zh_TW/">Traditional Chinese</a>, <a href="http://www.ruby-lang.org/id/">Bahasa Indonesia</a>, <a href="http://www.ruby-lang.org/de/">German</a>, <a href="http://www.ruby-lang.org/it/">Italian</a> and <a href="http://www.ruby-lang.org/bg/">Bulgarian</a>.</p> --> <p> <% if $DEBUG_RDOC %> <span id="debugging-toggle"><img src="assets/long/img/bug.png" alt="[debug]" title="Debug Toggle" height="16" width="16" align="right" style="margin-left: 6px;"/></span> <% end %> <a href="http://validator.w3.org/check/referer"><img src="assets/long/img/check.png" alt="[validate]" title="Validate" height="16" width="16" align="right" style="margin-left: 6px;" /></a> This website is made with Ruby and powered by <a href="http://github.com/proutils/webri">WebRI</a> v<%= WebRI::VERSION %>. It is proudly maintained by <a href="http://rubyidentity.org/">members of the Ruby community</a>. Please contact our <a href="mailto:[email protected]">webmaster</a> for questions or comments concerning this website. </p> </div> </div> </div> <!-- end page --> </body> </html>
razerbeans/webri
81f34a09c85b4ef95db2cbabb92af59879801832
add 'pre code' to all of the highlight component's styles
diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/ascetic.css b/lib/webri/components/highlight/static/assets/highlight/styles/ascetic.css index b869c71..2f0b9da 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/ascetic.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/ascetic.css @@ -1,42 +1,42 @@ /* Original style from softwaremaniacs.org (c) Ivan Sagalaev <[email protected]> */ pre code { display: block; background: white; color: black; border: solid #CCC 1px; } -.string, -.attribute .value, -.filter .argument, -.addition, -.change, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .attribute .value, +pre code .filter .argument, +pre code .addition, +pre code .change, +pre code .apache .tag, +pre code .apache .cbracket { color: #888; } -.comment, -.template_comment, -.shebang, -.doctype, -.pi, -.javadoc, -.deletion, -.apache .sqbracket { +pre code .comment, +pre code .template_comment, +pre code .shebang, +pre code .doctype, +pre code .pi, +pre code .javadoc, +pre code .deletion, +pre code .apache .sqbracket { color: #CCC; } -.keyword, -.tag .title, -.ini .title, -.winutils, -.flow, -.lisp .title, -.apache .tag { +pre code .keyword, +pre code .tag .title, +pre code .ini .title, +pre code .winutils, +pre code .flow, +pre code .lisp .title, +pre code .apache .tag { font-weight: bold; } diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/brown_paper.css b/lib/webri/components/highlight/static/assets/highlight/styles/brown_paper.css index e4518e1..0b19289 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/brown_paper.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/brown_paper.css @@ -1,104 +1,105 @@ /* Brown Paper style from goldblog.com.ua (c) Zaripov Yura <[email protected]> */ pre code[class]:after { content: 'highlight: ' attr(class); display: block; text-align: right; font-size: smaller; color: #2c2c2c; background: transparent; border-top: solid 1px black; padding-top: 0.5em; } pre code { display: block; background:#b7a68e url(./brown_papersq.png); padding-left:10px; padding-top:10px; } -.keyword, -.literal, -.change, -.winutils, -.flow, -.lisp .title { +pre code .keyword, +pre code .literal, +pre code .change, +pre code .winutils, +pre code .flow, +pre code .lisp .title { color:#005599; font-weight:bold; } pre code, -.ruby .subst { +pre code .ruby .subst { color: #363C69; } -.string, -.function .title, -.class .title, -.ini .title, -.tag .attribute .value, -.css .rules .value, -.preprocessor, -.ruby .symbol, -.ruby .instancevar, -.ruby .class .parent, -.built_in, -.sql .aggregate, -.django .template_tag, -.django .variable, -.smalltalk .class, -.javadoc, -.ruby .string, -.django .filter .argument, -.smalltalk .localvars, -.smalltalk .array, -.attr_selector, -.pseudo, -.addition, -.stream, -.envvar, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .tag .attribute .value, +pre code .css .rules .value, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .ruby .instancevar, +pre code .ruby .class .parent, +pre code .built_in, +pre code .sql .aggregate, +pre code .django .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .javadoc, +pre code .ruby .string, +pre code .django .filter .argument, +pre code .smalltalk .localvars, +pre code .smalltalk .array, +pre code .attr_selector, +pre code .pseudo, +pre code .addition, +pre code .stream, +pre code .envvar, +pre code .apache .tag, +pre code .apache .cbracket { color: #2C009F; } -.comment, -.java .annotation, -.python .decorator, -.template_comment, -.pi, -.doctype, -.deletion, -.shebang, -.apache .sqbracket { +pre code .comment, +pre code .java .annotation, +pre code .python .decorator, +pre code .template_comment, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .shebang, +pre code .apache .sqbracket { color: #802022; } -.keyword, -.literal, -.css .id, -.phpdoc, -.function .title, -.class .title, -.vbscript .built_in, -.sql .aggregate, -.rsl .built_in, -.smalltalk .class, -.xml .tag .title, -.diff .header, -.chunk, -.winutils, -.bash .variable, -.lisp .title, -.apache .tag { +pre code .keyword, +pre code .literal, +pre code .css .id, +pre code .phpdoc, +pre code .function .title, +pre code .class .title, +pre code .vbscript .built_in, +pre code .sql .aggregate, +pre code .rsl .built_in, +pre code .smalltalk .class, +pre code .xml .tag .title, +pre code .diff .header, +pre code .chunk, +pre code .winutils, +pre code .bash .variable, +pre code .lisp .title, +pre code .apache .tag { font-weight: bold; } -.html .css, -.html .javascript, -.html .vbscript { +pre code .html .css, +pre code .html .javascript, +pre code .html .vbscript { opacity: 0.8; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/dark.css b/lib/webri/components/highlight/static/assets/highlight/styles/dark.css index dd1c6c5..8e112c3 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/dark.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/dark.css @@ -1,101 +1,102 @@ /* Dark style from softwaremaniacs.org (c) Ivan Sagalaev <[email protected]> */ pre code[class]:after { content: 'highlight: ' attr(class); display: block; text-align: right; font-size: smaller; color: #CCC; background: white; border-top: solid 1px black; padding-top: 0.5em; } pre code { display: block; background: #444; } -.keyword, -.literal, -.change, -.winutils, -.flow, -.lisp .title { +pre code .keyword, +pre code .literal, +pre code .change, +pre code .winutils, +pre code .flow, +pre code .lisp .title { color: white; } pre code, -.ruby .subst { +pre code .ruby .subst { color: #DDD; } -.string, -.function .title, -.class .title, -.ini .title, -.tag .attribute .value, -.css .rules .value, -.preprocessor, -.ruby .symbol, -.ruby .instancevar, -.ruby .class .parent, -.built_in, -.sql .aggregate, -.django .template_tag, -.django .variable, -.smalltalk .class, -.javadoc, -.ruby .string, -.django .filter .argument, -.smalltalk .localvars, -.smalltalk .array, -.attr_selector, -.pseudo, -.addition, -.stream, -.envvar, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .tag .attribute .value, +pre code .css .rules .value, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .ruby .instancevar, +pre code .ruby .class .parent, +pre code .built_in, +pre code .sql .aggregate, +pre code .django .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .javadoc, +pre code .ruby .string, +pre code .django .filter .argument, +pre code .smalltalk .localvars, +pre code .smalltalk .array, +pre code .attr_selector, +pre code .pseudo, +pre code .addition, +pre code .stream, +pre code .envvar, +pre code .apache .tag, +pre code .apache .cbracket { color: #D88; } -.comment, -.java .annotation, -.python .decorator, -.template_comment, -.pi, -.doctype, -.deletion, -.shebang, -.apache .sqbracket { +pre code .comment, +pre code .java .annotation, +pre code .python .decorator, +pre code .template_comment, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .shebang, +pre code .apache .sqbracket { color: #777; } -.keyword, -.literal, -.css .id, -.phpdoc, -.function .title, -.class .title, -.vbscript .built_in, -.sql .aggregate, -.rsl .built_in, -.smalltalk .class, -.xml .tag .title, -.diff .header, -.chunk, -.winutils, -.bash .variable, -.lisp .title, -.apache .tag { +pre code .keyword, +pre code .literal, +pre code .css .id, +pre code .phpdoc, +pre code .function .title, +pre code .class .title, +pre code .vbscript .built_in, +pre code .sql .aggregate, +pre code .rsl .built_in, +pre code .smalltalk .class, +pre code .xml .tag .title, +pre code .diff .header, +pre code .chunk, +pre code .winutils, +pre code .bash .variable, +pre code .lisp .title, +pre code .apache .tag { font-weight: bold; } -.html .css, -.html .javascript, -.html .vbscript { +pre code .html .css, +pre code .html .javascript, +pre code .html .vbscript { opacity: 0.5; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/default.css b/lib/webri/components/highlight/static/assets/highlight/styles/default.css index da52100..728416a 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/default.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/default.css @@ -1,103 +1,104 @@ /* Original style from softwaremaniacs.org (c) Ivan Sagalaev <[email protected]> */ pre code[class]:after { content: 'highlight: ' attr(class); display: block; text-align: right; font-size: smaller; color: #CCC; background: white; border-top: solid 1px; padding-top: 0.5em; } pre code { display: block; background: #F0F0F0; } pre code, -.ruby .subst, -.xml .title, -.lisp .title { +pre code .ruby .subst, +pre code .xml .title, +pre code .lisp .title { color: black; } -.string, -.title, -.parent, -.tag .attribute .value, -.rules .value, -.rules .value .number, -.preprocessor, -.ruby .symbol, -.instancevar, -.aggregate, -.template_tag, -.django .variable, -.smalltalk .class, -.addition, -.flow, -.stream, -.bash .variable, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .title, +pre code .parent, +pre code .tag .attribute .value, +pre code .rules .value, +pre code .rules .value .number, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .instancevar, +pre code .aggregate, +pre code .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .addition, +pre code .flow, +pre code .stream, +pre code .bash .variable, +pre code .apache .tag, +pre code .apache .cbracket { color: #800; } -.comment, -.annotation, -.template_comment, -.diff .header, -.chunk { +pre code .comment, +pre code .annotation, +pre code .template_comment, +pre code .diff .header, +pre code .chunk { color: #888; } -.number, -.date, -.regexp, -.literal, -.smalltalk .symbol, -.smalltalk .char, -.change { +pre code .number, +pre code .date, +pre code .regexp, +pre code .literal, +pre code .smalltalk .symbol, +pre code .smalltalk .char, +pre code .change { color: #080; } -.label, -.javadoc, -.ruby .string, -.decorator, -.filter .argument, -.localvars, -.array, -.attr_selector, -.pseudo, -.pi, -.doctype, -.deletion, -.envvar, -.shebang, -.apache .sqbracket { +pre code .label, +pre code .javadoc, +pre code .ruby .string, +pre code .decorator, +pre code .filter .argument, +pre code .localvars, +pre code .array, +pre code .attr_selector, +pre code .pseudo, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .envvar, +pre code .shebang, +pre code .apache .sqbracket { color: #88F; } -.keyword, -.id, -.phpdoc, -.title, -.built_in, -.aggregate, -.smalltalk .class, -.winutils, -.bash .variable, -.apache .tag { +pre code .keyword, +pre code .id, +pre code .phpdoc, +pre code .title, +pre code .built_in, +pre code .aggregate, +pre code .smalltalk .class, +pre code .winutils, +pre code .bash .variable, +pre code .apache .tag { font-weight: bold; } -.html .css, -.html .javascript, -.html .vbscript { +pre code .html .css, +pre code .html .javascript, +pre code .html .vbscript { opacity: 0.5; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/far.css b/lib/webri/components/highlight/static/assets/highlight/styles/far.css index d1e0035..f4eeded 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/far.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/far.css @@ -1,113 +1,114 @@ /* FAR Style (c) MajestiC <[email protected]> */ pre code[class]:after { content: 'highlight: ' attr(class); display: block; text-align: right; font-size: smaller; color: #CCC; background: white; border-top: solid 1px; padding-top: 0.5em; } pre code { display: block; background: #000080; } pre code, -.ruby .subst { +pre code .ruby .subst { color: #0FF; } -.string, -.ruby .string, -.function .title, -.class .title, -.ini .title, -.tag .attribute .value, -.css .rules .value, -.css .rules .value .number, -.preprocessor, -.ruby .symbol, -.built_in, -.sql .aggregate, -.django .template_tag, -.django .variable, -.smalltalk .class, -.addition, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .ruby .string, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .tag .attribute .value, +pre code .css .rules .value, +pre code .css .rules .value .number, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .built_in, +pre code .sql .aggregate, +pre code .django .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .addition, +pre code .apache .tag, +pre code .apache .cbracket { color: #FF0; } -.keyword, -.css .id, -.function .title, -.class .title, -.ini .title, -.vbscript .built_in, -.sql .aggregate, -.rsl .built_in, -.smalltalk .class, -.xml .tag .title, -.winutils, -.flow, -.lisp .title, -.change, -.envvar, -.bash .variable { +pre code .keyword, +pre code .css .id, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .vbscript .built_in, +pre code .sql .aggregate, +pre code .rsl .built_in, +pre code .smalltalk .class, +pre code .xml .tag .title, +pre code .winutils, +pre code .flow, +pre code .lisp .title, +pre code .change, +pre code .envvar, +pre code .bash .variable { color: #FFF; } -.comment, -.phpdoc, -.javadoc, -.java .annotation, -.template_comment, -.deletion, -.apache .sqbracket { +pre code .comment, +pre code .phpdoc, +pre code .javadoc, +pre code .java .annotation, +pre code .template_comment, +pre code .deletion, +pre code .apache .sqbracket { color: #888; } -.number, -.date, -.regexp, -.literal, -.smalltalk .symbol, -.smalltalk .char { +pre code .number, +pre code .date, +pre code .regexp, +pre code .literal, +pre code .smalltalk .symbol, +pre code .smalltalk .char { color: #0F0; } -.python .decorator, -.django .filter .argument, -.smalltalk .localvars, -.smalltalk .array, -.attr_selector, -.pseudo, -.xml .pi, -.diff .header, -.chunk, -.shebang { +pre code .python .decorator, +pre code .django .filter .argument, +pre code .smalltalk .localvars, +pre code .smalltalk .array, +pre code .attr_selector, +pre code .pseudo, +pre code .xml .pi, +pre code .diff .header, +pre code .chunk, +pre code .shebang { color: #008080; } -.keyword, -.css .id, -.function .title, -.class .title, -.ini .title, -.vbscript .built_in, -.sql .aggregate, -.rsl .built_in, -.smalltalk .class, -.xml .tag .title, -.winutils, -.flow, -.lisp .title, -.apache .tag { +pre code .keyword, +pre code .css .id, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .vbscript .built_in, +pre code .sql .aggregate, +pre code .rsl .built_in, +pre code .smalltalk .class, +pre code .xml .tag .title, +pre code .winutils, +pre code .flow, +pre code .lisp .title, +pre code .apache .tag { font-weight: bold; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/github.css b/lib/webri/components/highlight/static/assets/highlight/styles/github.css index d2bf7b4..cacf759 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/github.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/github.css @@ -1,90 +1,116 @@ /* github.com style (c) Vasily Polovnyov <[email protected]> */ pre code { display: block; color: #000; background: #f8f8ff } -.comment, .template_comment, .diff .header, .javadoc { +pre code .comment, +pre code .template_comment, +pre code .diff .header, +pre code .javadoc { color: #998; font-style: italic } -.keyword, .css .rule .keyword, .winutils, .javascript .title, .lisp .title, .subst { +pre code .keyword, +pre code .css .rule .keyword, +pre code .winutils, +pre code .javascript .title, +pre code .lisp .title, +pre code .subst { color: #000; font-weight: bold } -.number, .hexcolor { +pre code .number, +pre code .hexcolor { color: #40a070 } -.string, .attribute .value, .phpdoc { +pre code .string, +pre code .attribute .value, +pre code .phpdoc { color: #d14 } -.title, .id { +pre code .title, +pre code .id { color: #900; font-weight: bold } -.javascript .title, .lisp .title, .subst { +pre code .javascript .title, +pre code .lisp .title, +pre code .subst { font-weight: normal } -.class .title { +pre code .class .title { color: #458; font-weight: bold } -.tag, .css .keyword, .html .keyword, .tag .title, .django .tag .keyword { +pre code .tag, +pre code .css .keyword, +pre code .html .keyword, +pre code .tag .title, +pre code .django .tag .keyword { color: #000080; font-weight: normal } -.attribute, .variable, .instancevar, .lisp .body { +pre code .attribute, +pre code .variable, +pre code .instancevar, +pre code .lisp .body { color: #008080 } -.regexp { +pre code .regexp { color: #009926 } -.class { +pre code .class { color: #458; font-weight: bold } -.symbol, .lisp .keyword { +pre code .symbol, +pre code .lisp .keyword { color: #990073 } -.builtin, .built_in, .lisp .title { +pre code .builtin, +pre code .built_in, .lisp .title { color: #0086b3 } -.preprocessor, .pi, .doctype, .shebang, .cdata { +pre code .preprocessor, +pre code .pi, .doctype, +pre code .shebang, .cdata { color: #999; font-weight: bold } -.deletion { +pre code .deletion { background: #fdd } -.addition { +pre code .addition { background: #dfd } -.diff .change { +pre code .diff .change { background: #0086b3 } -.chunk { +pre code .chunk { color: #aaa -} \ No newline at end of file +} + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/idea.css b/lib/webri/components/highlight/static/assets/highlight/styles/idea.css index cb514e9..d81bcf8 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/idea.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/idea.css @@ -1,74 +1,110 @@ /* Intellij Idea-like styling (c) Vasily Polovnyov <[email protected]> */ pre code { display: block; color: #000; background: #fff; } -.subst, .title { +pre code .subst, +pre code .title { font-weight: normal; color: #000; } -.comment, .template_comment, .javadoc, .diff .header { +pre code .comment, +pre code .template_comment, +pre code .javadoc, +pre code .diff .header { color: #808080; font-style: italic; } -.annotation, .decorator, .preprocessor, .doctype, .pi, .chunk, .shebang, .apache .cbracket { +pre code .annotation, +pre code .decorator, +pre code .preprocessor, +pre code .doctype, +pre code .pi, +pre code .chunk, +pre code .shebang, +pre code .apache .cbracket { color: #808000; } -.tag, .pi { +pre code .tag, +pre code .pi { background: #efefef; } -.tag .title, .id, .attr_selector, .pseudo, .literal, .keyword, .hexcolor, .css .function, .ini .title, .css .class, .list .title { +pre code .tag .title, +pre code .id, +pre code .attr_selector, +pre code .pseudo, +pre code .literal, +pre code .keyword, +pre code .hexcolor, +pre code .css .function, +pre code .ini .title, +pre code .css .class, +pre code .list .title { font-weight: bold; color: #000080; } -.attribute, .rules .keyword, .number, .date, .regexp { +pre code .attribute, +pre code .rules .keyword, +pre code .number, +pre code .date, +pre code .regexp { font-weight: bold; color: #0000ff; } -.number, .regexp { +pre code .number, +pre code .regexp { font-weight: normal; } -.string, .value, .filter .argument, .css .function .params, .apache .tag { +pre code .string, +pre code .value, +pre code .filter .argument, +pre code .css .function .params, +pre code .apache .tag { color: #008000; font-weight: bold; } -.symbol, .char { +pre code .symbol, +pre code .char { color: #000; background: #d0eded; font-style: italic; } -.phpdoc, .javadoctag { +pre code .phpdoc, +pre code .javadoctag { text-decoration: underline; } -.variable, .envvar, .apache .sqbracket { +pre code .variable, +pre code .envvar, +pre code .apache .sqbracket { color: #660e7a; } -.addition { +pre code .addition { background: #baeeba; } -.deletion { +pre code .deletion { background: #ffc8bd; } -.diff .change { +pre code .diff .change { background: #bccff9; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/ir_black.css b/lib/webri/components/highlight/static/assets/highlight/styles/ir_black.css index 0e5854e..25e1563 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/ir_black.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/ir_black.css @@ -1,67 +1,92 @@ /* IR_Black style (c) Vasily Mikhailitchenko <[email protected]> */ -pre code { - color: #f8f8f8; -} - pre { background: #000; } -.shebang, .comment, .template_comment, .javadoc { +pre code { + color: #f8f8f8; +} + +pre code .shebang, +pre code .comment, +pre code .template_comment, +pre code .javadoc { color: #7c7c7c; } -.keyword, .tag, .ruby .function .keyword { +pre code .keyword, +pre code .tag, +pre code .ruby .function .keyword { color: #96CBFE; } -.function .keyword, .sub .keyword, .method, .list .title { +pre code .function .keyword, +pre code .sub .keyword, +pre code .method, +pre code .list .title { color: #FFFFB6; } -.string, .attribute .value, .cdata, .filter .argument, .attr_selector, .apache .cbracket, .date { +pre code .string, +pre code .attribute .value, +pre code .cdata, +pre code .filter .argument, +pre code .attr_selector, +pre code .apache .cbracket, +pre code .date { color: #A8FF60; } -.subst { +pre code .subst { color: #DAEFA3; } -.regexp { +pre code .regexp { color: #E9C062; } -.function .title, .sub .identifier, .pi, .decorator, .ini .title { +pre code .function .title, +pre code .sub .identifier, +pre code .pi, +pre code .decorator, +pre code .ini .title { color: #FFFFB6; } -.class .title, .smalltalk .class, .javadoctag, .phpdoc { +pre code .class .title, +pre code .smalltalk .class, +pre code .javadoctag, +pre code .phpdoc { color: #FFFFB6; } -.symbol, .number, .variable, .vbscript, .literal { +pre code .symbol, +pre code .number, +pre code .variable, +pre code .vbscript, .literal { color: #C6C5FE; } -.css .keyword { +pre code .css .keyword { color: #96CBFE; } -.css .rule .keyword, .css .id { +pre code .css .rule .keyword, +pre code .css .id { color: #FFFFB6; } -.css .class { +pre code .css .class { color: #FFF; } -.hexcolor { +pre code .hexcolor { color: #C6C5FE; } -.number { +pre code .number { color:#FF73FD; } diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/magula.css b/lib/webri/components/highlight/static/assets/highlight/styles/magula.css index a774f2a..9e73710 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/magula.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/magula.css @@ -1,105 +1,105 @@ /* Description: Magula style for highligh.js Author: Ruslan Keba <[email protected]> Website: http://rukeba.com/ Version: 1.0 Date: 2009-01-03 Music: Aphex Twin / Xtal */ pre { margin: .5em; padding: .5em; background-color: #f4f4f4; } pre code, -.ruby .subst, -.lisp .title { +pre code .ruby .subst, +pre code .lisp .title { color: black; } -.string, -.title, -.parent, -.tag .attribute .value, -.rules .value, -.rules .value .number, -.preprocessor, -.ruby .symbol, -.instancevar, -.aggregate, -.template_tag, -.django .variable, -.smalltalk .class, -.addition, -.flow, -.stream, -.bash .variable, -.apache .cbracket { +pre code .string, +pre code .title, +pre code .parent, +pre code .tag .attribute .value, +pre code .rules .value, +pre code .rules .value .number, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .instancevar, +pre code .aggregate, +pre code .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .addition, +pre code .flow, +pre code .stream, +pre code .bash .variable, +pre code .apache .cbracket { color: #050; } -.comment, -.annotation, -.template_comment, -.diff .header, -.chunk { +pre code .comment, +pre code .annotation, +pre code .template_comment, +pre code .diff .header, +pre code .chunk { color: #777; } -.number, -.date, -.regexp, -.literal, -.smalltalk .symbol, -.smalltalk .char, -.change { +pre code .number, +pre code .date, +pre code .regexp, +pre code .literal, +pre code .smalltalk .symbol, +pre code .smalltalk .char, +pre code .change { color: #800; } -.label, -.javadoc, -.ruby .string, -.decorator, -.filter .argument, -.localvars, -.array, -.attr_selector, -.pseudo, -.pi, -.doctype, -.deletion, -.envvar, -.shebang, -.apache .sqbracket { +pre code .label, +pre code .javadoc, +pre code .ruby .string, +pre code .decorator, +pre code .filter .argument, +pre code .localvars, +pre code .array, +pre code .attr_selector, +pre code .pseudo, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .envvar, +pre code .shebang, +pre code .apache .sqbracket { color: #00e; } -.keyword, -.id, -.phpdoc, -.title, -.built_in, -.aggregate, -.smalltalk .class, -.winutils, -.bash .variable, -.apache .tag, -.xml .tag, -.xml .title { +pre code .keyword, +pre code .id, +pre code .phpdoc, +pre code .title, +pre code .built_in, +pre code .aggregate, +pre code .smalltalk .class, +pre code .winutils, +pre code .bash .variable, +pre code .apache .tag, +pre code .xml .tag, +pre code .xml .title { font-weight: bold; color: navy; } -.html .css, -.html .javascript, -.html .vbscript { +pre code .html .css, +pre code .html .javascript, +pre code .html .vbscript { opacity: 0.5; } /* --- */ -.apache .tag { +pre code .apache .tag { font-weight: bold; color: blue; } diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/rubylang.css b/lib/webri/components/highlight/static/assets/highlight/styles/rubylang.css new file mode 100644 index 0000000..56db5f6 --- /dev/null +++ b/lib/webri/components/highlight/static/assets/highlight/styles/rubylang.css @@ -0,0 +1,119 @@ +/* + +rubylang.org style (c) Thomas Sawyer + +*/ + +pre code { + display: block; + color: #ffffff; + background: #213449; +} + +pre code .comment, +pre code .template_comment, +pre code .diff .header, +pre code .javadoc { + color: #428bdd; + font-style: italic +} + +pre code .keyword, +pre code .css .rule .keyword, +pre code .winutils, +pre code .javascript .title, +pre code .lisp .title, +pre code .subst { + color: #f9bb00; + font-weight: bold +} + +pre code .number, +pre code .hexcolor { + color: #eddd3d; +} + +pre code .string, +pre code .attribute .value, +pre code .phpdoc { + color: #00cc00; +} + +pre code .title, +pre code .id { + color: #900; + font-weight: bold +} + +pre code .javascript .title, +pre code .lisp .title, +pre code .subst { + font-weight: normal +} + +pre code .class .title { + color: #fff; + font-weight: bold +} + +pre code .tag, +pre code .css .keyword, +pre code .html .keyword, +pre code .tag .title, +pre code .django .tag .keyword { + color: #f9bb00; + font-weight: normal +} + +pre code .attribute, +pre code .variable, +pre code .instancevar, +pre code .lisp .body { + color: #8aa6c1; +} + +pre code .regexp { + color: #ca4344; +} + +pre code .class { + color: #fff; + font-weight: bold +} + +pre code .symbol, +pre code .lisp .keyword { + color: #b53b3c; +} + +pre code .builtin, +pre code .built_in, +pre code .lisp .title { + color: #fff; +} + +pre code .preprocessor, +pre code .pi, +pre code .doctype, +pre code .shebang, +pre code .cdata { + color: #999; + font-weight: bold +} + +pre code .deletion { + background: #fdd +} + +pre code .addition { + background: #dfd +} + +pre code .diff .change { + background: #0086b3 +} + +pre code .chunk { + color: #aaa +} + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/school_book.css b/lib/webri/components/highlight/static/assets/highlight/styles/school_book.css index 1ecbce1..6fdf394 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/school_book.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/school_book.css @@ -1,106 +1,112 @@ /* School Book style from goldblog.com.ua (c) Zaripov Yura <[email protected]> */ +pre { + background:#f6f6ae url(./school_book.png); + border-top: solid 2px #d2e8b9; + border-bottom: solid 1px #d2e8b9; +} + pre code[class]:after { content: 'highlight: ' attr(class); - display: block; text-align: right; - color: #CCC; background: transparent; - + display: block; + text-align: right; + color: #CCC; + background: transparent; padding-top: 0.5em; } pre code { display: block; margin-left:30px; margin-top:15px; - font-size: 11px !important; + font-size: 11px !important; line-height:16px !important; - } -pre{background:#f6f6ae url(./school_book.png); - border-top: solid 2px #d2e8b9; - border-bottom: solid 1px #d2e8b9;} -.keyword, -.literal, -.change, -.winutils, -.flow, -.lisp .title { +} + +pre code .keyword, +pre code .literal, +pre code .change, +pre code .winutils, +pre code .flow, +pre code .lisp .title { color:#005599; font-weight:bold; } pre code, -.ruby .subst { +pre code .ruby .subst { color: #3E5915; } -.string, -.function .title, -.class .title, -.ini .title, -.tag .attribute .value, -.css .rules .value, -.preprocessor, -.ruby .symbol, -.ruby .instancevar, -.ruby .class .parent, -.built_in, -.sql .aggregate, -.django .template_tag, -.django .variable, -.smalltalk .class, -.javadoc, -.ruby .string, -.django .filter .argument, -.smalltalk .localvars, -.smalltalk .array, -.attr_selector, -.pseudo, -.addition, -.stream, -.envvar, -.apache .tag, -.apache .cbracket { +pre code .string, +pre code .function .title, +pre code .class .title, +pre code .ini .title, +pre code .tag .attribute .value, +pre code .css .rules .value, +pre code .preprocessor, +pre code .ruby .symbol, +pre code .ruby .instancevar, +pre code .ruby .class .parent, +pre code .built_in, +pre code .sql .aggregate, +pre code .django .template_tag, +pre code .django .variable, +pre code .smalltalk .class, +pre code .javadoc, +pre code .ruby .string, +pre code .django .filter .argument, +pre code .smalltalk .localvars, +pre code .smalltalk .array, +pre code .attr_selector, +pre code .pseudo, +pre code .addition, +pre code .stream, +pre code .envvar, +pre code .apache .tag, +pre code .apache .cbracket { color: #2C009F; } -.comment, -.java .annotation, -.python .decorator, -.template_comment, -.pi, -.doctype, -.deletion, -.shebang, -.apache .sqbracket { +pre code .comment, +pre code .java .annotation, +pre code .python .decorator, +pre code .template_comment, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .shebang, +pre code .apache .sqbracket { color: #E60415; } -.keyword, -.literal, -.css .id, -.phpdoc, -.function .title, -.class .title, -.vbscript .built_in, -.sql .aggregate, -.rsl .built_in, -.smalltalk .class, -.xml .tag .title, -.diff .header, -.chunk, -.winutils, -.bash .variable, -.lisp .title, -.apache .tag { +pre code .keyword, +pre code .literal, +pre code .css .id, +pre code .phpdoc, +pre code .function .title, +pre code .class .title, +pre code .vbscript .built_in, +pre code .sql .aggregate, +pre code .rsl .built_in, +pre code .smalltalk .class, +pre code .xml .tag .title, +pre code .diff .header, +pre code .chunk, +pre code .winutils, +pre code .bash .variable, +pre code .lisp .title, +pre code .apache .tag { font-weight: bold; } -.html .css, -.html .javascript, -.html .vbscript { +pre code .html .css, +pre code .html .javascript, +pre code .html .vbscript { opacity: 0.8; } + diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/sunburst.css b/lib/webri/components/highlight/static/assets/highlight/styles/sunburst.css index 5514593..82f7da9 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/sunburst.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/sunburst.css @@ -1,112 +1,140 @@ /* Sunburst-like style (c) Vasily Polovnyov <[email protected]> */ +pre { + background: #000; +} + pre code { font: 1em / 1.3em 'Lucida Console', 'courier new', monospace; color: #f8f8f8; } -pre { - background: #000; -} - -.comment, .template_comment, .javadoc { +pre code .comment, +pre code .template_comment, +pre code .javadoc { color: #aeaeae; font-style: italic; } -.keyword, .ruby .function .keyword { +pre code .keyword, +pre code .ruby .function .keyword { color: #E28964; } -.function .keyword, .sub .keyword, .method, .list .title { +pre code .function .keyword, +pre code .sub .keyword, +pre code .method, +pre code .list .title { color: #99CF50; } -.string, .attribute .value, .cdata, .filter .argument, .attr_selector, .apache .cbracket, .date { +pre code .string, +pre code .attribute .value, +pre code .cdata, +pre code .filter .argument, +pre code .attr_selector, +pre code .apache .cbracket, +pre code .date { color: #65B042; } .subst { color: #DAEFA3; } .regexp { color: #E9C062; } -.function .title, .sub .identifier, .pi, .tag, .tag .keyword, .decorator, .ini .title, .shebang { +pre code .function .title, +pre code .sub .identifier, +pre code .pi, +pre code .tag, +pre code .tag .keyword, +pre code .decorator, +pre code .ini .title, +pre code .shebang { color: #89BDFF; } -.class .title, .smalltalk .class, .javadoctag, .phpdoc { +pre code .class .title, +pre code .smalltalk .class, +pre code .javadoctag, +pre code .phpdoc { text-decoration: underline; } -.symbol, .number { +pre code .symbol, +pre code .number { color: #3387CC; } -.params, .variable { +pre code .params, +pre code .variable { color: #3E87E3; } -.css .keyword, .pseudo { +pre code .css .keyword, +pre code .pseudo { color: #CDA869; } -.css .class { +pre code .css .class { color: #9B703F; } -.rules .keyword { +pre code .rules .keyword { color: #C5AF75; } -.rules .value { +pre code .rules .value { color: #CF6A4C; } -.css .id { +pre code .css .id { color: #8B98AB; } -.annotation, .apache .sqbracket { +pre code .annotation, +pre code .apache .sqbracket { color: #9B859D; } -.preprocessor { +pre code .preprocessor { color: #8996A8; } -.hexcolor, .css .value .number { +pre code .hexcolor, +pre code .css .value .number { color: #DD7B3B; } -.css .function { +pre code .css .function { color: #DAD085; } -.diff .header, .chunk { +pre code .diff .header, +pre code .chunk { background-color: #0E2231; color: #F8F8F8; font-style: italic; } -.diff .change { +pre code .diff .change { background-color: #4A410D; color: #F8F8F8; } -.addition { +pre code .addition { background-color: #253B22; color: #F8F8F8; } -.deletion { +pre code .deletion { background-color: #420E09; color: #F8F8F8; } diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/vs.css b/lib/webri/components/highlight/static/assets/highlight/styles/vs.css index a5f5d26..716d598 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/vs.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/vs.css @@ -1,68 +1,69 @@ /* Visual Studio-like style based on original C# coloring by Jason Diamond <[email protected]> */ -.comment, -.annotation, -.template_comment, -.diff .header, -.chunk, -.apache .cbracket { + +pre code .comment, +pre code .annotation, +pre code .template_comment, +pre code .diff .header, +pre code .chunk, +pre code .apache .cbracket { color: rgb(0, 128, 0); } -.keyword, -.id, -.title, -.built_in, -.aggregate, -.smalltalk .class, -.winutils, -.bash .variable { +pre code .keyword, +pre code .id, +pre code .title, +pre code .built_in, +pre code .aggregate, +pre code .smalltalk .class, +pre code .winutils, +pre code .bash .variable { color: rgb(0, 0, 255); } -.string, -.title, -.parent, -.tag .attribute .value, -.rules .value, -.rules .value .number, -.ruby .symbol, -.instancevar, -.aggregate, -.template_tag, -.django .variable, -.addition, -.flow, -.stream, -.apache .tag, -.date { +pre code .string, +pre code .title, +pre code .parent, +pre code .tag .attribute .value, +pre code .rules .value, +pre code .rules .value .number, +pre code .ruby .symbol, +pre code .instancevar, +pre code .aggregate, +pre code .template_tag, +pre code .django .variable, +pre code .addition, +pre code .flow, +pre code .stream, +pre code .apache .tag, +pre code .date { color: rgb(163, 21, 21); } -.ruby .string, -.decorator, -.filter .argument, -.localvars, -.array, -.attr_selector, -.pseudo, -.pi, -.doctype, -.deletion, -.envvar, -.shebang, -.preprocessor, -.userType, -.apache .sqbracket { +pre code .ruby .string, +pre code .decorator, +pre code .filter .argument, +pre code .localvars, +pre code .array, +pre code .attr_selector, +pre code .pseudo, +pre code .pi, +pre code .doctype, +pre code .deletion, +pre code .envvar, +pre code .shebang, +pre code .preprocessor, +pre code .userType, +pre code .apache .sqbracket { color: rgb(43, 145, 175); } -.phpdoc, -.javadoc, -.xmlDocTag { +pre code .phpdoc, +pre code .javadoc, +pre code .xmlDocTag { color: rgb(128, 128, 128); } diff --git a/lib/webri/components/highlight/static/assets/highlight/styles/zenburn.css b/lib/webri/components/highlight/static/assets/highlight/styles/zenburn.css index fd6d016..5d423c9 100644 --- a/lib/webri/components/highlight/static/assets/highlight/styles/zenburn.css +++ b/lib/webri/components/highlight/static/assets/highlight/styles/zenburn.css @@ -1,113 +1,113 @@ /* Zenburn style from voldmar.ru (c) Vladimir Epifanov <[email protected]> based on dark.css by Ivan Sagalaev */ pre code[class]:after { content: 'highlight: ' attr(class); display: block; text-align: right; font-size: smaller; color: #CCC; background: white; border-top: solid 1px black; padding-top: 0.5em; } pre code { display: block; background: #3F3F3F; color: #DCDCDC; } -.keyword, -.tag, -.django .tag, -.django .keyword, -.css .class, -.css .id, -.lisp .title { +pre code .keyword, +pre code .tag, +pre code .django .tag, +pre code .django .keyword, +pre code .css .class, +pre code .css .id, +pre code .lisp .title { color: #E3CEAB; } -.django .template_tag, -.django .variable, -.django .filter .argument { +pre code .django .template_tag, +pre code .django .variable, +pre code .django .filter .argument { color: #DCDCDC; } -.number, -.date { +pre code .number, +pre code .date { color: #8CD0D3; } -.dos .envvar, -.dos .stream, -.variable, -.apache .sqbracket { +pre code .dos .envvar, +pre code .dos .stream, +pre code .variable, +pre code .apache .sqbracket { color: #EFDCBC; } -.dos .flow, -.diff .change, -.python .exception, -.python .built_in, -.literal { +pre code .dos .flow, +pre code .diff .change, +pre code .python .exception, +pre code .python .built_in, +pre code .literal { color: #EFEFAF; } -.diff .chunk, -.ruby .subst { +pre code .diff .chunk, +pre code .ruby .subst { color: #8F8F8F; } -.dos .keyword, -.python .decorator, -.class .title, -.function .title, -.ini .title, -.diff .header, -.ruby .class .parent, -.apache .tag { +pre code .dos .keyword, +pre code .python .decorator, +pre code .class .title, +pre code .function .title, +pre code .ini .title, +pre code .diff .header, +pre code .ruby .class .parent, +pre code .apache .tag { color: #efef8f; } -.dos .winutils, -.ruby .symbol, -.ruby .string, -.ruby .instancevar { +pre code .dos .winutils, +pre code .ruby .symbol, +pre code .ruby .string, +pre code .ruby .instancevar { color: #DCA3A3; } -.diff .deletion, -.string, -.tag .attribute .value, -.preprocessor, -.built_in, -.sql .aggregate, -.javadoc, -.smalltalk .class, -.smalltalk .localvars, -.smalltalk .array, -.css .rules .value, -.attr_selector, -.pseudo, -.apache .cbracket { +pre code .diff .deletion, +pre code .string, +pre code .tag .attribute .value, +pre code .preprocessor, +pre code .built_in, +pre code .sql .aggregate, +pre code .javadoc, +pre code .smalltalk .class, +pre code .smalltalk .localvars, +pre code .smalltalk .array, +pre code .css .rules .value, +pre code .attr_selector, +pre code .pseudo, +pre code .apache .cbracket { color: #CC9393; } -.shebang, -.diff .addition, -.comment, -.java .annotation, -.template_comment, -.pi, -.doctype { +pre code .shebang, +pre code .diff .addition, +pre code .comment, +pre code .java .annotation, +pre code .template_comment, +pre code .pi, +pre code .doctype { color: #7F9F7F; } -.html .css, -.html .javascript { +pre code .html .css, +pre code .html .javascript { opacity: 0.5; }
razerbeans/webri
83ea057b30d03db842d1231704e267d53d6a1220
remove some old commented out code
diff --git a/lib/webri/generators/newfish/generator.rb b/lib/webri/generators/newfish/generator.rb index a888b89..22867ea 100644 --- a/lib/webri/generators/newfish/generator.rb +++ b/lib/webri/generators/newfish/generator.rb @@ -1,35 +1,25 @@ require 'webri/generators/abstract' require 'webri/components/icons' require 'webri/components/subversion' module WebRI # = Redfish Template # # Redfish is based on RDoc's default Darkfish generator, # heavily modified to provide only a single sidebar con # document layout. And, as the name indicates, colorized # to be red (instead of green). # # You can thank Darkfish, a by extension Redfish, for the # "-fish" naming scheme :) # class Newfish < Generator include Icons include Subversion - # - #def path - # @path ||= Pathname.new(__FILE__).parent - #end - - # - #def generate_template - # super - #end - end end
razerbeans/webri
db56e6bf7f382c29303e1088e27e885259d72869
generate components first
diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index 06d6390..b51baeb 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,669 +1,669 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' require 'webri/extensions/times' require 'webri/extensions/fileutils' require 'webri/generators/abstract/metadata' -require 'webri/generators/abstract/erbtemplate' +require 'webri/generators/abstract/template' # module WebRI # = Abstract Generator Base Class # class Generator PATH = Pathname.new(File.join(LOADPATH, 'webri', 'generators')) #include ERB::Util include Metadata # # C O N S T A N T S # #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. PATH_STATIC = PATH + 'abstract/static' # Common template directory. PATH_TEMPLATE = PATH + 'abstract/template' # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # Get title from options or metadata. def title @title ||= ( if options.title == "RDoc Documentation" metadata.title || "RDoc Documentation" else options.title end ) end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel ||= @files_rdoc.select { |f| f.parser == RDoc::Parser::Simple } end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(files) @files_rdoc = files.sort generate_setup generate_commons + generate_components generate_static generate_template - generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end - # This method files copies the common static files of the abstract + # This method copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s show_from = PATH_STATIC.to_s.sub(PATH.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(PATH.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template - @erb_template ||= ERBTemplate.new(self, provisions) + @erb_template ||= Template.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/abstract/template.rb b/lib/webri/generators/abstract/template.rb index 6893f28..a57dce3 100644 --- a/lib/webri/generators/abstract/template.rb +++ b/lib/webri/generators/abstract/template.rb @@ -1,117 +1,119 @@ require 'erb' module WebRI - # ERBTemplate is used by the generator to build + # = ERB Template + # + # Template is used by the generator to build # template files. It has access to all the # the <i>data methods</i> in the generator. - class ERBTemplate + class Template include ERB::Util # New ERBTemplate instance. def initialize(generator, provisions) @generator = generator # add component provisions provisions.each do |name, block| (class << self; self; end).class_eval do define_method(name){ |*a,&b| block.call(*a,&b) } end end end # Render a template. def render(template_file, local_assigns={}) template_source = template_file.read erb = ERB.new(template_source, nil, '<>') erb.filename = template_file.to_s local_assigns.each do |key, val| (class << self; self; end).class_eval do define_method(key){ val } end end begin erb_binding = binding #eval code, b erb.result(erb_binding) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ template_file.to_s, err.message, eval("_erbout[-50,50]", erb_binding) ], err.backtrace end end # FIXME: this probably goes not need to double dispatch via generator def include_template(*a,&b) @generator.include_template(*a,&b) end def options ; @generator.options ; end def title ; @generator.title ; end def copyright ; @generator.copyright ; end def class_dir ; @generator.class_dir ; end def file_dir ; @generator.file_dir ; end #def all_classes_and_modules ; @generator.all_classes_and_modules ; end # classes and modules def classes ; @generator.classes ; end def classes_toplevel ; @generator.classes_toplevel ; end def classes_salient ; @generator.classes_salient ; end def classes_hash ; @generator.classes_hash ; end # just modules, no classes def modules ; @generator.modules ; end def modules_toplevel ; @generator.modulews_toplevel ; end def modules_salient ; @generator.modules_salient ; end def modules_hash ; @generator.modules_hash ; end # just classes w/o modules def types ; @generator.types ; end def types_toplevel ; @generator.types_toplevel ; end def types_salient ; @generator.types_salient ; end def types_hash ; @generator.types_hash ; end # def methods_all ; @generator.methods_all ; end # def files ; @generator.files ; end def files_toplevel ; @generator.files_toplevel ; end def files_hash ; @generator.files_hash ; end def find_class_named(*a,&b) ; @generator.find_class_named(*a,&b) ; end def find_module_named(*a,&b) ; @generator.find_module_named(*a,&b) ; end def find_type_named(*a,&b) ; @generator.find_type_named(*a,&b) ; end def find_file_named(*a,&b) ; @generator.find_file_named(*a,&b) ; end # Load and render the erb template with the given +template_name+ within # current context. Adds all +local_assigns+ to context def include_template(template_name, local_assigns={}) #source = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join #eval("#{source}; templatefile = path_template + template_name;eval_template(templatefile, binding)") template_file = @generator.__send__(:path_template) + template_name render(template_file, local_assigns) end # def method_missing(s, *a, &b) if @generator.respond_to?(s) @generator.__send__(s, *a, &b) end end end end
razerbeans/webri
b1f6487d65c336996befc36d7d86e3b4eade97e0
sometimes there is no superclass [bug]
diff --git a/lib/webri/generators/longfish/template/class_context.rhtml b/lib/webri/generators/longfish/template/class_context.rhtml index c02853c..2784357 100644 --- a/lib/webri/generators/longfish/template/class_context.rhtml +++ b/lib/webri/generators/longfish/template/class_context.rhtml @@ -1,305 +1,307 @@ <% desc = context.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) name = md[1] desc = md.post_match else name = context.name end %> <div id="content-wrapper"> <div id="head-wrapper-1"> <div id="head-wrapper-2"> <div id="head"> <h1><%= name %></h1> </div> </div> </div> <div id="content"> <!-- DESCRIPTION --> <% unless desc.empty? %> <div class="description"> <%= desc %> </div> <% end %> <!-- REQUIRES --> <% unless context.requires.empty? %> <h3>Required Files</h3> <ul> <% context.requires.each do |req| %> <li><%= h req.name %></li> <% end %> </ul> <% end %> <!-- CONTENTS --> <% sections = context.sections.select { |section| section.title } %> <% unless sections.empty? %> <h3>Contents</h3> <ul> <% sections.each do |section| %> <li><a href="#<%= section.sequence %>"><%= h section.title %></a></li> <% end %> </ul> <% end %> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> <% end %> <!-- DESCRIPTION (of what?) ---> <% sections.each do |section| %> <h3><a name="<%= h section.sequence %>"><%= h section.title %></a></h3> <% unless (description = section.description).empty? %> <div class="description"> <%= description %> </div> <% end %> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= context.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> <% end %> <!-- CONSTANTS --> <% unless context.constants.empty? %> <h3>Constants</h3> <table border='0' cellpadding='5'> <% context.each_constant do |const| %> <tr valign='top'> <td class="attr-name"><%= h const.name %></td> <td>=</td> <td class="attr-value"><%= h const.value %></td> </tr> <% unless (description = const.description).empty? %> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"><%= description %></td> </tr> <% end %> <% end %> </table> <% end %> <!-- ATTRIBUTES --> <% unless context.attributes.empty? %> <h3>Attributes</h3> <table border='0' cellpadding='5'> <% context.each_attribute do |attrib| %> <tr valign='top'> <td class='attr-rw'> [<%= attrib.rw %>] </td> <td class='attr-name'><%= h attrib.name %></td> <td class='attr-desc'><%= attrib.description.strip %></td> </tr> <% end %> </table> <% end %> <!-- METHODS --> <% context.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? next unless options.show_all || visibility == :public || visibility == :protected || methods.any? {|m| m.force_documentation } %> <h3><%= type.capitalize %> <%= visibility.to_s.capitalize %> methods</h3> <dl> <% methods.each do |method| %> <p class="source-link" style="float: right;"> <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source"><img src="<%= rel_prefix %>/assets/img/bullet_toggle_plus.png" alt="[+]"></a> <% if markup =~ /File\s(\S+), line (\d+)/ path = $1 line = $2.to_i end github = github_url(path) if github %> | <a href="<%= "#{github}#L#{line}" %>" target="_blank" class="github_url">on GitHub</a> <% end %> </p> <dt> <% if method.call_seq %> <a name="<%= method.aref %>"></a><b><%= method.call_seq.gsub(/->/, '&rarr;') %></b> <% else %> <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> <% end %> </dt> <dd> <% if (description = method.description).empty? %> Not Documented <% else %> <%# TODO delete this dirty hack when documentation for example for JavaScriptHelper will not be cutted off by <script> tag %> <%= description.gsub('<script>'){ |m| h(m) } %> <% end %> <% unless method.aliases.empty? %> <div class="aka"> This method is also aliased as <% method.aliases.each do |aka| %> <a href="<%= context.aref_to aka.path %>"><%= h aka.name %></a> <% end %> </div> <% end %> <% if method.token_stream %> <% markup = method.markup_code %> <div id="<%= method.aref %>_source" style="display: none;"> <pre class="code"><code><%= method.markup_code %></code></pre> </div> <% end %> </dd> <% end %> <% end %> <% end %> </div> </div> <hr class="hidden-modern" /> <div id="sidebar-wrapper"> <div id="sidebar"> <div class="navigation"> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" style="width: 95%;" /> </fieldset> </form> </div> <br/><br/> <!-- PARENT --> <% if context.parent %> <div class="navigation"> <h3>Parent</h3> <ul> <li><a href="<%= context.aref_to context.parent.path %>"><%= context.parent.name %></a></li> </ul> </div> <% end %> <!-- SUPERCLASS --> <% if !context.is_a?(RDoc::TopLevel) && context.type == 'class' %> - <div class="navigation"> - <h3>Superclass</h3> - <ul> - <li> - <% unless String === context.superclass %> - <a href="<%= context.aref_to context.superclass.path %>"><%= context.superclass.full_name %></a> - <% else %> - <%= context.superclass %> + <% if context.superclass %> + <div class="navigation"> + <h3>Superclass</h3> + <ul> + <li> + <% unless String === context.superclass %> + <a href="<%= context.aref_to context.superclass.path %>"><%= context.superclass.full_name %></a> + <% else %> + <%= context.superclass %> + <% end %> + </li> + </ul> + </div> <% end %> - </li> - </ul> - </div> <% end %> <!-- INCLUDED MODULES --> <% unless context.includes.empty? %> <div class="navigation"> <h3>Included Modules</h3> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> </li> <% end %> </ul> </div> <% end %> <!-- CLASSES AND MODULES --> <% unless context.classes_and_modules.empty? %> <div class="navigation"> <h3>Classes and Modules</h3> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><a href="<%= context.aref_to mod.path %>"><%= mod.full_name.sub(context.full_name+'::', '') %></a></li> <% end %> </ul> </div> <% end %> <!-- METHOD LIST --> <% list = context.method_list unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end %> <% unless list.empty? %> <div class="navigation"> <h3>Methods</h3> <ul class="menu"> <% list.sort{ |a, b| a.name <=> b.name }.each do |method| %> <li><a href="#<%= method.aref %>"><%= method.name %></a></li> <% end %> </ul> </div> <% end %> <!-- IN FILES --> <div class="navigation"> <h3>In Files</h3> <ul> <% context.in_files.each do |tl| %> <li class="file"> <a href="<%= rel_prefix %>/<%= h tl.path %>" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a> </li> <% end %> </ul> </div> </div> </div>
razerbeans/webri
402b75aa3bce23a4f1e71d5d312dbabf9fe448fe
fixed icons for redfish and newfish [minor]
diff --git a/lib/webri/components/icons/component.rb b/lib/webri/components/icons/component.rb index a55e3c2..143fc2b 100644 --- a/lib/webri/components/icons/component.rb +++ b/lib/webri/components/icons/component.rb @@ -1,13 +1,13 @@ -require 'webri/componenets/abstract' +require 'webri/components/abstract' module WebRI # Very simple generator component that provides # a set of small standard name icons for typical # Ruby needs. - module Icons < Component + class Icons < Component end end diff --git a/lib/webri/generators/newfish/static/assets/img/wrench.png b/lib/webri/components/icons/static/assets/img/fixme.png similarity index 100% rename from lib/webri/generators/newfish/static/assets/img/wrench.png rename to lib/webri/components/icons/static/assets/img/fixme.png diff --git a/lib/webri/components/icons/static/assets/img/list.png b/lib/webri/components/icons/static/assets/img/list.png new file mode 100644 index 0000000..fc61cef Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/list.png differ diff --git a/lib/webri/components/icons/static/assets/img/loading.gif b/lib/webri/components/icons/static/assets/img/loading.gif new file mode 100644 index 0000000..085ccae Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/loading.gif differ diff --git a/lib/webri/components/icons/static/assets/img/module.png b/lib/webri/components/icons/static/assets/img/module.png index da3c2a2..d78da76 100644 Binary files a/lib/webri/components/icons/static/assets/img/module.png and b/lib/webri/components/icons/static/assets/img/module.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/page_green.png b/lib/webri/components/icons/static/assets/img/page.png similarity index 100% rename from lib/webri/generators/newfish/static/assets/img/page_green.png rename to lib/webri/components/icons/static/assets/img/page.png diff --git a/lib/webri/generators/newfish/static/assets/img/page_white_width.png b/lib/webri/components/icons/static/assets/img/stat.png similarity index 100% rename from lib/webri/generators/newfish/static/assets/img/page_white_width.png rename to lib/webri/components/icons/static/assets/img/stat.png diff --git a/lib/webri/generators/newfish/generator.rb b/lib/webri/generators/newfish/generator.rb index 8e9018d..a888b89 100644 --- a/lib/webri/generators/newfish/generator.rb +++ b/lib/webri/generators/newfish/generator.rb @@ -1,33 +1,35 @@ require 'webri/generators/abstract' +require 'webri/components/icons' require 'webri/components/subversion' module WebRI # = Redfish Template # # Redfish is based on RDoc's default Darkfish generator, # heavily modified to provide only a single sidebar con # document layout. And, as the name indicates, colorized # to be red (instead of green). # # You can thank Darkfish, a by extension Redfish, for the # "-fish" naming scheme :) # class Newfish < Generator + include Icons include Subversion # #def path # @path ||= Pathname.new(__FILE__).parent #end # #def generate_template # super #end end end diff --git a/lib/webri/generators/newfish/static/assets/css/rdoc.css b/lib/webri/generators/newfish/static/assets/css/rdoc.css index ada9734..0ee889b 100644 --- a/lib/webri/generators/newfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/newfish/static/assets/css/rdoc.css @@ -1,835 +1,664 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; background: #ffffff; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; padding: 0 40px 15px 40px; } #main { width: 1024px; margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } img { border: none; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: black; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; color: #844; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } pre { padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; padding: 10px 10px; margin: 0 8px -0.5em 8px; } .head h1 { color: #666; font-weight: bold; font-size: 18px; } .head h1 a { font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; /* background: #ddd; */ border: 1px solid #ccc; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; - background: white url(images/wrench_orange.png) no-repeat 4px center; + background: white url(../img/fixme.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; - background: url(images/bullet_black.png) no-repeat left 4px; + background: url(../img/bullet.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; - background: url(images/method.png) no-repeat left 2px; + background: url(../img/method.png) no-repeat left 2px; +} + +#metadata li.singleton { + padding-left: 20px; + background: url(../img/singleton.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; - background: url(images/module.png) no-repeat left 2px; + background: url(../img/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; - background: url(images/class.png) no-repeat left 2px; + background: url(../img/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; - background: url(images/file.png) no-repeat left 2px; + background: url(../img/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: right; width: 320px; margin-top: 10px; border-left: 1px solid #ccc; padding-left: 12px; } #documentation { margin: 0 360px 5em 1em; min-width: 340px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #fff; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 0 solid #ccc; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #fff; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #ccc; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; - list-style-image: url(images/page_green.png); + list-style-image: url(../img/page.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 0px solid #ccc; } #project-metadata h3.section-header { border-bottom: 1px solid #ccc; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ffffff; padding: 8px 8px 16px; border-bottom: 0px solid #ccc; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } .method-parent-aside { float: right; font-size: 0.7em; font-weight: bold; padding: 0 20px; color: #aaa; font-family: helvetica; letter-spacing: -1px; } /* @end */ /* @group Documentation Section */ #documentation h1 { margin: 8px 0 0 0; padding: 0.5em 0.1em 0.1em 0.1em; border-bottom: 0px solid #bbb; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #documentation ul { margin-top: 10px; } #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.5em; /* background-color: #dedede; */ color: #333; font-size: 150%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; - background: url(images/method.png) no-repeat left bottom; + background: url(../img/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; - background: url(images/zoom.png) no-repeat right top; + background: url(../img/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; - background: url(images/alias.png) no-repeat left bottom; + background: url(../img/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { - background: url(images/attribute.png) no-repeat left bottom; + background: url(../img/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ /* .file #documentation { margin: 0; } */ .file #metadata { float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; - background: url(../img/page_white_width.png) no-repeat left top; + background: url(../img/stat.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } /* .file h2 { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.1em; color: #333; font-size: 120%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } */ /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ - - - - - - - - - - - - - -/* @group ThickBox Styles */ -#TB_window { - font: 12px Arial, Helvetica, sans-serif; - color: #333333; -} - -#TB_secondLine { - font: 10px Arial, Helvetica, sans-serif; - color:#666666; -} - -#TB_window a:link {color: #666666;} -#TB_window a:visited {color: #666666;} -#TB_window a:hover {color: #000;} -#TB_window a:active {color: #666666;} -#TB_window a:focus{color: #666666;} - -#TB_overlay { - position: fixed; - z-index:100; - top: 0px; - left: 0px; - height:100%; - width:100%; -} - -.TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} -.TB_overlayBG { - background-color:#000; - filter:alpha(opacity=75); - -moz-opacity: 0.75; - opacity: 0.75; -} - -* html #TB_overlay { /* ie6 hack */ - position: absolute; - height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); -} - -#TB_window { - position: fixed; - background: #ffffff; - z-index: 102; - color:#000000; - display:none; - border: 4px solid #525252; - text-align:left; - top:50%; - left:50%; -} - -* html #TB_window { /* ie6 hack */ -position: absolute; -margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); -} - -#TB_window img#TB_Image { - display:block; - margin: 15px 0 0 15px; - border-right: 1px solid #ccc; - border-bottom: 1px solid #ccc; - border-top: 1px solid #666; - border-left: 1px solid #666; -} - -#TB_caption{ - height:25px; - padding:7px 30px 10px 25px; - float:left; -} - -#TB_closeWindow{ - height:25px; - padding:11px 25px 10px 0; - float:right; -} - -#TB_closeAjaxWindow{ - padding:7px 10px 5px 0; - margin-bottom:1px; - text-align:right; - float:right; -} - -#TB_ajaxWindowTitle{ - float:left; - padding:7px 0 5px 10px; - margin-bottom:1px; - font-size: 22px; -} - -#TB_title{ - background-color: #FF226C; - color: #dedede; - height:40px; -} -#TB_title a { - color: white !important; - border-bottom: 1px dotted #dedede; -} - -#TB_ajaxContent{ - clear:both; - padding:2px 15px 15px 15px; - overflow:auto; - text-align:left; - line-height:1.4em; -} - -#TB_ajaxContent.TB_modal{ - padding:15px; -} - -#TB_ajaxContent p{ - padding:5px 0px 5px 0px; -} - -#TB_load{ - position: fixed; - display:none; - height:13px; - width:208px; - z-index:103; - top: 50%; - left: 50%; - margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ -} - -* html #TB_load { /* ie6 hack */ -position: absolute; -margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); -} - -#TB_HideSelect{ - z-index:99; - position:fixed; - top: 0; - left: 0; - background-color:#fff; - border:none; - filter:alpha(opacity=0); - -moz-opacity: 0; - opacity: 0; - height:100%; - width:100%; -} - -* html #TB_HideSelect { /* ie6 hack */ - position: absolute; - height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); -} - -#TB_iframeContent{ - clear:both; - border:none; - margin-bottom:-1px; - margin-top:1px; - _margin-bottom:1px; -} - -/* @end */ - - diff --git a/lib/webri/generators/newfish/static/assets/img/alias.png b/lib/webri/generators/newfish/static/assets/img/alias.png index 9ebf013..0a59bea 100644 Binary files a/lib/webri/generators/newfish/static/assets/img/alias.png and b/lib/webri/generators/newfish/static/assets/img/alias.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/bug.png b/lib/webri/generators/newfish/static/assets/img/bug.png deleted file mode 100644 index 2d5fb90..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/bug.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_black.png b/lib/webri/generators/newfish/static/assets/img/bullet_black.png deleted file mode 100644 index 5761970..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/bullet_black.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png deleted file mode 100644 index b47ce55..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png deleted file mode 100644 index 9ab4a89..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/class.png b/lib/webri/generators/newfish/static/assets/img/class.png deleted file mode 100644 index f763a16..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/class.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/date.png b/lib/webri/generators/newfish/static/assets/img/date.png deleted file mode 100644 index 783c833..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/date.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/file.png b/lib/webri/generators/newfish/static/assets/img/file.png deleted file mode 100644 index 813f712..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/file.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/find.png b/lib/webri/generators/newfish/static/assets/img/find.png deleted file mode 100644 index 1547479..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/find.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif b/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif deleted file mode 100644 index 82290f4..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png b/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png deleted file mode 100644 index c6473b3..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/method.png b/lib/webri/generators/newfish/static/assets/img/method.png index 7851cf3..500bdb4 100644 Binary files a/lib/webri/generators/newfish/static/assets/img/method.png and b/lib/webri/generators/newfish/static/assets/img/method.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/module.png b/lib/webri/generators/newfish/static/assets/img/module.png deleted file mode 100644 index da3c2a2..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/module.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/plugin.png b/lib/webri/generators/newfish/static/assets/img/plugin.png deleted file mode 100644 index 6187b15..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/plugin.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/project.png b/lib/webri/generators/newfish/static/assets/img/project.png deleted file mode 100644 index 9183c02..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/project.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/singleton.png b/lib/webri/generators/newfish/static/assets/img/singleton.png new file mode 100644 index 0000000..a122fbd Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/singleton.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/wrench_orange.png b/lib/webri/generators/newfish/static/assets/img/wrench_orange.png deleted file mode 100644 index 565a933..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/wrench_orange.png and /dev/null differ diff --git a/lib/webri/generators/newfish/static/assets/img/zoom.png b/lib/webri/generators/newfish/static/assets/img/zoom.png deleted file mode 100644 index 908612e..0000000 Binary files a/lib/webri/generators/newfish/static/assets/img/zoom.png and /dev/null differ diff --git a/lib/webri/generators/newfish/template/class.rhtml b/lib/webri/generators/newfish/template/class.rhtml index c5d8552..07e1ae1 100644 --- a/lib/webri/generators/newfish/template/class.rhtml +++ b/lib/webri/generators/newfish/template/class.rhtml @@ -1,325 +1,328 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> <% if klass.type == "class" %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> <% else %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> <% end %> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="<%= klass.type %>"> <div id="main"> <div class="head"> <h1> <% if klass.type == "class" %> <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; <% end %> <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <ul> <% klass.in_files.each do |tl| %> <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> <% end %> </ul> </div> </div> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <!-- TODO: generalize this for all SCMs --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> </div> <div id="class-metadata"> <!-- Parent Class --> <% if klass.type == 'class' %> <div id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <ul> <% unless String === klass.superclass %> <!-- why was this class="link" ? --> <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> <% else %> <li class="class"><%= klass.superclass %></li> <% end %> </ul> </div> <% end %> <!-- Namespace Contents --> <% unless klass.classes_and_modules.empty? %> <div id="namespace-list-section" class="section"> <h3 class="section-header">Namespace</h3> <ul class="link-list"> <% (klass.modules.sort + klass.classes.sort).each do |mod| %> - <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> + <li class="<%= mod.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> </div> <% end %> <!-- Method Quickref --> <% unless klass.method_list.empty? %> <div id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <% klass.each_method do |meth| %> - <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> + <% t = meth.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>"> + <a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a> + </li> <% end %> </ul> </div> <% end %> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> </div> <div id="project-metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <!-- classpage.html : classes --> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <div id="documentation"> <div id="description"> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC require 'pp' %> <pre><%= h PP.pp(klass, _erbout) %></pre> </div> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> </main> </body> </html> diff --git a/lib/webri/generators/newfish/template/file.rhtml b/lib/webri/generators/newfish/template/file.rhtml index 61b7695..15e252b 100644 --- a/lib/webri/generators/newfish/template/file.rhtml +++ b/lib/webri/generators/newfish/template/file.rhtml @@ -1,156 +1,155 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= h title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="file"> <!-- .file-popup is no more --> <div id="main"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> <div id="file-stats-section" class="section"> <h3 class="section-header">File Stats</h3> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if !file.requires.empty? %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> - <% RDoc::TopLevel.all_classes_and_modules.map do |mod| - mod.method_list - end.flatten.sort.each do |method| %> - <li class="method" style="clear: both;"> + <% methods_all.each do |method| %> + <% t = method.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- .file-popup was wrapped: <div id="documentation"> <% if file.comment %> <div class="description"> ... file.description ... </div> <% end %> </div> So maybe that css is no longer needed. --> <div id="documentation"> <%= file.description %> </div> </div> </body> </html> diff --git a/lib/webri/generators/newfish/template/index.rhtml b/lib/webri/generators/newfish/template/index.rhtml index 0a20281..3bd5f39 100644 --- a/lib/webri/generators/newfish/template/index.rhtml +++ b/lib/webri/generators/newfish/template/index.rhtml @@ -1,153 +1,152 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= h title %></title> <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="indexpage"> <div id="main"> <% $stderr.sync = true %> <div class="head"> <h1> <img src="assets/img/project.png" align="absmiddle">&nbsp; <a href="index.html"><%= h title %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> - <% RDoc::TopLevel.all_classes_and_modules.map do |mod| - mod.method_list - end.flatten.sort.each do |method| %> - <li class="method" style="clear: both;"> + <% methods_all.each do |method| %> + <% t = method.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <h2>Files</h2> <ul> <% simple_files.sort.each do |file| %> <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> <% end %> <h2>Classes/Modules</h2> <ul> <% classes_salient.each do |klass| %> <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> <% end %> </ul> <h2>Methods</h2> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> <% end %> </ul> --> <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> <div id="documentation"> <%= main_page.description %> </div> <% else %> <p>This is the API documentation for '<%= h title %>'.</p> <% end %> </div> </body> </html> diff --git a/lib/webri/generators/redfish/static/assets/css/rdoc.css b/lib/webri/generators/redfish/static/assets/css/rdoc.css index 09d962d..4dbd4b6 100644 --- a/lib/webri/generators/redfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/redfish/static/assets/css/rdoc.css @@ -1,853 +1,860 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; padding: 0 40px 15px 40px; } #main { width: 1024px; margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } img { border: none; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: #FF226C; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } pre {#FF226C; padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-bottom: 0px solid #aaa; border-left: 0px solid #aaa; border-right: 0px solid #aaa; padding: 10px 10px; margin: 0 8px -0.5em 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; - background: white url(images/wrench_orange.png) no-repeat 4px center; + background: white url(images/fixme.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; - background: url(images/bullet_black.png) no-repeat left 4px; + background: url(../img/bullet.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; - background: url(images/method.png) no-repeat left 2px; + background: url(../img/method.png) no-repeat left 2px; +} + +#metadata li.singleton { + padding-left: 20px; + background: url(../img/singleton.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; - background: url(images/module.png) no-repeat left 2px; + background: url(../img/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; - background: url(images/class.png) no-repeat left 2px; + background: url(../img/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; - background: url(images/file.png) no-repeat left 2px; + background: url(../img/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: right; width: 320px; margin-top: 10px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } +/* #file-metadata ul { padding-left: 28px; - list-style-image: url(images/page_green.png); + list-style-image: url(images/page.png); } +*/ dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } .method-parent-aside { float: right; font-size: 0.7em; font-weight: bold; - padding: 0 20px; + padding: 0 0; color: #999; } /* @end */ /* @group Documentation Section */ #documentation { margin: 0 360px 5em 1em; min-width: 340px; } #documentation h1 { margin: 10px 0 10px 0; padding: 0.5em 0.5em 0.5em 0.5em; border: 1px solid #bbb; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #documentation ul { margin-top: 10px; } #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em 0.5em 0.5em; background-color: #dedede; color: #333; color: #FF226C; font-size: 150%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; - background: url(images/method.png) no-repeat left bottom; + background: url(../img/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; - background: url(images/zoom.png) no-repeat right top; + background: url(../img/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; - background: url(images/alias.png) no-repeat left bottom; + background: url(../img/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { - background: url(images/attribute.png) no-repeat left bottom; + background: url(../ima/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ /* .file #documentation { margin: 0; } */ .file #metadata { float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; - background: url(../img/page_white_width.png) no-repeat left top; + background: url(../img/stat.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { - background: url(../img/wrench.png) no-repeat left top; + background: url(../img/tool.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } .file h1, h2, h3, h4, h5 { color: #FF226C; } /* .file h2 { margin-top: 2em; padding: 0.75em 0.5em 0.5em 0.5em; color: #333; font-size: 120%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; background: #dedede; } /* .file h2 { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.1em; color: #333; font-size: 120%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } */ /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ diff --git a/lib/webri/generators/redfish/static/assets/img/alias.png b/lib/webri/generators/redfish/static/assets/img/alias.png deleted file mode 100644 index 9ebf013..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/alias.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/attribute.png b/lib/webri/generators/redfish/static/assets/img/attribute.png deleted file mode 100644 index 83ec984..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/attribute.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/bug.png b/lib/webri/generators/redfish/static/assets/img/bug.png deleted file mode 100644 index 2d5fb90..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/bug.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/bullet_black.png b/lib/webri/generators/redfish/static/assets/img/bullet_black.png deleted file mode 100644 index 5761970..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/bullet_black.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/bullet_toggle_minus.png b/lib/webri/generators/redfish/static/assets/img/bullet_toggle_minus.png deleted file mode 100644 index b47ce55..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/bullet_toggle_minus.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/bullet_toggle_plus.png b/lib/webri/generators/redfish/static/assets/img/bullet_toggle_plus.png deleted file mode 100644 index 9ab4a89..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/bullet_toggle_plus.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/class.png b/lib/webri/generators/redfish/static/assets/img/class.png deleted file mode 100644 index f763a16..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/class.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/date.png b/lib/webri/generators/redfish/static/assets/img/date.png deleted file mode 100644 index 783c833..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/date.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/file.png b/lib/webri/generators/redfish/static/assets/img/file.png deleted file mode 100644 index 813f712..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/file.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/find.png b/lib/webri/generators/redfish/static/assets/img/find.png deleted file mode 100644 index 1547479..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/find.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/loadingAnimation.gif b/lib/webri/generators/redfish/static/assets/img/loadingAnimation.gif deleted file mode 100644 index 82290f4..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/loadingAnimation.gif and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/macFFBgHack.png b/lib/webri/generators/redfish/static/assets/img/macFFBgHack.png deleted file mode 100644 index c6473b3..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/macFFBgHack.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/method.png b/lib/webri/generators/redfish/static/assets/img/method.png deleted file mode 100644 index 7851cf3..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/method.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/module.png b/lib/webri/generators/redfish/static/assets/img/module.png deleted file mode 100644 index da3c2a2..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/module.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/page_green.png b/lib/webri/generators/redfish/static/assets/img/page_green.png deleted file mode 100644 index de8e003..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/page_green.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/page_white_width.png b/lib/webri/generators/redfish/static/assets/img/page_white_width.png deleted file mode 100644 index 1eb8809..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/page_white_width.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/plugin.png b/lib/webri/generators/redfish/static/assets/img/plugin.png deleted file mode 100644 index 6187b15..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/plugin.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/wrench.png b/lib/webri/generators/redfish/static/assets/img/wrench.png deleted file mode 100644 index 5c8213f..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/wrench.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/wrench_orange.png b/lib/webri/generators/redfish/static/assets/img/wrench_orange.png deleted file mode 100644 index 565a933..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/wrench_orange.png and /dev/null differ diff --git a/lib/webri/generators/redfish/static/assets/img/zoom.png b/lib/webri/generators/redfish/static/assets/img/zoom.png deleted file mode 100644 index 908612e..0000000 Binary files a/lib/webri/generators/redfish/static/assets/img/zoom.png and /dev/null differ diff --git a/lib/webri/generators/redfish/template/.document b/lib/webri/generators/redfish/template/.document deleted file mode 100644 index e69de29..0000000 diff --git a/lib/webri/generators/redfish/template/class.rhtml b/lib/webri/generators/redfish/template/class.rhtml index c5d8552..07e1ae1 100644 --- a/lib/webri/generators/redfish/template/class.rhtml +++ b/lib/webri/generators/redfish/template/class.rhtml @@ -1,325 +1,328 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> <% if klass.type == "class" %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> <% else %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> <% end %> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="<%= klass.type %>"> <div id="main"> <div class="head"> <h1> <% if klass.type == "class" %> <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; <% end %> <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <ul> <% klass.in_files.each do |tl| %> <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> <% end %> </ul> </div> </div> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <!-- TODO: generalize this for all SCMs --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> </div> <div id="class-metadata"> <!-- Parent Class --> <% if klass.type == 'class' %> <div id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <ul> <% unless String === klass.superclass %> <!-- why was this class="link" ? --> <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> <% else %> <li class="class"><%= klass.superclass %></li> <% end %> </ul> </div> <% end %> <!-- Namespace Contents --> <% unless klass.classes_and_modules.empty? %> <div id="namespace-list-section" class="section"> <h3 class="section-header">Namespace</h3> <ul class="link-list"> <% (klass.modules.sort + klass.classes.sort).each do |mod| %> - <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> + <li class="<%= mod.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> </div> <% end %> <!-- Method Quickref --> <% unless klass.method_list.empty? %> <div id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <% klass.each_method do |meth| %> - <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> + <% t = meth.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>"> + <a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a> + </li> <% end %> </ul> </div> <% end %> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> </div> <div id="project-metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <!-- classpage.html : classes --> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <div id="documentation"> <div id="description"> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC require 'pp' %> <pre><%= h PP.pp(klass, _erbout) %></pre> </div> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> </main> </body> </html> diff --git a/lib/webri/generators/redfish/template/file.rhtml b/lib/webri/generators/redfish/template/file.rhtml index d8d8ee0..75572ee 100644 --- a/lib/webri/generators/redfish/template/file.rhtml +++ b/lib/webri/generators/redfish/template/file.rhtml @@ -1,156 +1,155 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="file"> <!-- .file-popup is no more --> <div id="main"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> <div id="file-stats-section" class="section"> <h3 class="section-header">File Stats</h3> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if !file.requires.empty? %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> - <% RDoc::TopLevel.all_classes_and_modules.map do |mod| - mod.method_list - end.flatten.sort.each do |method| %> - <li class="method" style="clear: both;"> + <% methods_all.each do |method| %> + <% t = method.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- .file-popup was wrapped: <div id="documentation"> <% if file.comment %> <div class="description"> ... file.description ... </div> <% end %> </div> So maybe that css is no longer needed. --> <div id="documentation"> <%= file.description %> </div> </div> </body> </html> diff --git a/lib/webri/generators/redfish/template/index.rhtml b/lib/webri/generators/redfish/template/index.rhtml index 0a20281..3bd5f39 100644 --- a/lib/webri/generators/redfish/template/index.rhtml +++ b/lib/webri/generators/redfish/template/index.rhtml @@ -1,153 +1,152 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= h title %></title> <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="indexpage"> <div id="main"> <% $stderr.sync = true %> <div class="head"> <h1> <img src="assets/img/project.png" align="absmiddle">&nbsp; <a href="index.html"><%= h title %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> - <% RDoc::TopLevel.all_classes_and_modules.map do |mod| - mod.method_list - end.flatten.sort.each do |method| %> - <li class="method" style="clear: both;"> + <% methods_all.each do |method| %> + <% t = method.singleton ? 'singleton' : 'method' %> + <li class="<%= t %>" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <h2>Files</h2> <ul> <% simple_files.sort.each do |file| %> <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> <% end %> <h2>Classes/Modules</h2> <ul> <% classes_salient.each do |klass| %> <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> <% end %> </ul> <h2>Methods</h2> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> <% end %> </ul> --> <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> <div id="documentation"> <%= main_page.description %> </div> <% else %> <p>This is the API documentation for '<%= h title %>'.</p> <% end %> </div> </body> </html>
razerbeans/webri
6226fa14db7985b8ca2a08d57867e805366d58da
added icons component to house a set of standard icons
diff --git a/lib/webri/components/icons.rb b/lib/webri/components/icons.rb new file mode 100644 index 0000000..6d69379 --- /dev/null +++ b/lib/webri/components/icons.rb @@ -0,0 +1 @@ +require 'webri/components/icons/component' diff --git a/lib/webri/components/icons/component.rb b/lib/webri/components/icons/component.rb new file mode 100644 index 0000000..a55e3c2 --- /dev/null +++ b/lib/webri/components/icons/component.rb @@ -0,0 +1,13 @@ +require 'webri/componenets/abstract' + +module WebRI + + # Very simple generator component that provides + # a set of small standard name icons for typical + # Ruby needs. + + module Icons < Component + end + +end + diff --git a/lib/webri/components/icons/static/assets/img/alias.png b/lib/webri/components/icons/static/assets/img/alias.png new file mode 100644 index 0000000..9ebf013 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/alias.png differ diff --git a/lib/webri/components/icons/static/assets/img/attribute.png b/lib/webri/components/icons/static/assets/img/attribute.png new file mode 100644 index 0000000..83ec984 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/attribute.png differ diff --git a/lib/webri/components/icons/static/assets/img/bug.png b/lib/webri/components/icons/static/assets/img/bug.png new file mode 100644 index 0000000..2d5fb90 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/bug.png differ diff --git a/lib/webri/components/icons/static/assets/img/bullet.png b/lib/webri/components/icons/static/assets/img/bullet.png new file mode 100644 index 0000000..5761970 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/bullet.png differ diff --git a/lib/webri/components/icons/static/assets/img/bullet_minus.png b/lib/webri/components/icons/static/assets/img/bullet_minus.png new file mode 100644 index 0000000..b47ce55 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/bullet_minus.png differ diff --git a/lib/webri/components/icons/static/assets/img/bullet_plus.png b/lib/webri/components/icons/static/assets/img/bullet_plus.png new file mode 100644 index 0000000..9ab4a89 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/bullet_plus.png differ diff --git a/lib/webri/components/icons/static/assets/img/check.png b/lib/webri/components/icons/static/assets/img/check.png new file mode 100644 index 0000000..83ec984 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/check.png differ diff --git a/lib/webri/components/icons/static/assets/img/class.png b/lib/webri/components/icons/static/assets/img/class.png new file mode 100644 index 0000000..f763a16 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/class.png differ diff --git a/lib/webri/components/icons/static/assets/img/date.png b/lib/webri/components/icons/static/assets/img/date.png new file mode 100644 index 0000000..783c833 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/date.png differ diff --git a/lib/webri/components/icons/static/assets/img/favicon.ico b/lib/webri/components/icons/static/assets/img/favicon.ico new file mode 100644 index 0000000..e0e80cf Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/favicon.ico differ diff --git a/lib/webri/components/icons/static/assets/img/file.png b/lib/webri/components/icons/static/assets/img/file.png new file mode 100644 index 0000000..813f712 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/file.png differ diff --git a/lib/webri/components/icons/static/assets/img/find.png b/lib/webri/components/icons/static/assets/img/find.png new file mode 100644 index 0000000..1547479 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/find.png differ diff --git a/lib/webri/components/icons/static/assets/img/method.png b/lib/webri/components/icons/static/assets/img/method.png new file mode 100644 index 0000000..7851cf3 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/method.png differ diff --git a/lib/webri/components/icons/static/assets/img/module.png b/lib/webri/components/icons/static/assets/img/module.png new file mode 100644 index 0000000..da3c2a2 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/module.png differ diff --git a/lib/webri/components/icons/static/assets/img/plugin.png b/lib/webri/components/icons/static/assets/img/plugin.png new file mode 100644 index 0000000..6187b15 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/plugin.png differ diff --git a/lib/webri/generators/redfish/static/assets/img/project.png b/lib/webri/components/icons/static/assets/img/project.png similarity index 100% rename from lib/webri/generators/redfish/static/assets/img/project.png rename to lib/webri/components/icons/static/assets/img/project.png diff --git a/lib/webri/components/icons/static/assets/img/singleton.png b/lib/webri/components/icons/static/assets/img/singleton.png new file mode 100644 index 0000000..ba43aff Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/singleton.png differ diff --git a/lib/webri/components/icons/static/assets/img/tool.png b/lib/webri/components/icons/static/assets/img/tool.png new file mode 100644 index 0000000..565a933 Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/tool.png differ diff --git a/lib/webri/components/icons/static/assets/img/zoom.png b/lib/webri/components/icons/static/assets/img/zoom.png new file mode 100644 index 0000000..908612e Binary files /dev/null and b/lib/webri/components/icons/static/assets/img/zoom.png differ diff --git a/lib/webri/generators/redfish/generator.rb b/lib/webri/generators/redfish/generator.rb index d9f7dc1..d5936f3 100644 --- a/lib/webri/generators/redfish/generator.rb +++ b/lib/webri/generators/redfish/generator.rb @@ -1,33 +1,35 @@ require 'webri/generators/abstract' +require 'webri/components/icons' require 'webri/components/subversion' module WebRI # = Redfish Template # # Redfish is based on RDoc's default Darkfish generator, # heavily modified to provide only a single sidebar con # document layout. And, as the name indicates, colorized # to be red (instead of green). # - # You can thank Darkfish, a by extension Redfish, for the - # "-fish" naming scheme :) + # You can thank Darkfish, and by extension Redfish, for the + # "-fish" naming scheme of all the templates ;) # class Redfish < Generator + include Icons include Subversion # - def path - @path ||= Pathname.new(__FILE__).parent - end + #def path + # @path ||= Pathname.new(__FILE__).parent + #end # #def generate_template # super #end end end diff --git a/meta/version b/meta/version index d3827e7..9459d4b 100644 --- a/meta/version +++ b/meta/version @@ -1 +1 @@ -1.0 +1.1
razerbeans/webri
f81afeb3f3351a75468510f4bbe36472e9644781
added some new metadata
diff --git a/meta/devsite b/meta/devsite new file mode 100644 index 0000000..a297638 --- /dev/null +++ b/meta/devsite @@ -0,0 +1 @@ +http://github.com/proutils/webri diff --git a/meta/mailinglist b/meta/mailinglist new file mode 100644 index 0000000..9b55ea5 --- /dev/null +++ b/meta/mailinglist @@ -0,0 +1 @@ +http://googlegroups.com/group/proutils diff --git a/meta/wiki b/meta/wiki new file mode 100644 index 0000000..c6325c3 --- /dev/null +++ b/meta/wiki @@ -0,0 +1 @@ +http://proutils.github.com/webri/wiki
razerbeans/webri
d20e38c146113b9ad8330f4b52bd2ec9f192487a
improved newfish and add a rakefile to demo
diff --git a/demo/fish-sampler/Rakefile b/demo/fish-sampler/Rakefile new file mode 100644 index 0000000..559b37d --- /dev/null +++ b/demo/fish-sampler/Rakefile @@ -0,0 +1,35 @@ + +desc "onefish" +task :onefish do + sh "webri -T onefish --main README README lib" +end + +desc "twofish" +task :twofish do + sh "webri -T twofish --main README README lib" +end + +desc "redfish" +task :redfish do + sh "webri -T redfish --main README README lib" +end + +desc "newfish" +task :newfish do + sh "webri -T newfish --main README README lib" +end + +desc "blackfish" +task :blackfish do + sh "webri -T blackfish --main README README lib" +end + +desc "longfish" +task :longfish do + sh "webri -T longfish --main README README lib" +end + +task :clean do + sh "rm -r doc" +end + diff --git a/lib/webri/generators/newfish/static/assets/css/rdoc.css b/lib/webri/generators/newfish/static/assets/css/rdoc.css index a87db22..ada9734 100644 --- a/lib/webri/generators/newfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/newfish/static/assets/css/rdoc.css @@ -1,838 +1,835 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; background: #ffffff; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; padding: 0 40px 15px 40px; } #main { width: 1024px; margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } img { border: none; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: black; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; - color: #669; + color: #844; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } pre { padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; - border-bottom: 0px solid #aaa; - border-left: 0px solid #aaa; - border-right: 0px solid #aaa; padding: 10px 10px; margin: 0 8px -0.5em 8px; } .head h1 { - color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { - color: #FF226C; - color: #666; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; - background: #ddd; - border: 1px solid #aaa; + /* background: #ddd; */ + border: 1px solid #ccc; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; background: url(images/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; background: url(images/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; background: url(images/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; background: url(images/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; background: url(images/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: right; width: 320px; margin-top: 10px; - border-left: 0px solid #aaa; + border-left: 1px solid #ccc; + padding-left: 12px; } #documentation { margin: 0 360px 5em 1em; min-width: 340px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #fff; -moz-border-radius: 5px; -webkit-border-radius: 5px; - border: 0 solid #aaa; + border: 0 solid #ccc; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #fff; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; - border-bottom: 1px solid #aaa; + border-bottom: 1px solid #ccc; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { - border: 0px solid #aaa; + border: 0px solid #ccc; } #project-metadata h3.section-header { - border-bottom: 1px solid #aaa; + border-bottom: 1px solid #ccc; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; - background: #ccc; + background: #ffffff; padding: 8px 8px 16px; - border-bottom: 1px solid #bbb; + border-bottom: 0px solid #ccc; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } .method-parent-aside { float: right; font-size: 0.7em; font-weight: bold; padding: 0 20px; - color: #999; + color: #aaa; + font-family: helvetica; + letter-spacing: -1px; } /* @end */ /* @group Documentation Section */ #documentation h1 { margin: 8px 0 0 0; - padding: 0.5em 0.1em 0.25em 0.1em; + padding: 0.5em 0.1em 0.1em 0.1em; border-bottom: 0px solid #bbb; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #documentation ul { margin-top: 10px; } #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.5em; /* background-color: #dedede; */ color: #333; font-size: 150%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ /* .file #documentation { margin: 0; } */ .file #metadata { float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } /* .file h2 { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.1em; color: #333; font-size: 120%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } */ /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */
razerbeans/webri
00d520a0871064d45c6f40cf763f889005dc769e
fixed all title reference (don't use options.title)
diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index f43a74e..06d6390 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,662 +1,669 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' require 'webri/extensions/times' require 'webri/extensions/fileutils' require 'webri/generators/abstract/metadata' require 'webri/generators/abstract/erbtemplate' # module WebRI # = Abstract Generator Base Class # class Generator PATH = Pathname.new(File.join(LOADPATH, 'webri', 'generators')) #include ERB::Util include Metadata # # C O N S T A N T S # #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. PATH_STATIC = PATH + 'abstract/static' # Common template directory. PATH_TEMPLATE = PATH + 'abstract/template' # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options - # TODO: Get from metadata -- use POM if available. + # Get title from options or metadata. + def title - options.title + @title ||= ( + if options.title == "RDoc Documentation" + metadata.title || "RDoc Documentation" + else + options.title + end + ) end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel ||= @files_rdoc.select { |f| f.parser == RDoc::Parser::Simple } end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(files) @files_rdoc = files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s show_from = PATH_STATIC.to_s.sub(PATH.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(PATH.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' - files_toplevel.each do |file| + files.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template @erb_template ||= ERBTemplate.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/blackfish/template/context.rhtml b/lib/webri/generators/blackfish/template/context.rhtml index 2eae20c..4f34c63 100644 --- a/lib/webri/generators/blackfish/template/context.rhtml +++ b/lib/webri/generators/blackfish/template/context.rhtml @@ -1,164 +1,164 @@ <div id="content"> <% unless (desc = context.description).empty? %> <div class="description"><%= desc %></div> <% end %> <% unless context.requires.empty? %> <div class="sectiontitle">Required Files</div> <ul> <% context.requires.each do |req| %> <li><%= h req.name %></li> <% end %> </ul> <% end %> <% sections = context.sections.select { |section| section.title } %> <% unless sections.empty? %> <div class="sectiontitle">Contents</div> <ul> <% sections.each do |section| %> <li><a href="#<%= section.sequence %>"><%= h section.title %></a></li> <% end %> </ul> <% end %> <% list = context.method_list unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end %> <% unless list.empty? %> <div class="sectiontitle">Methods</div> <ul> <% list.sort{ |a, b| a.name <=> b.name }.each do |method| %> <li><a href="#<%= method.aref %>"><%= method.name %></a></li> <% end %> </ul> <% end %> <% unless context.includes.empty? %> <div class="sectiontitle">Included Modules</div> <ul> <% context.includes.each do |inc| %> <li> <% unless String === inc.module %> <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> <% else %> <span><%= h inc.name %></span> <% end %> START:includes </li> <% end %> </ul> <% end %> <% sections.each do |section| %> <div class="sectiontitle"><a name="<%= h section.sequence %>"><%= h section.title %></a></div> <% unless (description = section.description).empty? %> <div class="description"> <%= description %> </div> <% end %> <% end %> <% unless context.classes_and_modules.empty? %> <div class="sectiontitle">Classes and Modules</div> <ul> <% (context.modules.sort + context.classes.sort).each do |mod| %> <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= context.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> <% end %> <% unless context.constants.empty? %> <div class="sectiontitle">Constants</div> <table border='0' cellpadding='5'> <% context.each_constant do |const| %> <tr valign='top'> <td class="attr-name"><%= h const.name %></td> <td>=</td> <td class="attr-value"><%= h const.value %></td> </tr> <% unless (description = const.description).empty? %> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"><%= description %></td> </tr> <% end %> <% end %> </table> <% end %> <% unless context.attributes.empty? %> <div class="sectiontitle">Attributes</div> <table border='0' cellpadding='5'> <% context.each_attribute do |attrib| %> <tr valign='top'> <td class='attr-rw'> [<%= attrib.rw %>] </td> <td class='attr-name'><%= h attrib.name %></td> <td class='attr-desc'><%= attrib.description.strip %></td> </tr> <% end %> </table> <% end %> <% context.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? next unless options.show_all || visibility == :public || visibility == :protected || methods.any? {|m| m.force_documentation } %> - <div class="sectiontitle"><%= type.capitalize %> <%= visibility.to_s.capitalize %> methods</div> + <div class="sectiontitle"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</div> <% methods.each do |method| %> <div class="method"> <div class="title"> <% if method.call_seq %> <a name="<%= method.aref %>"></a><b><%= method.call_seq.gsub(/->/, '&rarr;') %></b> <% else %> <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> <% end %> </div> <% unless (description = method.description).empty? %> <div class="description"> <%# TODO delete this dirty hack when documentation for example for JavaScriptHelper will not be cutted off by <script> tag %> <%= description.gsub('<script>'){ |m| h(m) } %> </div> <% end %> <% unless method.aliases.empty? %> <div class="aka"> This method is also aliased as <% method.aliases.each do |aka| %> <a href="<%= context.aref_to aka.path %>"><%= h aka.name %></a> <% end %> </div> <% end %> <% if method.token_stream %> <% markup = method.markup_code %> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source">show</a> <% if markup =~ /File\s(\S+), line (\d+)/ path = $1 line = $2.to_i end github = github_url(path) if github %> | <a href="<%= "#{github}#L#{line}" %>" target="_blank" class="github_url">on GitHub</a> <% end %> </p> <div id="<%= method.aref %>_source" class="dyn-source"> <pre><%= method.markup_code %></pre> </div> </div> <% end %> </div> <% end end end %> </div> diff --git a/lib/webri/generators/newfish.rb b/lib/webri/generators/newfish.rb new file mode 100644 index 0000000..68d6b09 --- /dev/null +++ b/lib/webri/generators/newfish.rb @@ -0,0 +1 @@ +require 'webri/generators/newfish/generator' diff --git a/lib/webri/generators/twofish/template/class.rhtml b/lib/webri/generators/twofish/template/class.rhtml index 4b45da3..07db551 100644 --- a/lib/webri/generators/twofish/template/class.rhtml +++ b/lib/webri/generators/twofish/template/class.rhtml @@ -1,285 +1,285 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title><%= h title %> - WebRI</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <meta http-equiv="Content-Type" content="text/html; charset=<%= options.charset %>" /> <link rel="icon" href="<%= rel_prefix %>/assets/img/ruby_logo.png" type="image/x-icon"> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/reset.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/style.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/jquery.jam.js"></script> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/jquery.ri.js"></script> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); </script> </head> <body> <div class="<%= klass.type %>"> <!-- <div class="head"> <h1> <% if klass.type == "class" %> <img src="assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="assets/img/module.png" align="absmiddle">&nbsp; <% end %> - <a href="index.html"><%= h options.title %></a>&nbsp; + <a href="index.html"><%= h title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> --> <!-- <div id="metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> --> <!-- <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% modules_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> </div> --> <div id="documentation"> <div id="description"> <!-- Parent Class --> <% if klass.type == 'class' %> <h1 style="color: #ccc; float: right;"> &lt; <% unless String === klass.superclass %> <a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a> <% else %> <%= klass.superclass %> <% end %> </h1> <% end %> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <br/> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end %> <% end %> <!-- In Files --> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <br/> <ul> <% klass.in_files.each do |tl| %> <li class="file"> <a href="<%= rel_prefix %>/<%= h tl.path %>" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a> </li> <% end %> </ul> </div> </div> <br/></br> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> <% if $DEBUG_RDOC %> <div id="debugging-toggle" class="section"> <img src="assets/img/bug.png" alt="toggle debugging" height="16" width="16" onclick="$('#rdoc-debugging-section-dump').toggle();" /> </div> <% end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC %> <% require 'pp' %> <pre><%= h klass.inspect %></pre> <pre> prefix: <a href="<%= rel_prefix %>"><%= rel_prefix %></a></pre> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> </div> </body> </html> diff --git a/lib/webri/generators/twofish/template/file.rhtml b/lib/webri/generators/twofish/template/file.rhtml index 5a5e0cc..df85b82 100644 --- a/lib/webri/generators/twofish/template/file.rhtml +++ b/lib/webri/generators/twofish/template/file.rhtml @@ -1,137 +1,137 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/reset.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/style.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> </head> <% if file.parser == RDoc::Parser::Simple %> <body> <div class="file"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; - <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; + <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <!-- <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% modules_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <% if $DEBUG_RDOC %> <div id="debugging-toggle"><img src="<%= rel_prefix %>/assets/img/bug.png" alt="toggle debugging" height="16" width="16" /></div> <% end %> </div> <div id="validator-badges"> Generated with <a href="http://github.com/proutils/rdazzle">Razzle Dazzle Redfish</a><br/><br/> <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> --> <div id="documentation"> <%= file.description %> </div> </div> </body> <% else %> <body> <div class="file"> <div id="metadata"> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if file.requires %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="documentation"> <% if file.comment %> <div class="description"> <%= file.description %> </div> <% end %> </div> </div> </body> <% end %> </html>
razerbeans/webri
f35bbb4e2160e5f8912c2aacce6a175cb4b86b6c
method type should come after visibility
diff --git a/lib/webri/generators/longfish/generator.rb b/lib/webri/generators/longfish/generator.rb index f8b7700..1d4de16 100644 --- a/lib/webri/generators/longfish/generator.rb +++ b/lib/webri/generators/longfish/generator.rb @@ -1,78 +1,78 @@ require 'webri/generators/abstract' #require 'webri/components/subversion' require 'webri/components/github' module WebRI # = Longfish Template # # The Longfish tempolate is based on John Long's design # of the ruby-lang.org website. It was built to supply # Ruby core and stadard documentation with an "offical" # look, but there's no reason you can't use it for your # project too, if you prefer it. # class Longfish < Generator #include Subversion include GitHub # def path @path ||= Pathname.new(__FILE__).parent end # def site_homepage metadata.homepage end # def site_community metadata.mailinglist || metadata.wiki end # def site_repository metadata.development end # def site_news metadata.blog end # def index_title @index_title ||= parse_index_header[0] end # def index_description @index_description ||= parse_index_header[1] end # TODO: Generalize for all generators (?) def parse_index_header if options.main_page && main_page = files_toplevel.find { |f| f.full_name == options.main_page } desc = main_page.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) title = md[1] desc = md.post_match else title = options.main_page end else title = options.title - desc = "This is the API documentation for '#{options.title}'." + desc = "This is the API documentation for '#{title}'." end return title, desc end end end
razerbeans/webri
75706b67807bfa1463c7ba7f523cd15e375381fe
made redfish a little more red
diff --git a/lib/webri/generators/redfish/static/assets/css/rdoc.css b/lib/webri/generators/redfish/static/assets/css/rdoc.css index 717a2ff..09d962d 100644 --- a/lib/webri/generators/redfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/redfish/static/assets/css/rdoc.css @@ -1,834 +1,853 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; padding: 0 40px 15px 40px; } #main { width: 1024px; margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } img { border: none; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: #FF226C; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } -pre { +pre {#FF226C; padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-bottom: 0px solid #aaa; border-left: 0px solid #aaa; border-right: 0px solid #aaa; padding: 10px 10px; margin: 0 8px -0.5em 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; background: url(images/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; background: url(images/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; background: url(images/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; background: url(images/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; background: url(images/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: right; width: 320px; margin-top: 10px; } -#documentation { - margin: 0 360px 5em 1em; - min-width: 340px; -} - /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } .method-parent-aside { float: right; font-size: 0.7em; font-weight: bold; padding: 0 20px; color: #999; } /* @end */ /* @group Documentation Section */ + +#documentation { + margin: 0 360px 5em 1em; + min-width: 340px; +} + #documentation h1 { margin: 10px 0 10px 0; - padding: 0.5em 0.1em 0.25em 0.1em; - border-bottom: 0px solid #bbb; + padding: 0.5em 0.5em 0.5em 0.5em; + border: 1px solid #bbb; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #documentation ul { margin-top: 10px; } #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; - padding: 0.75em 0.5em 0.25em 0.5em; - /* background-color: #dedede; */ + padding: 0.75em 0.5em 0.5em 0.5em; + background-color: #dedede; color: #333; + color: #FF226C; font-size: 150%; - border-bottom: 1px solid #bbb; + border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ /* .file #documentation { margin: 0; } */ .file #metadata { float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } +.file h1, h2, h3, h4, h5 { + color: #FF226C; +} + +/* +.file h2 { + margin-top: 2em; + padding: 0.75em 0.5em 0.5em 0.5em; + color: #333; + font-size: 120%; + border: 1px solid #bbb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + background: #dedede; +} + + /* .file h2 { margin-top: 2em; padding: 0.75em 0.5em 0.25em 0.1em; color: #333; font-size: 120%; border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } */ /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ diff --git a/lib/webri/generators/redfish/template/class.rhtml b/lib/webri/generators/redfish/template/class.rhtml index 3cc5cb8..c5d8552 100644 --- a/lib/webri/generators/redfish/template/class.rhtml +++ b/lib/webri/generators/redfish/template/class.rhtml @@ -1,325 +1,325 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> <% if klass.type == "class" %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> <% else %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> <% end %> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="<%= klass.type %>"> <div id="main"> <div class="head"> <h1> <% if klass.type == "class" %> <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; <% end %> - <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; + <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <ul> <% klass.in_files.each do |tl| %> <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> <% end %> </ul> </div> </div> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <!-- TODO: generalize this for all SCMs --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> </div> <div id="class-metadata"> <!-- Parent Class --> <% if klass.type == 'class' %> <div id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <ul> <% unless String === klass.superclass %> <!-- why was this class="link" ? --> <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> <% else %> <li class="class"><%= klass.superclass %></li> <% end %> </ul> </div> <% end %> <!-- Namespace Contents --> <% unless klass.classes_and_modules.empty? %> <div id="namespace-list-section" class="section"> <h3 class="section-header">Namespace</h3> <ul class="link-list"> <% (klass.modules.sort + klass.classes.sort).each do |mod| %> <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> </div> <% end %> <!-- Method Quickref --> <% unless klass.method_list.empty? %> <div id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <% klass.each_method do |meth| %> <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> <% end %> </ul> </div> <% end %> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> </div> <div id="project-metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <!-- classpage.html : classes --> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <div id="documentation"> <div id="description"> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC require 'pp' %> <pre><%= h PP.pp(klass, _erbout) %></pre> </div> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> </main> </body> </html> diff --git a/lib/webri/generators/redfish/template/file.rhtml b/lib/webri/generators/redfish/template/file.rhtml index bf5ac7b..d8d8ee0 100644 --- a/lib/webri/generators/redfish/template/file.rhtml +++ b/lib/webri/generators/redfish/template/file.rhtml @@ -1,156 +1,156 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> - <title>File: <%= file.base_name %> [<%= options.title %>]</title> + <title>File: <%= file.base_name %> [<%= title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="file"> <!-- .file-popup is no more --> <div id="main"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; - <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; + <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> <div id="file-stats-section" class="section"> <h3 class="section-header">File Stats</h3> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if !file.requires.empty? %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li class="method" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- .file-popup was wrapped: <div id="documentation"> <% if file.comment %> <div class="description"> ... file.description ... </div> <% end %> </div> So maybe that css is no longer needed. --> <div id="documentation"> <%= file.description %> </div> </div> </body> </html> diff --git a/lib/webri/generators/redfish/template/index.rhtml b/lib/webri/generators/redfish/template/index.rhtml index c28948c..0a20281 100644 --- a/lib/webri/generators/redfish/template/index.rhtml +++ b/lib/webri/generators/redfish/template/index.rhtml @@ -1,153 +1,153 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> - <title><%= h options.title %></title> + <title><%= h title %></title> <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="indexpage"> <div id="main"> <% $stderr.sync = true %> <div class="head"> <h1> <img src="assets/img/project.png" align="absmiddle">&nbsp; - <a href="index.html"><%= h options.title %></a> + <a href="index.html"><%= h title %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li class="method" style="clear: both;"> <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <h2>Files</h2> <ul> <% simple_files.sort.each do |file| %> <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> <% end %> <h2>Classes/Modules</h2> <ul> <% classes_salient.each do |klass| %> <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> <% end %> </ul> <h2>Methods</h2> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> <% end %> </ul> --> <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> <div id="documentation"> <%= main_page.description %> </div> <% else %> - <p>This is the API documentation for '<%= options.title %>'.</p> + <p>This is the API documentation for '<%= h title %>'.</p> <% end %> </div> </body> </html>
razerbeans/webri
b7d64d48594541457ec5d4f495c0972d79dfd9a4
added newfish template
diff --git a/lib/webri.rb b/lib/webri.rb index bece65b..eb76427 100644 --- a/lib/webri.rb +++ b/lib/webri.rb @@ -1,46 +1,46 @@ #$:.unshift File.dirname(__FILE__) begin require "rubygems" gem "rdoc", ">= 2.4.2" require "rdoc/rdoc" module WebRI LOADPATH = File.dirname(__FILE__) VERSION = "1.0.0" #:till: VERSION="<%= version %>" end require "rdoc/c_parser_fix" unless defined? $WEBRI_FIXED_RDOC_OPTIONS $WEBRI_FIXED_RDOC_OPTIONS = 1 class RDoc::Options #alias_method :rdoc_initialize, :initialize #def initialize # rdoc_initialize # @generator = RDoc::Generator::RDazzle #end alias_method :rdoc_parse, :parse #FIXME: look up templates dynamically def parse(argv) rdoc_parse(argv) - if %w{redfish twofish blackfish longfish onefish}.include?(@template) + if %w{redfish twofish blackfish longfish onefish newfish}.include?(@template) require "webri/generators/#{template}" @generator = WebRI.const_get(@template.capitalize) end end end end rescue Exception warn "WebRI requires RDoc v2.4.2 or greater." end diff --git a/lib/webri/generators/newfish/generator.rb b/lib/webri/generators/newfish/generator.rb new file mode 100644 index 0000000..8e9018d --- /dev/null +++ b/lib/webri/generators/newfish/generator.rb @@ -0,0 +1,33 @@ +require 'webri/generators/abstract' +require 'webri/components/subversion' + +module WebRI + + # = Redfish Template + # + # Redfish is based on RDoc's default Darkfish generator, + # heavily modified to provide only a single sidebar con + # document layout. And, as the name indicates, colorized + # to be red (instead of green). + # + # You can thank Darkfish, a by extension Redfish, for the + # "-fish" naming scheme :) + # + class Newfish < Generator + + include Subversion + + # + #def path + # @path ||= Pathname.new(__FILE__).parent + #end + + # + #def generate_template + # super + #end + + end + +end + diff --git a/lib/webri/generators/newfish/static/assets/css/rdoc.css b/lib/webri/generators/newfish/static/assets/css/rdoc.css new file mode 100644 index 0000000..a87db22 --- /dev/null +++ b/lib/webri/generators/newfish/static/assets/css/rdoc.css @@ -0,0 +1,838 @@ +/* + * "Darkfish" Rdoc CSS + * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ + * + * Author: Michael Granger <[email protected]> + * + */ + +/* Base Red is: color: #FF226C; */ + +*{ padding: 0; margin: 0; } + +body { + background: #efefef; + background: #ffffff; + font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; + padding: 0 40px 15px 40px; +} + +#main { + width: 1024px; + margin: 0 auto; +} + +/* +body.class, body.module, body.file { + margin-left: 40px; +} +*/ + +body.file-popup { + font-size: 90%; + margin-left: 0; +} + +img { border: none; } + +h1 { + font-size: 300%; + text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; + color: black; +} + +h2,h3,h4 { margin-top: 1.5em; } + +a { + color: #FF226C; + color: #669; + text-decoration: none; +} + +a:hover { + border-bottom: 1px dotted #FF226C; +} + +pre { + padding: 0.5em 0; + border: 1px solid #ccc; +} + +p { + margin: 1em 0; +} + +ul { + margin-left: 20px; +} + + +.head { + width: auto; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-bottom: 0px solid #aaa; + border-left: 0px solid #aaa; + border-right: 0px solid #aaa; + padding: 10px 10px; + margin: 0 8px -0.5em 8px; +} + +.head h1 { + color: #FF226C; + color: #666; + font-weight: bold; + font-size: 18px; +} + +.head h1 a { + color: #FF226C; + color: #666; + font-weight: bold; +} + +/* @group Generic Classes */ + +.initially-hidden { + display: none; +} + +.quicksearch-field { + width: 98%; + background: #ddd; + border: 1px solid #aaa; + height: 1.5em; + -webkit-border-radius: 4px; +} +.quicksearch-field:focus { + background: #f1edba; +} + +.missing-docs { + font-size: 120%; + background: white url(images/wrench_orange.png) no-repeat 4px center; + color: #ccc; + line-height: 2em; + border: 0px solid #d00; + opacity: 1; + padding-left: 20px; + text-indent: 24px; + letter-spacing: 3px; + font-weight: bold; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; +} + +.target-section { + border: 2px solid #dcce90; + border-left-width: 8px; + padding: 0 1em; + background: #fff3c2; +} + +/* @end */ + + +/* @group Index Page, Standalone file pages */ + +/* +body.indexpage { + margin: 1em 3em; +} +*/ + +/* +body.indexpage p, +body.indexpage div, +body.file p { + margin: 1em 0; +} +*/ + +#metadata ul { + font-size: 14px; +} + +#metadata ul a { + font-size: 14px; +} + +/* +.indexpage ul, +.file #documentation ul { + line-height: 160%; + list-style: none; +} +*/ + +#metadata ul { + list-style: none; + margin-left: 0; +} + +/* +.indexpage ul a, +.file #documentation ul a { + font-size: 16px; +} +*/ + +#metadata li { + padding-left: 20px; + background: url(images/bullet_black.png) no-repeat left 4px; + color: #666; +} + +#metadata li.method { + padding-left: 20px; + background: url(images/method.png) no-repeat left 2px; +} + +#metadata li.module { + padding-left: 20px; + background: url(images/module.png) no-repeat left 2px; +} + +#metadata li.class { + padding-left: 20px; + background: url(images/class.png) no-repeat left 2px; +} + +#metadata li.file { + padding-left: 20px; + background: url(images/file.png) no-repeat left 2px; +} + +/* @end */ + +/* @group Top-Level Structure */ + +#metadata { + float: right; + width: 320px; + margin-top: 10px; + border-left: 0px solid #aaa; +} + +#documentation { + margin: 0 360px 5em 1em; + min-width: 340px; +} + +/* +.file #metadata { + margin: 0.8em; +} +*/ + +#validator-badges { + clear: both; + text-align: left; + margin: 1em 1em 2em; + font-weight: bold; + font-size: 80%; +} + +/* @end */ + +/* @group Metadata Section */ + +#metadata .section { + background-color: #fff; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border: 0 solid #aaa; + margin: 0 8px 16px; + font-size: 90%; + overflow: hidden; +} + +#metadata h3.section-header { + margin: 0; + padding: 2px 8px; + background: #fff; + color: #666; + -moz-border-radius-topleft: 4px; + -moz-border-radius-topright: 4px; + -webkit-border-top-left-radius: 4px; + -webkit-border-top-right-radius: 4px; + border-bottom: 1px solid #aaa; +} + +#metadata ul, +#metadata dl, +#metadata p { + padding: 8px; + list-style: none; +} + +#file-metadata ul { + padding-left: 28px; + list-style-image: url(images/page_green.png); +} + +dl.svninfo { + color: #666; + margin: 0; +} +dl.svninfo dt { + font-weight: bold; +} + +ul.link-list li { + white-space: nowrap; +} + +ul.link-list .type { + font-size: 8px; + text-transform: uppercase; + color: white; + background: #969696; + padding: 2px 4px; + -webkit-border-radius: 5px; +} + +/* @end */ + + +/* @group Project Metadata Section */ +#project-metadata { + margin-top: 0em; +} + +/* +.file #project-metadata { + margin-top: 0em; +} +*/ + +#project-metadata .section { + border: 0px solid #aaa; +} +#project-metadata h3.section-header { + border-bottom: 1px solid #aaa; + position: relative; +} +#project-metadata h3.section-header .search-toggle { + position: absolute; + right: 5px; +} + + +#project-metadata form { + color: #777; + background: #ccc; + padding: 8px 8px 16px; + border-bottom: 1px solid #bbb; +} +#project-metadata fieldset { + border: 0; +} + +#no-class-search-results { + margin: 0 auto 1em; + text-align: center; + font-size: 14px; + font-weight: bold; + color: #aaa; +} + +.method-parent-aside { + float: right; font-size: 0.7em; + font-weight: bold; + padding: 0 20px; + color: #999; +} + +/* @end */ + + +/* @group Documentation Section */ + +#documentation h1 { + margin: 8px 0 0 0; + padding: 0.5em 0.1em 0.25em 0.1em; + border-bottom: 0px solid #bbb; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; +} + +#documentation ul { + margin-top: 10px; +} + +#description { + font-size: 100%; + color: #333; +} + +#description p { + margin: 1em 0.4em; +} + +#description ul { + margin-left: 2em; +} +#description ul li { + line-height: 1.4em; +} + +#description dl, +#documentation dl { + margin: 8px 1.5em; + border: 1px solid #ccc; +} +#description dl { + font-size: 14px; +} + +#description dt, +#documentation dt { + padding: 2px 4px; + font-weight: bold; + background: #ddd; +} +#description dd, +#documentation dd { + padding: 2px 12px; +} +#description dd + dt, +#documentation dd + dt { + margin-top: 0.7em; +} + +#documentation .section { + font-size: 90%; +} +#documentation h3.section-header { + margin-top: 2em; + padding: 0.75em 0.5em 0.25em 0.5em; + /* background-color: #dedede; */ + color: #333; + font-size: 150%; + border-bottom: 1px solid #bbb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; +} + +#constants-list > dl, +#attributes-list > dl { + margin: 1em 0 2em 2em; + border: 0; +} +#constants-list > dl dt, +#attributes-list > dl dt { + padding-left: 0; + font-weight: bold; + font-family: Monaco, "Andale Mono"; + background: inherit; +} +#constants-list > dl dt a, +#attributes-list > dl dt a { + color: inherit; +} +#constants-list > dl dd, +#attributes-list > dl dd { + margin: 0 0 1em 0; + padding: 0; + color: #666; +} + +/* @group Method Details */ + +#documentation .method-source-code { + display: none; +} + +#documentation .method-detail { + margin: 0.5em 0; + padding: 0.5em 0; + cursor: pointer; +} +#documentation .method-detail:hover { + background-color: #f1edba; +} +#documentation .method-alias { + font-style: oblique; +} +#documentation .method-heading { + position: relative; + padding: 2px 4px 0 20px; + font-size: 125%; + font-weight: bold; + color: #333; + background: url(images/method.png) no-repeat left bottom; +} +#documentation .method-heading a { + color: inherit; +} +#documentation .method-click-advice { + position: absolute; + top: 2px; + right: 5px; + font-size: 10px; + color: #9b9877; + visibility: hidden; + padding-right: 20px; + line-height: 20px; + background: url(images/zoom.png) no-repeat right top; +} +#documentation .method-detail:hover .method-click-advice { + visibility: visible; +} + +#documentation .method-alias .method-heading { + color: #666; + background: url(images/alias.png) no-repeat left bottom; +} + +#documentation .method-description, +#documentation .aliases { + margin: 0 20px; + line-height: 1.2em; + color: #666; +} +#documentation .aliases { + padding-top: 4px; + font-style: italic; + cursor: default; +} +#documentation .method-description p { + padding: 0; +} +#documentation .method-description p + p { + margin-bottom: 0.5em; +} + +#documentation .attribute-method-heading { + background: url(images/attribute.png) no-repeat left bottom; +} +#documentation #attribute-method-details .method-detail:hover { + background-color: transparent; + cursor: default; +} +#documentation .attribute-access-type { + font-size: 60%; + text-transform: uppercase; + vertical-align: super; + padding: 0 2px; +} +/* @end */ + +/* @end */ + + + +/* @group Source Code */ + +a.source-toggle { + font-size: 90%; +} + +a.source-toggle img { +} + +div.method-source-code { + background: #262626; + background: #F6F6F6; + color: #2f2f2f; + margin: 1em; + padding: 0.5em; + border: 1px dashed #999; + overflow: hidden; +} + +div.method-source-code pre { + background: inherit; + padding: 0; + color: #222; + overflow: hidden; +} + +/* @group Ruby keyword styles */ + +.standalone-code { background: #221111; color: #22dead; overflow: hidden; } + +.ruby-constant { color: #7fffd4; background: transparent; } +.ruby-keyword { color: #00ffff; background: transparent; } +.ruby-ivar { color: #eedd82; background: transparent; } +.ruby-operator { color: #00ffee; background: transparent; } +.ruby-identifier { color: #ffdead; background: transparent; } +.ruby-node { color: #ffa07a; background: transparent; } +.ruby-comment { color: #b22222; background: transparent; font-weight: bold;} +.ruby-regexp { color: #ffa07a; background: transparent; } +.ruby-value { color: #7fffd4; background: transparent; } + +.ruby-constant { color: #70004d; background: transparent; } +.ruby-keyword { color: #000000; background: transparent; font-weight: bold;} +.ruby-ivar { color: #11448e; background: transparent; } +.ruby-operator { color: #ff0022; background: transparent; } +.ruby-identifier { color: #00413d; background: transparent; } +.ruby-node { color: #001f71; background: transparent; } +.ruby-comment { color: #bbbbbb; background: transparent; } +.ruby-regexp { color: #001f71; background: transparent; } +.ruby-value { color: #70004d; background: transparent; } + +/* @end */ +/* @end */ + + +/* @group File Popup Contents */ + +/* .file #documentation { + margin: 0; +} */ + +.file #metadata { + float: right; +} + +.file-popup #metadata { + float: right; +} + +.file-popup dl { + font-size: 80%; + padding: 0.75em; + background-color: #efefef; + color: #333; + border: 1px solid #bbb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; +} +.file dt { + font-weight: bold; + padding-left: 22px; + line-height: 20px; + background: url(../img/page_white_width.png) no-repeat left top; +} +.file dt.modified-date { + background: url(../img/date.png) no-repeat left top; +} +.file dt.requires { + background: url(../img/plugin.png) no-repeat left top; +} +.file dt.scs-url { + background: url(../img/wrench.png) no-repeat left top; +} + +.file dl dd { + margin: 0 0 1em 0; +} +.file #metadata dl dd ul { + list-style: circle; + margin-left: 20px; + padding-top: 0; +} +.file #metadata dl dd ul li { +} + +/* +.file h2 { + margin-top: 2em; + padding: 0.75em 0.5em 0.25em 0.1em; + color: #333; + font-size: 120%; + border-bottom: 1px solid #bbb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; +} +*/ + +/* @end */ + + +/* @group Debugging Section */ + +#debugging-toggle { + text-align: center; +} +#debugging-toggle img { + cursor: pointer; +} + +#rdoc-debugging-section-dump { + display: none; + margin: 0 2em 2em; + background: #ccc; + border: 1px solid #999; +} + +/* @end */ + + + + + + + + + + + + + + +/* @group ThickBox Styles */ +#TB_window { + font: 12px Arial, Helvetica, sans-serif; + color: #333333; +} + +#TB_secondLine { + font: 10px Arial, Helvetica, sans-serif; + color:#666666; +} + +#TB_window a:link {color: #666666;} +#TB_window a:visited {color: #666666;} +#TB_window a:hover {color: #000;} +#TB_window a:active {color: #666666;} +#TB_window a:focus{color: #666666;} + +#TB_overlay { + position: fixed; + z-index:100; + top: 0px; + left: 0px; + height:100%; + width:100%; +} + +.TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} +.TB_overlayBG { + background-color:#000; + filter:alpha(opacity=75); + -moz-opacity: 0.75; + opacity: 0.75; +} + +* html #TB_overlay { /* ie6 hack */ + position: absolute; + height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); +} + +#TB_window { + position: fixed; + background: #ffffff; + z-index: 102; + color:#000000; + display:none; + border: 4px solid #525252; + text-align:left; + top:50%; + left:50%; +} + +* html #TB_window { /* ie6 hack */ +position: absolute; +margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); +} + +#TB_window img#TB_Image { + display:block; + margin: 15px 0 0 15px; + border-right: 1px solid #ccc; + border-bottom: 1px solid #ccc; + border-top: 1px solid #666; + border-left: 1px solid #666; +} + +#TB_caption{ + height:25px; + padding:7px 30px 10px 25px; + float:left; +} + +#TB_closeWindow{ + height:25px; + padding:11px 25px 10px 0; + float:right; +} + +#TB_closeAjaxWindow{ + padding:7px 10px 5px 0; + margin-bottom:1px; + text-align:right; + float:right; +} + +#TB_ajaxWindowTitle{ + float:left; + padding:7px 0 5px 10px; + margin-bottom:1px; + font-size: 22px; +} + +#TB_title{ + background-color: #FF226C; + color: #dedede; + height:40px; +} +#TB_title a { + color: white !important; + border-bottom: 1px dotted #dedede; +} + +#TB_ajaxContent{ + clear:both; + padding:2px 15px 15px 15px; + overflow:auto; + text-align:left; + line-height:1.4em; +} + +#TB_ajaxContent.TB_modal{ + padding:15px; +} + +#TB_ajaxContent p{ + padding:5px 0px 5px 0px; +} + +#TB_load{ + position: fixed; + display:none; + height:13px; + width:208px; + z-index:103; + top: 50%; + left: 50%; + margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ +} + +* html #TB_load { /* ie6 hack */ +position: absolute; +margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); +} + +#TB_HideSelect{ + z-index:99; + position:fixed; + top: 0; + left: 0; + background-color:#fff; + border:none; + filter:alpha(opacity=0); + -moz-opacity: 0; + opacity: 0; + height:100%; + width:100%; +} + +* html #TB_HideSelect { /* ie6 hack */ + position: absolute; + height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); +} + +#TB_iframeContent{ + clear:both; + border:none; + margin-bottom:-1px; + margin-top:1px; + _margin-bottom:1px; +} + +/* @end */ + + diff --git a/lib/webri/generators/newfish/static/assets/img/alias.png b/lib/webri/generators/newfish/static/assets/img/alias.png new file mode 100644 index 0000000..9ebf013 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/alias.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/attribute.png b/lib/webri/generators/newfish/static/assets/img/attribute.png new file mode 100644 index 0000000..83ec984 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/attribute.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/bug.png b/lib/webri/generators/newfish/static/assets/img/bug.png new file mode 100644 index 0000000..2d5fb90 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/bug.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_black.png b/lib/webri/generators/newfish/static/assets/img/bullet_black.png new file mode 100644 index 0000000..5761970 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/bullet_black.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png new file mode 100644 index 0000000..b47ce55 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_minus.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png new file mode 100644 index 0000000..9ab4a89 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/bullet_toggle_plus.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/class.png b/lib/webri/generators/newfish/static/assets/img/class.png new file mode 100644 index 0000000..f763a16 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/class.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/date.png b/lib/webri/generators/newfish/static/assets/img/date.png new file mode 100644 index 0000000..783c833 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/date.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/file.png b/lib/webri/generators/newfish/static/assets/img/file.png new file mode 100644 index 0000000..813f712 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/file.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/find.png b/lib/webri/generators/newfish/static/assets/img/find.png new file mode 100644 index 0000000..1547479 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/find.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif b/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif new file mode 100644 index 0000000..82290f4 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/loadingAnimation.gif differ diff --git a/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png b/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png new file mode 100644 index 0000000..c6473b3 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/macFFBgHack.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/method.png b/lib/webri/generators/newfish/static/assets/img/method.png new file mode 100644 index 0000000..7851cf3 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/method.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/module.png b/lib/webri/generators/newfish/static/assets/img/module.png new file mode 100644 index 0000000..da3c2a2 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/module.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/page_green.png b/lib/webri/generators/newfish/static/assets/img/page_green.png new file mode 100644 index 0000000..de8e003 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/page_green.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/page_white_width.png b/lib/webri/generators/newfish/static/assets/img/page_white_width.png new file mode 100644 index 0000000..1eb8809 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/page_white_width.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/plugin.png b/lib/webri/generators/newfish/static/assets/img/plugin.png new file mode 100644 index 0000000..6187b15 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/plugin.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/project.png b/lib/webri/generators/newfish/static/assets/img/project.png new file mode 100644 index 0000000..9183c02 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/project.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/ruby.png b/lib/webri/generators/newfish/static/assets/img/ruby.png new file mode 100644 index 0000000..f763a16 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/ruby.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/wrench.png b/lib/webri/generators/newfish/static/assets/img/wrench.png new file mode 100644 index 0000000..5c8213f Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/wrench.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/wrench_orange.png b/lib/webri/generators/newfish/static/assets/img/wrench_orange.png new file mode 100644 index 0000000..565a933 Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/wrench_orange.png differ diff --git a/lib/webri/generators/newfish/static/assets/img/zoom.png b/lib/webri/generators/newfish/static/assets/img/zoom.png new file mode 100644 index 0000000..908612e Binary files /dev/null and b/lib/webri/generators/newfish/static/assets/img/zoom.png differ diff --git a/lib/webri/generators/newfish/static/assets/js/darkfish.js b/lib/webri/generators/newfish/static/assets/js/darkfish.js new file mode 100644 index 0000000..0020f25 --- /dev/null +++ b/lib/webri/generators/newfish/static/assets/js/darkfish.js @@ -0,0 +1,107 @@ +/** + * + * Darkfish Page Functions + * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ + * + * Author: Michael Granger <[email protected]> + * + */ + +/* Provide console simulation for firebug-less environments */ +if (!("console" in window) || !("firebug" in console)) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", + "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; + + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +}; + + +/** + * Unwrap the first element that matches the given @expr@ from the targets and return them. + */ +$.fn.unwrap = function( expr ) { + return this.each( function() { + $(this).parents( expr ).eq( 0 ).after( this ).remove(); + }); +}; + + +function showSource( e ) { + var target = e.target; + var codeSections = $(target). + parents('.method-detail'). + find('.method-source-code'); + + $(target). + parents('.method-detail'). + find('.method-source-code'). + slideToggle(); +}; + +function hookSourceViews() { + $('.method-description,.method-heading').click( showSource ); +}; + +function toggleDebuggingSection() { + $('.debugging-section').slideToggle(); +}; + +function hookDebuggingToggle() { + $('#debugging-toggle img').click( toggleDebuggingSection ); +}; + +function hookQuickSearch() { + $('.quicksearch-field').each( function() { + var searchElems = $(this).parents('.section').find( 'li' ); + var toggle = $(this).parents('.section').find('h3 .search-toggle'); + // console.debug( "Toggle is: %o", toggle ); + var qsbox = $(this).parents('form').get( 0 ); + + $(this).quicksearch( this, searchElems, { + noSearchResultsIndicator: 'no-class-search-results', + focusOnLoad: false + }); + $(toggle).click( function() { + // console.debug( "Toggling qsbox: %o", qsbox ); + $(qsbox).toggle(); + }); + }); +}; + +function highlightTarget( anchor ) { + console.debug( "Highlighting target '%s'.", anchor ); + + $("a[name=" + anchor + "]").each( function() { + if ( !$(this).parent().parent().hasClass('target-section') ) { + console.debug( "Wrapping the target-section" ); + $('div.method-detail').unwrap( 'div.target-section' ); + $(this).parent().wrap( '<div class="target-section"></div>' ); + } else { + console.debug( "Already wrapped." ); + } + }); +}; + +function highlightLocationTarget() { + console.debug( "Location hash: %s", window.location.hash ); + if ( ! window.location.hash || window.location.hash.length == 0 ) return; + + var anchor = window.location.hash.substring(1); + console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" ); + + highlightTarget( anchor ); +}; + +function highlightClickTarget( event ) { + console.debug( "Highlighting click target for event %o", event.target ); + try { + var anchor = $(event.target).attr( 'href' ).substring(1); + console.debug( "Found target anchor: %s", anchor ); + highlightTarget( anchor ); + } catch ( err ) { + console.error( "Exception while highlighting: %o", err ); + }; +}; + diff --git a/lib/webri/generators/newfish/static/assets/js/quicksearch.js b/lib/webri/generators/newfish/static/assets/js/quicksearch.js new file mode 100644 index 0000000..332772a --- /dev/null +++ b/lib/webri/generators/newfish/static/assets/js/quicksearch.js @@ -0,0 +1,114 @@ +/** + * + * JQuery QuickSearch - Hook up a form field to hide non-matching elements. + * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $ + * + * Author: Michael Granger <[email protected]> + * + */ +jQuery.fn.quicksearch = function( target, searchElems, options ) { + // console.debug( "Quicksearch fn" ); + + var settings = { + delay: 250, + clearButton: false, + highlightMatches: false, + focusOnLoad: false, + noSearchResultsIndicator: null + }; + if ( options ) $.extend( settings, options ); + + return jQuery(this).each( function() { + // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems ); + new jQuery.quicksearch( this, searchElems, settings ); + }); +}; + + +jQuery.quicksearch = function( searchBox, searchElems, settings ) { + var timeout; + var boxdiv = $(searchBox).parents('div').eq(0); + + function init() { + setupKeyEventHandlers(); + focusOnLoad(); + }; + + function setupKeyEventHandlers() { + // console.debug( "Hooking up the 'keypress' event to %o", searchBox ); + $(searchBox). + unbind( 'keyup' ). + keyup( function(e) { return onSearchKey( e.keyCode ); }); + $(searchBox). + unbind( 'keypress' ). + keypress( function(e) { + switch( e.which ) { + // Execute the search on Enter, Tab, or Newline + case 9: + case 13: + case 10: + clearTimeout( timeout ); + e.preventDefault(); + doQuickSearch(); + break; + + // Allow backspace + case 8: + return true; + break; + + // Only allow valid search characters + default: + return validQSChar( e.charCode ); + } + }); + }; + + function focusOnLoad() { + if ( !settings.focusOnLoad ) return false; + $(searchBox).focus(); + }; + + function onSearchKey ( code ) { + clearTimeout( timeout ); + // console.debug( "...scheduling search." ); + timeout = setTimeout( doQuickSearch, settings.delay ); + }; + + function validQSChar( code ) { + var c = String.fromCharCode( code ); + return ( + (c == ':') || + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') + ); + }; + + function doQuickSearch() { + var searchText = searchBox.value; + var pat = new RegExp( searchText, "im" ); + var shownCount = 0; + + if ( settings.noSearchResultsIndicator ) { + $('#' + settings.noSearchResultsIndicator).hide(); + } + + // All elements start out hidden + $(searchElems).each( function(index) { + var str = $(this).text(); + + if ( pat.test(str) ) { + shownCount += 1; + $(this).fadeIn(); + } else { + $(this).hide(); + } + }); + + if ( shownCount == 0 && settings.noSearchResultsIndicator ) { + $('#' + settings.noSearchResultsIndicator).slideDown(); + } + }; + + init(); +}; diff --git a/lib/webri/generators/newfish/static/assets/js/ready.js b/lib/webri/generators/newfish/static/assets/js/ready.js new file mode 100644 index 0000000..5d27860 --- /dev/null +++ b/lib/webri/generators/newfish/static/assets/js/ready.js @@ -0,0 +1,13 @@ +$(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); +}); + diff --git a/lib/webri/generators/newfish/template/.document b/lib/webri/generators/newfish/template/.document new file mode 100644 index 0000000..e69de29 diff --git a/lib/webri/generators/newfish/template/class.rhtml b/lib/webri/generators/newfish/template/class.rhtml new file mode 100644 index 0000000..c5d8552 --- /dev/null +++ b/lib/webri/generators/newfish/template/class.rhtml @@ -0,0 +1,325 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> + + <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> + + <% if klass.type == "class" %> + <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> + <% else %> + <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> + <% end %> + + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> + + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> +</head> +<body class="<%= klass.type %>"> +<div id="main"> + + <div class="head"> + <h1> + <% if klass.type == "class" %> + <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; + <% else %> + <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; + <% end %> + <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; + <a href="/"><%= klass.full_name %></a> + </h1> + </div> + + <div id="metadata"> + <div id="project-metadata"> + + <div id="file-list-section" class="section"> + <h3 class="section-header">In Files</h3> + <div class="section-body"> + <ul> + <% klass.in_files.each do |tl| %> + <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" + class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> + <% end %> + </ul> + </div> + </div> + + <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> + <!-- TODO: generalize this for all SCMs --> + + <% if !svninfo(klass).empty? %> + <div id="file-svninfo-section" class="section"> + <h3 class="section-header">Subversion Info</h3> + <div class="section-body"> + <dl class="svninfo"> + <dt>Rev</dt> + <dd><%= svninfo(klass)[:rev] %></dd> + + <dt>Last Checked In</dt> + <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> + (<%= svninfo(klass)[:commitdelta] %> ago)</dd> + + <dt>Checked in by</dt> + <dd><%= svninfo(klass)[:committer] %></dd> + </dl> + </div> + </div> + <% end %> + </div> + + <div id="class-metadata"> + + <!-- Parent Class --> + <% if klass.type == 'class' %> + <div id="parent-class-section" class="section"> + <h3 class="section-header">Parent</h3> + <ul> + <% unless String === klass.superclass %> + <!-- why was this class="link" ? --> + <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> + <% else %> + <li class="class"><%= klass.superclass %></li> + <% end %> + </ul> + </div> + <% end %> + + <!-- Namespace Contents --> + <% unless klass.classes_and_modules.empty? %> + <div id="namespace-list-section" class="section"> + <h3 class="section-header">Namespace</h3> + <ul class="link-list"> + <% (klass.modules.sort + klass.classes.sort).each do |mod| %> + <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> + <% end %> + </ul> + </div> + <% end %> + + <!-- Method Quickref --> + <% unless klass.method_list.empty? %> + <div id="method-list-section" class="section"> + <h3 class="section-header">Methods</h3> + <ul class="link-list"> + <% klass.each_method do |meth| %> + <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> + <% end %> + </ul> + </div> + <% end %> + + <!-- Included Modules --> + <% unless klass.includes.empty? %> + <div id="includes-section" class="section"> + <h3 class="section-header">Included Modules</h3> + <ul class="link-list"> + <% klass.each_include do |inc| %> + <% unless String === inc.module %> + <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> + <% else %> + <li class="module"><span class="include"><%= inc.name %></span></li> + <% end %> + <% end %> + </ul> + </div> + <% end %> + </div> + + <div id="project-metadata"> + <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> + <% unless simple_files.empty? then %> + <div id="fileindex-section" class="section project-section"> + <h3 class="section-header">Files</h3> + <ul> + <% simple_files.each do |file| %> + <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> + <% end %> + </ul> + </div> + <% end %> + + <div id="classindex-section" class="section project-section"> + <h3 class="section-header">Class Index + <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" + height="16" width="16" alt="[+]" + title="show/hide quicksearch" /></span></h3> + <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> + <fieldset> + <legend>Quicksearch</legend> + <input type="text" name="quicksearch" value="" + class="quicksearch-field" /> + </fieldset> + </form> + + <!-- classpage.html : classes --> + <ul class="link-list"> + <% classes_salient.each do |index_klass| %> + <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> + <% end %> + </ul> + <div id="no-class-search-results" style="display: none;">No matching classes.</div> + </div> + </div> + + <div id="validator-badges"> + <% if $DEBUG_RDOC %> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> + </div> + <% end %> + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> + Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> + <br/><br/> + </div> + </div> + + <div id="documentation"> + + <div id="description"> + <% if /\s*\<h1\>/ !~ klass.description %> + <h1><%= klass.name %></h1> + <% end %> + + <%= klass.description %> + </div> + + <!-- Constants --> + <% unless klass.constants.empty? %> + <div id="constants-list" class="section"> + <h3 class="section-header">Constants</h3> + <dl> + <% klass.each_constant do |const| %> + <dt><a name="<%= const.name %>"><%= const.name %></a></dt> + <% if const.comment %> + <dd class="description"><%= const.description.strip %></dd> + <% else %> + <dd class="description missing-docs">(Not documented)</dd> + <% end %> + <% end %> + </dl> + </div> + <% end %> + + <!-- Attributes --> + <% unless klass.attributes.empty? %> + <div id="attribute-method-details" class="method-section section"> + <h3 class="section-header">Attributes</h3> + + <% klass.each_attribute do |attrib| %> + <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> + <a name="<%= h attrib.name %>"></a> + <% if attrib.rw =~ /w/i %> + <a name="<%= h attrib.name %>="></a> + <% end %> + <div class="method-heading attribute-method-heading"> + <span class="method-name"><%= h attrib.name %></span><span + class="attribute-access-type">[<%= attrib.rw %>]</span> + </div> + + <div class="method-description"> + <% if attrib.comment %> + <%= attrib.description.strip %> + <% else %> + <p class="missing-docs">(Not documented)</p> + <% end %> + </div> + </div> + <% end %> + </div> + <% end %> + + <!-- Methods --> + <% klass.methods_by_type.each do |type, visibilities| + next if visibilities.empty? + visibilities.each do |visibility, methods| + next if methods.empty? %> + <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> + <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> + + <% methods.each do |method| %> + <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> + <a name="<%= h method.aref %>"></a> + + <div class="method-heading"> + <% if method.call_seq %> + <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> + <span class="method-click-advice">click to toggle source</span> + <% else %> + <span class="method-name"><%= h method.name %></span><span + class="method-args"><%= method.params %></span> + <span class="method-click-advice">click to toggle source</span> + <% end %> + </div> + + <div class="method-description"> + <% if method.comment %> + <%= method.description.strip %> + <% else %> + <p class="missing-docs">(Not documented)</p> + <% end %> + + <% if method.token_stream %> + <div class="method-source-code" + id="<%= method.html_name %>-source"> +<pre> +<%= method.markup_code %> +</pre> + </div> + <% end %> + </div> + + <% unless method.aliases.empty? %> + <div class="aliases"> + Also aliased as: <%= method.aliases.map do |aka| + %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} + end.join(", ") %> + </div> + <% end %> + </div> + + <% end %> + </div> + <% end + end %> + + </div> + + + <div id="rdoc-debugging-section-dump" class="debugging-section"> + <% if $DEBUG_RDOC + require 'pp' %> +<pre><%= h PP.pp(klass, _erbout) %></pre> + </div> + <% else %> + <p>Disabled; run with --debug to generate this.</p> + <% end %> + </div> + +</main> +</body> +</html> + diff --git a/lib/webri/generators/newfish/template/file.rhtml b/lib/webri/generators/newfish/template/file.rhtml new file mode 100644 index 0000000..61b7695 --- /dev/null +++ b/lib/webri/generators/newfish/template/file.rhtml @@ -0,0 +1,156 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> + + <title>File: <%= file.base_name %> [<%= h title %>]</title> + + <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> + + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> + + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> +</head> + +<body class="file"> <!-- .file-popup is no more --> +<div id="main"> + + <div class="head"> + <h1> + <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; + <a href="<%= rel_prefix %>/index.html"><%= h title %></a>&nbsp; + <a href="/"><%= file.base_name %></a> + </h1> + </div> + + <div id="metadata"> + <div id="file-stats-section" class="section"> + <h3 class="section-header">File Stats</h3> + <dl> + <dt class="modified-date">Last Modified</dt> + <dd class="modified-date"><%= file.last_modified %></dd> + + <% if !file.requires.empty? %> + <dt class="requires">Requires</dt> + <dd class="requires"> + <ul> + <% file.requires.each do |require| %> + <li><%= require.name %></li> + <% end %> + </ul> + </dd> + <% end %> + + <% if options.webcvs %> + <dt class="scs-url">Trac URL</dt> + <dd class="scs-url"><a target="_top" + href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> + <% end %> + </dl> + </div> + + <div id="project-metadata"> + <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> + <% unless simple_files.empty? then %> + <div id="fileindex-section" class="section project-section"> + <h3 class="section-header">Information</h3> + <ul> + <% simple_files.each do |f| %> + <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> + <% end %> + </ul> + </div> + <% end %> + + <div id="classindex-section" class="section project-section"> + <h3 class="section-header">Class Index + <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" + height="16" width="16" alt="[+]" + title="show/hide quicksearch" /></span></h3> + <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> + <fieldset> + <legend>Quicksearch</legend> + <input type="text" name="quicksearch" value="" + class="quicksearch-field" /> + </fieldset> + </form> + + <ul class="link-list"> + <% classes_salient.each do |index_klass| %> + <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> + <% end %> + </ul> + <div id="no-class-search-results" style="display: none;">No matching classes.</div> + </div> + + <!-- METHODS --> + <div id="methodindex-section" class="section project-section"> + <h3 class="section-header">Method Index</h3> + <ul> + <% RDoc::TopLevel.all_classes_and_modules.map do |mod| + mod.method_list + end.flatten.sort.each do |method| %> + <li class="method" style="clear: both;"> + <span class="method-parent-aside"><%= method.parent.full_name %></span> + <a href="<%= method.path %>"><%= method.pretty_name %></a> + </li> + <% end %> + </ul> + </div> + </div> + + <div id="validator-badges"> + <% if $DEBUG_RDOC %> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> + </div> + <% end %> + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> + Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> + <br/><br/> + </div> + </div> + + <!-- .file-popup was wrapped: + <div id="documentation"> + <% if file.comment %> + <div class="description"> + ... file.description ... + </div> + <% end %> + </div> + So maybe that css is no longer needed. + --> + + <div id="documentation"> + <%= file.description %> + </div> + +</div> +</body> +</html> + diff --git a/lib/webri/generators/newfish/template/index.rhtml b/lib/webri/generators/newfish/template/index.rhtml new file mode 100644 index 0000000..0a20281 --- /dev/null +++ b/lib/webri/generators/newfish/template/index.rhtml @@ -0,0 +1,153 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" + "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> + + <title><%= h title %></title> + + <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> + + <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> + + <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> + <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> + <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> + <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> +</head> +<body class="indexpage"> +<div id="main"> + + <% $stderr.sync = true %> + <div class="head"> + <h1> + <img src="assets/img/project.png" align="absmiddle">&nbsp; + <a href="index.html"><%= h title %></a> + </h1> + </div> + + <div id="metadata"> + <div id="project-metadata"> + + <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> + <% unless simple_files.empty? then %> + <div id="fileindex-section" class="section project-section"> + <h3 class="section-header">Information</h3> + <ul> + <% simple_files.each do |f| %> + <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> + <% end %> + </ul> + </div> + <% end %> + + <div id="classindex-section" class="section project-section"> + <h3 class="section-header">Class Index + <span class="search-toggle"><img src="assets/img/find.png" + height="16" width="16" alt="[+]" + title="show/hide quicksearch" /></span></h3> + <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> + <fieldset> + <legend>Quicksearch</legend> + <input type="text" name="quicksearch" value="" + class="quicksearch-field" /> + </fieldset> + </form> + + <ul class="link-list"> + <% classes_salient.each do |index_klass| %> + <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> + <% end %> + </ul> + <div id="no-class-search-results" style="display: none;">No matching classes.</div> + </div> + + <!-- METHODS --> + <div id="methodindex-section" class="section project-section"> + <h3 class="section-header">Method Index</h3> + <ul> + <% RDoc::TopLevel.all_classes_and_modules.map do |mod| + mod.method_list + end.flatten.sort.each do |method| %> + <li class="method" style="clear: both;"> + <span class="method-parent-aside"><%= method.parent.full_name %></span> + <a href="<%= method.path %>"><%= method.pretty_name %></a> + </li> + <% end %> + </ul> + </div> + + </div> + + <div id="validator-badges"> + <% if $DEBUG_RDOC %> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="assets/img/bug.png" alt="[Debug]" height="16" width="16" /> + </div> + <% end %> + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> + Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> + <br/><br/> + </div> + </div> + +<!-- + <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> + <% unless simple_files.empty? then %> + <h2>Files</h2> + <ul> + <% simple_files.sort.each do |file| %> + <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> + <% end %> + </ul> + <% end %> + + <h2>Classes/Modules</h2> + <ul> + <% classes_salient.each do |klass| %> + <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> + <% end %> + </ul> + + <h2>Methods</h2> + <ul> + <% RDoc::TopLevel.all_classes_and_modules.map do |mod| + mod.method_list + end.flatten.sort.each do |method| %> + <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> + <% end %> + </ul> +--> + + <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> + <div id="documentation"> + <%= main_page.description %> + </div> + <% else %> + <p>This is the API documentation for '<%= h title %>'.</p> + <% end %> + +</div> +</body> +</html> +
razerbeans/webri
9d16d7849db331562e362c0281cb481cd3a3eef0
added syckle task to build samples
diff --git a/task/webri.syckle b/task/webri.syckle new file mode 100644 index 0000000..c1c2ea1 --- /dev/null +++ b/task/webri.syckle @@ -0,0 +1,51 @@ +--- +webri-sample-redfish: + service : WebRI + title : Fish Sampler + template : redfish + include : [demo/fish-sampler/README, demo/fish-sampler/lib] + main : demo/fish-sampler/README + output : site/samples/redfish + extra : ~ + active : true + +webri-sample-blackfish: + service : WebRI + title : Fish Sampler + template : blackfish + include : [demo/fish-sampler/README, demo/fish-sampler/lib] + main : demo/fish-sampler/README + output : site/samples/blackfish + extra : ~ + active : true + +webri-sample-longfish: + service : WebRI + title : Fish Sampler + template : longfish + include : [demo/fish-sampler/README, demo/fish-sampler/lib] + main : demo/fish-sampler/README + output : site/samples/longfish + extra : ~ + active : true + +webri-sample-onefish: + service : WebRI + title : Fish Sampler + template : onefish + include : [demo/fish-sampler/README, demo/fish-sampler/lib] + main : demo/fish-sampler/README + output : site/samples/onefish + extra : ~ + active : true + +webri-sample-twofish: + service : WebRI + title : Fish Sampler + template : twofish + include : [demo/fish-sampler/README, demo/fish-sampler/lib] + main : demo/fish-sampler/README + output : site/samples/twofish + extra : ~ + active : true +
razerbeans/webri
617c32d9f1eaf43ef73948c2f3288bcdad33a0ea
fixed files_toplevel
diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index a66f5df..f43a74e 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,662 +1,662 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' require 'webri/extensions/times' require 'webri/extensions/fileutils' require 'webri/generators/abstract/metadata' require 'webri/generators/abstract/erbtemplate' # module WebRI # = Abstract Generator Base Class # class Generator PATH = Pathname.new(File.join(LOADPATH, 'webri', 'generators')) #include ERB::Util include Metadata # # C O N S T A N T S # #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. PATH_STATIC = PATH + 'abstract/static' # Common template directory. PATH_TEMPLATE = PATH + 'abstract/template' # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # TODO: Get from metadata -- use POM if available. def title options.title end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel - @files_toplevel + @files_toplevel ||= @files_rdoc.select { |f| f.parser == RDoc::Parser::Simple } end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. - def generate(toplevel_files) - @files_toplevel = toplevel_files.sort + def generate(files) + @files_rdoc = files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s show_from = PATH_STATIC.to_s.sub(PATH.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(PATH.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files_toplevel.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template @erb_template ||= ERBTemplate.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/longfish/generator.rb b/lib/webri/generators/longfish/generator.rb index 89057b4..f8b7700 100644 --- a/lib/webri/generators/longfish/generator.rb +++ b/lib/webri/generators/longfish/generator.rb @@ -1,80 +1,78 @@ require 'webri/generators/abstract' #require 'webri/components/subversion' require 'webri/components/github' -require 'webri/components/metadata' module WebRI # = Longfish Template # # The Longfish tempolate is based on John Long's design # of the ruby-lang.org website. It was built to supply # Ruby core and stadard documentation with an "offical" # look, but there's no reason you can't use it for your # project too, if you prefer it. # class Longfish < Generator #include Subversion include GitHub - include Metadata # def path @path ||= Pathname.new(__FILE__).parent end # def site_homepage metadata.homepage end # def site_community metadata.mailinglist || metadata.wiki end # def site_repository metadata.development end # def site_news metadata.blog end # def index_title @index_title ||= parse_index_header[0] end # def index_description @index_description ||= parse_index_header[1] end # TODO: Generalize for all generators (?) def parse_index_header if options.main_page && main_page = files_toplevel.find { |f| f.full_name == options.main_page } desc = main_page.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) title = md[1] desc = md.post_match else title = options.main_page end else title = options.title desc = "This is the API documentation for '#{options.title}'." end return title, desc end end end
razerbeans/webri
f925302853b5e3e33b788e5a9c702eef4825fb4a
renamed riserver directory to just server
diff --git a/bin/webri-server b/bin/webri-server index ec1a606..1d3f499 100755 --- a/bin/webri-server +++ b/bin/webri-server @@ -1,151 +1,151 @@ #!/usr/bin/env ruby # == Synopsis # # webri: Serve ri documentation via the Web # # == Usage # # webri [OPTIONS] ... [RI_DIR] # # OPTIONS: # # -h, --help # show help # # -o, --output OUTPUT_DIR # ouput static files to OUTPUT_DIR # # RI_DIR: # # The directory in which to find the ri files generate by RDoc. #require 'rdoc/usage' require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: webri [options] [ri-dir]" opts.on("-o", "--output DIR", "Output static files to this directory.") do |v| options[:output] = v end opts.on("-1", "--onepage", "Generate a single page document.") do |v| options[:onepage] = true end opts.on("-t", "--title TITLE", "Title to use on webpages.") do |v| options[:title] = v end opts.separator "" opts.separator "Location options (only apply if no ri-dir is given):" opts.on("--[no-]system", "Include documentation from Ruby's standard library.") do |v| options[:system] = v end opts.on("--[no-]site", "Include documentation from libraries installed in site locations.") do |v| options[:site] = v end opts.on("--[no-]gems", "Include documentation from Ruby's standard library.") do |v| options[:gems] = v end opts.on("--[no-]home", "Include documentation stored in ~/.rdoc. Defaults to true.") do |v| options[:home] = v end opts.on("--ruby", "Same as --system --no-site --no-gems --no-home.") do |v| options[:system] = true options[:site] = false options[:gems] = false options[:home] = false end opts.separator "" opts.separator "Common options:" opts.on_tail("-h", "--help", "Show this message") do puts opts exit end end.parse! #if ARGV.length != 1 # puts "Missing ri directory argument (try --help)" # exit 0 #end options[:library] = ARGV.shift # --- --- -require 'webri/ri_service' +require 'webri/server/ri_service' service = WebRI::RiService.new(options) if output = options[:output] if options[:onepage] # generate static pages require 'webri/generator1' wri = WebRI::GeneratorOne.new(service, :title=>options[:title]) wri.generate(output) else # generate static pages require 'webri/generator' wri = WebRI::Generator.new(service, :title=>options[:title]) wri.generate(output) end else # serve dynamically via WEBrick - require 'webri/server' + require 'webri/server/server' wri = WebRI::Server.new(service, :title=>options[:title]) #puts wri.to_html require 'webrick' include WEBrick p wri.directory + "/public" s = HTTPServer.new( :Port => 8888, :DocumentRoot => wri.directory + "/public" ) s.mount_proc("/"){ |req, res| path = req.path_info.sub(/^\//,'') if path == '' res.body = wri.index res['Content-Type'] = "text/html" else res.body = wri.lookup(path) res['Content-Type'] = "text/html" end } # s.mount_proc("/ri"){|req, res| # #key = File.basename(req.path_info) # #p key # res.body = wri.lookup(req) # res['Content-Type'] = "text/html" # } ## mount subdirectories s.mount("/assets", HTTPServlet::FileHandler, wri.directory + "/assets") #s.mount("/css", HTTPServlet::FileHandler, wri.directory + "/assets/css") #s.mount("/img", HTTPServlet::FileHandler, wri.directory + "/assets/img") trap("INT"){ s.shutdown } s.start end
razerbeans/webri
9ad261a78b731eb853a0f3d39675b5b849e5a6d0
renamed riserver directory to just server
diff --git a/lib/webri/server/generator1.rb b/lib/webri/server/generator1.rb index 523aff5..429a3ce 100644 --- a/lib/webri/server/generator1.rb +++ b/lib/webri/server/generator1.rb @@ -1,211 +1,211 @@ -require 'webri/riserver/server' +require 'webri/server/server' module WebRI # This is the static website generator which creates # a single page. # class GeneratorOne < Server # Reference to CGI Service #attr :cgi # Reference to RI Service #attr :service # Dir in which to store generated html attr :output # attr :html # def initialize(service, options={}) super(service, options) @html = "" #@cgi = {} #CGI.new('html4') #@service = service @directory_depth = 0 end # #def tree # #%[<iframe src="tree.html"></iframe>] # @tree ||= heirarchy.to_html_static #end =begin # def lookup(req) keyw = File.basename(req.path_info) if keyw keyw.sub!('-','#') html = service.info(keyw) #puts html #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}" else html = "<h1>ERROR</h1>" end return html end =end #def template_source # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) #end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # generate webpages def generate(output=".") @output = File.expand_path(output) @assets = {} # traverse the the hierarchy #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end generate_support_files end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name #file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') html << %[<h1>#{entry.full_name}</h1>] html << %[\n<div id="#{file}" class="slot module">\n] html << service.info(keyword) html << %[\n</div>\n] #html << %[<h1>Class Methods</h1>] cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot cmethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end #html << %[<h1>Instance Methods</h1>] imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |name| mname = "#{entry.full_name}##{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot imethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts file FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) index = render(template('index1')) #base = base.strip.chomp('</html>').strip.chomp('</body>').strip.chomp('</div>') #base = base + html #base = base + "</div>\n</body>\n</html>" write(File.join(output, 'webri.html'), index) #write(File.join(output, 'header.html'), page_header) #write(File.join(output, 'tree.html'), page_tree) #write(File.join(output, 'main.html'), page_main) # copy assets #dir = File.join(directory, 'assets') #FileUtils.cp_r(dir, output) end # def current_content @current_content end # def asset(name) @assets[name] ||= File.read(File.join(directory, 'assets', name)) end # def css asset('css/style1.css') end # def jquery '' # asset('js/jquery.js') end # def rijquery '' #asset('js/ri.jquery.js') end end #class Generator end #module WebRI diff --git a/lib/webri/server/server.rb b/lib/webri/server/server.rb index 77dcfca..190b381 100644 --- a/lib/webri/server/server.rb +++ b/lib/webri/server/server.rb @@ -1,352 +1,352 @@ require 'erb' require 'yaml' require 'cgi' -require 'webri/riserver/opesc' -require 'webri/riserver/heirarchy' +require 'webri/server/opesc' +require 'webri/server/heirarchy' module WebRI # Server class and base class for Generator. # class Server # Reference to CGI Service #attr :cgi # Reference to RI Service attr :service # Directory in which to store generated html files #attr :output # Title of docs to add to webpage header. attr :title # def initialize(service, options={}) #@cgi = {} #CGI.new('html4') @service = service @templates = {} @title = options[:title] end # Tile of documentation as given by commandline option # or a the namespace of the root entry of the heirarchy. def title @title ||= heirarchy.full_name end # def directory @directory ||= File.dirname(__FILE__) end # def heirarchy @heirarchy ||=( ns = Heirarchy.new(nil) service.names.each do |m| if m.index('#') type = :instance space, method = m.split('#') spaces = space.split('::').collect{|s| s.to_sym } method = method.to_sym elsif m.index('::') type = :class spaces = m.split('::').collect{|s| s.to_sym } if spaces.last.to_s =~ /^[a-z]/ method = spaces.pop else next # what to do about class/module ? end else next # what to do abot class/module ? end memo = ns spaces.each do |space| memo[space] ||= Heirarchy.new(space, memo) memo = memo[space] end if type == :class memo.class_methods << method else memo.instance_methods << method end end ns ) end # def tree #%[<iframe src="tree.html"></iframe>] @tree ||= generate_tree(heirarchy) #heirarchy.to_html end # generate html tree # def generate_tree(entry) markup = [] if entry.root? markup << %[<div class="root">] else path = WebRI.entry_to_path(entry.full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <span class="link" onClick="lookup_static(this, '#{path}');">#{entry.name}</span> ] markup << %[<div class="branch">] end markup << %[<ul>] cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |method| path = WebRI.entry_to_path(entry.full_name + ".#{method}") markup << %[ <li class="meta_leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |method| path = WebRI.entry_to_path(entry.full_name + "##{method}") markup << %[ <li class="leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end entry.subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << generate_tree(subspace) #subspace.to_html end markup << %[</ul>] if entry.root? markup << %[</div>] else markup << %[</div>] markup << %[</li>] end return markup.join("\n") end # def lookup(path) entry = WebRI.path_to_entry(path) if entry html = service.info(entry) html = autolink(html, entry) #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}<br/><br/>" else html = "<h1>ERROR</h1>" end return html end # Search for certain patterns within the HTML and subs in hyperlinks. # # Eg. # # <h2>Instance methods:</h2> # current_content, directory, generate, generate_recurse, generate_tree # def autolink(html, entry) link = entry.gsub('::','/') re = Regexp.new(Regexp.escape(entry), Regexp::MULTILINE) if md = re.match(html) title = %[<a class="link title" href="javascript: lookup_static(this, '#{link}.html');">#{md[0]}</a>] html[md.begin(0)...md.end(0)] = title end # class methods re = Regexp.new(Regexp.escape("<h2>Class methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/c-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end # instance methods re = Regexp.new(Regexp.escape("<h2>Instance methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/i-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end return html end # def template(name) @templates[name] ||= File.read(File.join(directory, 'templates', name + '.html')) end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # def render(source) template = ERB.new(source) template.result(binding) end # #def page_header # render(template('header')) #end # #def page_tree # render(template('tree')) #end # def index render(template('index')) end # #def page_main # render(template('main')) #end =begin # generate webpages def generate(output=".") @output = File.expand_path(output) # traverse the the hierarchy generate_support_files #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name + '.html' file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') write(file, service.info(keyword)) #File.open(file, 'w') { |f| f << service.info(keyword) } #to_html } entry.class_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}--#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.instance_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}-#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts mfile File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) # generate index file file = File.join(output, 'index.html') File.open(file, 'w') { |f| f << to_html } # copy css file dir = File.join(directory,'public','css') FileUtils.cp_r(dir, output) # copy images dir = File.join(directory,'public','img') FileUtils.cp_r(dir, output) # copy scripts dir = File.join(directory,'public','js') FileUtils.cp_r(dir, output) end =end # def current_content @current_content end # def esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end # def self.esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end end #class Engine end #module WebRI
razerbeans/webri
95f1f6015de2b5ccda713f098c5b72d145e75fbb
timedelta changes, single point on path entry and css tweaks
diff --git a/.gitignore b/.gitignore index 0407676..f5ccc3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,11 @@ MANIFEST .cache log pkg demo/fish-sampler/doc doc/rdoc doc/ri doc/webri doc/webri.html +site/samples work/sandbox diff --git a/lib/webri/components/abstract.rb b/lib/webri/components/abstract.rb index e9499a1..95901ce 100644 --- a/lib/webri/components/abstract.rb +++ b/lib/webri/components/abstract.rb @@ -1,114 +1,111 @@ module WebRI # = Abstract Generator Component # class Component + PATH = Pathname.new(File.join(LOADPATH, 'webri', 'components')) + # attr :generator # New component instance. Components require the generator # they are augmenting. def initialize(generator) @generator = generator initialize_methods end - # Path to the component. This should be defined in the - # subclass as: - # - # def path - # @path ||= Pathname.new(__FILE__).parent - # end - # - def path - raise "Must be implemented by subclass!" - end - # Subcomponents use this to setup template provisions. # # def initialize_methods # provide :svninfo # end # # See the #provide method. def initialize_methods end # This is the method that is called by the generator, # allowing the component in turn to generate the # files it needs. By default this copies the components # <tt>static</tt> directory. def generate generate_static end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s - show_from = path_static.to_s.sub(path.parent.to_s+'/', '') + show_from = path_static.to_s.sub(PATH.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}:" fileutils.cp_r from, dest, :preserve => true end # def method_missing(s, *a, &b) generator.__send__(s,*a,&b) end # def path_static - path + 'static' + PATH + "#{name}/static" + end + + # + + def name + self.class.name.split('::').last.downcase end # Provide a method interface(s) to the generator. This extends # the generator's context with component methods. Since # ERB templates are rendering in the generator scope, this # is useful when a component needs to provide method access # to templates. def provision(method, &block) if block generator.provision(method, &block) else generator.provision(method) do |*a, &b| __send__(method, *a, &b) end end end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index 7b82b8e..a66f5df 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,659 +1,662 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' +require 'webri/extensions/times' require 'webri/extensions/fileutils' -require 'webri/generators/abstract/timedelta' +require 'webri/generators/abstract/metadata' require 'webri/generators/abstract/erbtemplate' # module WebRI # = Abstract Generator Base Class # class Generator + PATH = Pathname.new(File.join(LOADPATH, 'webri', 'generators')) + #include ERB::Util - include TimeDelta + include Metadata # # C O N S T A N T S # #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. - PATH_STATIC = Pathname.new(LOADPATH + '/webri/generators/abstract/static') + PATH_STATIC = PATH + 'abstract/static' # Common template directory. - PATH_TEMPLATE = Pathname.new(LOADPATH + '/webri/generators/abstract/template') + PATH_TEMPLATE = PATH + 'abstract/template' # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # TODO: Get from metadata -- use POM if available. def title options.title end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(toplevel_files) @files_toplevel = toplevel_files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s - show_from = PATH_STATIC.to_s.sub(LOADPATH.to_s+'/','') + show_from = PATH_STATIC.to_s.sub(PATH.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s - show_from = path_static.to_s.sub(path.parent.to_s+'/', '') + show_from = path_static.to_s.sub(PATH.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files_toplevel.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template @erb_template ||= ERBTemplate.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/abstract/metadata.rb b/lib/webri/generators/abstract/metadata.rb index 913d118..d05a10c 100644 --- a/lib/webri/generators/abstract/metadata.rb +++ b/lib/webri/generators/abstract/metadata.rb @@ -1,60 +1,61 @@ require 'webri/components/abstract' require 'ostruct' module WebRI # Metadata mixin, needs #path_base. # module Metadata # def metadata @metadata ||= get_metadata end # def get_metadata data = OpenStruct.new begin require 'pom/metadata' pom = POM::Metadata.load(path_base) raise LoadError unless pom.name data.title = pom.title data.version = pom.version - data.subtitle = pom.subtitle + data.subtitle = nil #pom.subtitle data.homepage = pom.homepage data.development = pom.development data.mailinglist = pom.mailinglist data.forum = pom.forum data.wiki = pom.wiki data.blog = pom.blog data.copyright = pom.copyright rescue LoadError if file = Dir[path_base + '*.gemspec'].first gem = YAML.load(file) data.title = gem.title data.version = gem.version data.subtitle = nil date.homepage = gem.homepage data.mailinglist = gem.email date.development = nil # TODO: how to improve? data.forum = nil data.wiki = nil data.blog = nil data.copyright = nil else + puts "No Metadata!" # TODO: we may be able to develop some other hueristics here, but for now, nope. end end return data end # def scm Dir[File.join(path_base.to_s,"{.svn,.git}")].first end end end diff --git a/lib/webri/generators/abstract/timedelta.rb b/lib/webri/generators/abstract/timedelta.rb index bd56ee5..fe017a2 100644 --- a/lib/webri/generators/abstract/timedelta.rb +++ b/lib/webri/generators/abstract/timedelta.rb @@ -1,114 +1,114 @@ module WebRI # module TimeDelta MINUTES = 60 HOURS = 60 * MINUTES DAYS = 24 * HOURS WEEKS = 7 * DAYS MONTHS = 30 * DAYS YEARS = 365.25 * DAYS # Return a string describing the amount of time in the given number of # seconds in terms a human can understand easily. - def time_delta_string( seconds ) + def time_delta_string(seconds) return 'less than a minute' if seconds < MINUTES return (seconds / MINUTES).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < (50 * MINUTES) return 'about one hour' if seconds < (90 * MINUTES) return (seconds / HOURS).to_s + ' hours' if seconds < (18 * HOURS) return 'one day' if seconds < DAYS return 'about one day' if seconds < (2 * DAYS) return (seconds / DAYS).to_s + ' days' if seconds < WEEKS return 'about one week' if seconds < (2 * WEEKS) return (seconds / WEEKS).to_s + ' weeks' if seconds < (3 * MONTHS) return (seconds / MONTHS).to_s + ' months' if seconds < YEARS return (seconds / YEARS).to_s + ' years' end end end =begin # Extend Numeric with time constants class Numeric # :nodoc: # Time constants module TimeConstantMethods # :nodoc: # Number of seconds (returns receiver unmodified) def seconds return self end alias_method :second, :seconds # Returns number of seconds in <receiver> minutes def minutes return self * 60 end alias_method :minute, :minutes # Returns the number of seconds in <receiver> hours def hours return self * 60.minutes end alias_method :hour, :hours # Returns the number of seconds in <receiver> days def days return self * 24.hours end alias_method :day, :days # Return the number of seconds in <receiver> weeks def weeks return self * 7.days end alias_method :week, :weeks # Returns the number of seconds in <receiver> fortnights def fortnights return self * 2.weeks end alias_method :fortnight, :fortnights # Returns the number of seconds in <receiver> months (approximate) def months return self * 30.days end alias_method :month, :months # Returns the number of seconds in <receiver> years (approximate) def years return (self * 365.25.days).to_i end alias_method :year, :years # Returns the Time <receiver> number of seconds before the # specified +time+. E.g., 2.hours.before( header.expiration ) def before( time ) return time - self end # Returns the Time <receiver> number of seconds ago. (e.g., # expiration > 2.hours.ago ) def ago return self.before( ::Time.now ) end # Returns the Time <receiver> number of seconds after the given +time+. # E.g., 10.minutes.after( header.expiration ) def after( time ) return time + self end # Reads best without arguments: 10.minutes.from_now def from_now return self.after( ::Time.now ) end end # module TimeConstantMethods include TimeConstantMethods end =end diff --git a/lib/webri/generators/redfish/static/assets/css/rdoc.css b/lib/webri/generators/redfish/static/assets/css/rdoc.css index 81ba389..717a2ff 100644 --- a/lib/webri/generators/redfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/redfish/static/assets/css/rdoc.css @@ -1,831 +1,834 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; padding: 0 40px 15px 40px; } #main { width: 1024px; margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } img { border: none; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: #FF226C; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } pre { padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-bottom: 0px solid #aaa; border-left: 0px solid #aaa; border-right: 0px solid #aaa; padding: 10px 10px; margin: 0 8px -0.5em 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; background: url(images/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; background: url(images/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; background: url(images/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; background: url(images/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; background: url(images/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: right; width: 320px; margin-top: 10px; } #documentation { margin: 0 360px 5em 1em; min-width: 340px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } .method-parent-aside { float: right; font-size: 0.7em; font-weight: bold; padding: 0 20px; color: #999; } /* @end */ /* @group Documentation Section */ #documentation h1 { margin: 10px 0 10px 0; - padding: 0.5em 0.5em; - background-color: #dedede; - border: 1px solid #bbb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; + padding: 0.5em 0.1em 0.25em 0.1em; + border-bottom: 0px solid #bbb; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; +} + +#documentation ul { + margin-top: 10px; } #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; - padding: 0.75em 0.5em; - background-color: #dedede; + padding: 0.75em 0.5em 0.25em 0.5em; + /* background-color: #dedede; */ color: #333; font-size: 150%; - border: 1px solid #bbb; + border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { - margin: 1em 0 2em; + margin: 1em 0 2em 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ /* .file #documentation { margin: 0; } */ .file #metadata { float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } - +/* .file h2 { margin-top: 2em; - padding: 0.75em 0.5em; - background-color: #dedede; + padding: 0.75em 0.5em 0.25em 0.1em; color: #333; font-size: 120%; - border: 1px solid #bbb; + border-bottom: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } +*/ /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ diff --git a/lib/webri/generators/redfish/template/file.rhtml b/lib/webri/generators/redfish/template/file.rhtml index 06516c0..bf5ac7b 100644 --- a/lib/webri/generators/redfish/template/file.rhtml +++ b/lib/webri/generators/redfish/template/file.rhtml @@ -1,141 +1,156 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= options.title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); </script> </head> <body class="file"> <!-- .file-popup is no more --> <div id="main"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> <div id="file-stats-section" class="section"> <h3 class="section-header">File Stats</h3> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if !file.requires.empty? %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> + + <!-- METHODS --> + <div id="methodindex-section" class="section project-section"> + <h3 class="section-header">Method Index</h3> + <ul> + <% RDoc::TopLevel.all_classes_and_modules.map do |mod| + mod.method_list + end.flatten.sort.each do |method| %> + <li class="method" style="clear: both;"> + <span class="method-parent-aside"><%= method.parent.full_name %></span> + <a href="<%= method.path %>"><%= method.pretty_name %></a> + </li> + <% end %> + </ul> + </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right; margin-right: 5px;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> <div style="float: right; margin-right: 5px;"> <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> </div> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> </div> </div> <!-- .file-popup was wrapped: <div id="documentation"> <% if file.comment %> <div class="description"> ... file.description ... </div> <% end %> </div> So maybe that css is no longer needed. --> <div id="documentation"> <%= file.description %> </div> </div> </body> </html> diff --git a/lib/webri/generators/twofish/generator.rb b/lib/webri/generators/twofish/generator.rb index 3e08584..46085a8 100644 --- a/lib/webri/generators/twofish/generator.rb +++ b/lib/webri/generators/twofish/generator.rb @@ -1,123 +1,123 @@ require 'webri/generators/abstract' require 'webri/components/subversion' module WebRI # = Twofish Template # # The Twofish template is a two pane layout, providing # a navigation pane on the left and a document pane to # the right. The navigation pane presents a collapsable # namespace tree which updates the document pane, an iframe, # via targeted a href links. # class Twofish < Generator include Subversion # - def path - @path ||= Pathname.new(__FILE__).parent - end + #def path + # @path ||= Pathname.new(__FILE__).parent + #end # - def initialize_methods - provision :html_tree - end + #def initialize_methods + # provision :html_tree + #end # #def generate_template # super #end #<ul> # <li class="trigger"> # <img src="assets/img/class.png" onClick="showBranch(this);"/> # # <span class="link" path="__path__" onClick="lookup_static(this);">__entry.name__</span> # # <div class="branch"> # <ul> # <li class="meta_leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # <ul> # <li class="leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # </li> #</ul> # def html_tree #%[<iframe src="tree.html"></iframe>] @html_tree ||= ( %[<div class="root">] + generate_html_tree(classes_toplevel) + %[</div>] #heirarchy) #heirarchy.to_html ) end # generate html tree # def generate_html_tree(classes) markup = ["<ul>"] classes = classes.sort{ |a,b| a.full_name <=> b.full_name } classes.each do |entry| path = entry.path #WebRI.entry_to_path(entry.full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <a class="link" href="#{path}" target="main">#{entry.name}</a> ] markup << %[<div class="branch">] markup << %[<ul>] cmethods, imethods = *entry.method_list.partition{ |m| m.singleton } cmethods = cmethods.sort{ |a,b| a.name <=> b.name } cmethods.each do |method| path = method.path #entry.full_name + ".#{method.name}" #WebRI.entry_to_path(entry.full_name + ".#{method}") markup << %[ <li class="meta_leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end imethods = imethods.sort{ |a,b| a.name <=> b.name } imethods.each do |method| path = method.path #WebRI.entry_to_path(entry.full_name + "##{method}") markup << %[ <li class="leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end #entry.classes.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << generate_html_tree(entry.classes_and_modules) if entry.classes #end markup << %[</ul>] #if entry.root? # markup << %[</div>] #else markup << %[</div>] markup << %[</li>] #end end markup << "</ul>" return markup.join("\n") end end end#module WebRI diff --git a/lib/webri/generators/twofish/static/assets/css/rdoc.css b/lib/webri/generators/twofish/static/assets/css/rdoc.css index d9fdf50..ab7ffef 100644 --- a/lib/webri/generators/twofish/static/assets/css/rdoc.css +++ b/lib/webri/generators/twofish/static/assets/css/rdoc.css @@ -1,576 +1,581 @@ /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 0px solid #aaa; padding: 0 10px; margin: 0 8px 5px 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, */ /* body div.file, body div.class, body div.module { padding: 10px; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; - background: url(images/bullet_black.png) no-repeat left 4px; + background: url(../img/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; - background: url(images/method.png) no-repeat left 2px; + background: url(../img/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; - background: url(images/module.png) no-repeat left 2px; + background: url(../img/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; - background: url(images/class.png) no-repeat left 2px; + background: url(../img/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; - background: url(images/file.png) no-repeat left 2px; + background: url(../img/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: left; width: 320px; margin-top: 10px; } #documentation { margin: 0; padding: 10px 20px; min-width: 340px; background: white; } /* .file #metadata { margin: 0.8em; } */ /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } /* @end */ /* @group Documentation Section */ #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 150%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ .file #metadata, .file-popup #metadata { float: right; + padding: 0.75em; margin-right: 20px; + background-color: white; + border: 1px solid #ccc; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; } .file-popup dl { font-size: 80%; padding: 0.75em; color: #333; background: url(../img/fade.png) repeat-x #dedede; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } .file h2 { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 120%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ diff --git a/lib/webri/generators/twofish/template/file.rhtml b/lib/webri/generators/twofish/template/file.rhtml index 0164bde..5a5e0cc 100644 --- a/lib/webri/generators/twofish/template/file.rhtml +++ b/lib/webri/generators/twofish/template/file.rhtml @@ -1,135 +1,137 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/reset.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/style.css" /> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> </head> <% if file.parser == RDoc::Parser::Simple %> <body> <div class="file"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> +<!-- <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% modules_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <% if $DEBUG_RDOC %> <div id="debugging-toggle"><img src="<%= rel_prefix %>/assets/img/bug.png" alt="toggle debugging" height="16" width="16" /></div> <% end %> </div> <div id="validator-badges"> Generated with <a href="http://github.com/proutils/rdazzle">Razzle Dazzle Redfish</a><br/><br/> <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> +--> <div id="documentation"> <%= file.description %> </div> </div> </body> <% else %> <body> <div class="file"> <div id="metadata"> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if file.requires %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="documentation"> <% if file.comment %> <div class="description"> <%= file.description %> </div> <% end %> </div> </div> </body> <% end %> </html> diff --git a/lib/webri/generators/twofish/template/index.rhtml b/lib/webri/generators/twofish/template/index.rhtml index 5c5a2c7..4fc7926 100644 --- a/lib/webri/generators/twofish/template/index.rhtml +++ b/lib/webri/generators/twofish/template/index.rhtml @@ -1,71 +1,71 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title><%= h title %> - WebRI</title> <meta http-equiv="Content-Type" content="text/html; charset=<%= options.charset %>" /> <link rel="icon" href="assets/img/ruby_logo.png" type="image/x-icon"> <link type="text/css" media="screen" rel="stylesheet" href="assets/css/reset.css" /> <link type="text/css" media="screen" rel="stylesheet" href="assets/css/style.css" /> <link type="text/css" media="screen" rel="stylesheet" href="assets/css/rdoc.css" /> <script type="text/javascript" src="assets/js/jquery.js"></script> <script type="text/javascript" src="assets/js/jquery.jam.js"></script> <script type="text/javascript" src="assets/js/jquery.ri.js"></script> <script type="text/javascript" src="assets/js/thickbox.js"></script> <script type="text/javascript" src="assets/js/quicksearch.js"></script> <script type="text/javascript" src="assets/js/darkfish.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); </script> </head> <body> <div id="screen"> <table cellspacing="15px" style="width: 100%; height: 100%; position: relative;"> <tbody style="height: 70%;"> <tr> <td colspan="2" style="height: 110px;"> <div id="header"> <img src="assets/img/ruby_logo.png" align="left"/> <h1><%= h title %></h1> <h2>&nbsp; <%= copyright %></a></h2> </div> </td> </tr> <tr> - <td style="width: 200px; height: 100%; border: 1px solid #ccc; padding: 10px; background: white;"> + <td style="width: 250px; height: 100%; border: 1px solid #ccc; padding: 10px; background: white;"> <div id="tree"> <%= html_tree %> </div> </td> <td style="height: 100%;"> <iframe id="main" name="main" src="files/README.html" scrolling="auto"> </iframe> </td> </tr> <tr> <td colspan="2" style="height: 40px;"> <div id="footer"> <div class="small ad" style="float: right; width: 200px;"> </div> Generated with <a href="http://github.com/proutils/webri">WebRI TwoFish</a> &nbsp; <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </td> </tr> </tbody> </table> </div> </body> </html> diff --git a/plug/syckle/services/webri.rb b/plug/syckle/services/webri.rb index f90a695..347154f 100644 --- a/plug/syckle/services/webri.rb +++ b/plug/syckle/services/webri.rb @@ -1,263 +1,269 @@ module Syckle::Plugins # WebRI documentation plugin generates WebRI-based RDocs for # your project. # # By default it generates the documentaiton at doc/webri, # unless an 'webri' directory exists in the project's root # directory, in which case the documentation will be # stored there (unless an alternative is specified). # # This plugin provides the following cycle-phases: # # main:document - generate rdocs # main:reset - mark rdocs out-of-date # main:clean - remove rdocs # # site:document - generate rdocs # site:reset - mark rdocs out-of-date # site:clean - remove rdocs # # WebRI service will be available automatically if the project # has a +doc/webri+ or +webri+ directory. # class WebRI < Service #Plugin ## # Generate rdocs in main cycle. # :method: main_document cycle :main, :document cycle :main, :reset cycle :main, :clean cycle :site, :document cycle :site, :reset cycle :site, :clean # TODO: IMPROVE #available do |project| # !project.metadata.loadpath.empty? #end # RDoc can run automatically if the project has # a +doc/rdoc+ directory. autorun do |project| project.root.glob('doc/webri,webri').first end # Default location to store rdoc documentation files. DEFAULT_OUTPUT = "doc/webri" # Locations to check for existance in deciding where to store rdoc documentation. DEFAULT_OUTPUT_MATCH = "{doc/webri,webri}" # Default main file. DEFAULT_MAIN = "README{,.*}" # Default rdoc template to use. DEFAULT_TEMPLATE = "redfish" # Deafult extra options to add to rdoc call. DEFAULT_EXTRA = '' private # Setup default attribute values. def initialize_defaults @title = metadata.title @files = metadata.loadpath + ['[A-Z]*', 'bin'] # DEFAULT_FILES @output = Dir[DEFAULT_OUTPUT_MATCH].first || DEFAULT_OUTPUT @extra = DEFAULT_EXTRA @main = Dir[DEFAULT_MAIN].first @template = ENV['RDOC_TEMPLATE'] || DEFAULT_TEMPLATE end public # Title of documents. Defaults to general metadata title field. attr_accessor :title # Where to save rdoc files (doc/rdoc). attr_accessor :output # Template to use (defaults to ENV['RDOC_TEMPLATE'] or 'darkfish') attr_accessor :template # Main file. This can be a file pattern. (README{,.*}) attr_accessor :main # Which files to document. attr_accessor :files # Alias for +files+. alias_accessor :include, :files # Paths to specifically exclude. attr_accessor :exclude # File patterns to ignore. #attr_accessor :ignore # Ad file html snippet to add to html rdocs. #attr_accessor :adfile # Additional options passed to the rdoc command. attr_accessor :extra # Generate Rdoc documentation. Settings are the # same as the rdoc command's option, with two # exceptions: +inline+ for +inline-source+ and # +output+ for +op+. # def document(options=nil) options ||= {} + # TODO: get rid of options (?) originally they were used for commanline overrides, + # but that's not being used anymore, and it's probably better that way. title = options['title'] || self.title output = options['output'] || self.output main = options['main'] || self.main template = options['template'] || self.template files = options['files'] || self.files exclude = options['exclude'] || self.exclude #adfile = options['adfile'] || self.adfile extra = options['extra'] || self.extra + root = options['root'] || self.root # NOTE: Due to a bug in RDOC this needs to be done so that # alternate templates can be used. begin gem('rdoc') #gem(templib || template) rescue LoadError end require 'rdoc/rdoc' + #output = File.expand_path(output) + # you can specify more than one possibility, first match wins - adfile = [adfile].flatten.compact.find do |f| - File.exist?(f) - end + #adfile = [adfile].flatten.compact.find do |f| + # File.exist?(f) + #end main = Dir.glob(main, File::FNM_CASEFOLD).first include_files = files.to_list.uniq exclude_files = exclude.to_list.uniq if mfile = project.manifest_file exclude_files << mfile.basename.to_s # TODO: I think base name should retun a string? end filelist = amass(include_files, exclude_files) filelist = filelist.select{ |fname| File.file?(fname) } if outofdate?(output, *filelist) or force? status "Generating #{output}" #target_main = Dir.glob(target['main'].to_s, File::FNM_CASEFOLD).first #target_main = File.expand_path(target_main) if target_main #target_output = File.expand_path(File.join(output, subdir)) #target_output = File.join(output, subdir) argv = [] argv.concat(extra.split(/\s+/)) argv.concat ['--op', output] argv.concat ['--main', main] if main argv.concat ['--template', template] if template argv.concat ['--title', title] if title exclude_files.each do |file| argv.concat ['--exclude', file] end argv = argv + filelist #include_files rdoc_target(output, include_files, argv) #rdoc_insert_ads(output, adfile) touch(output) else - status "RDocs are current (#{output})." + status "WebRI RDocs are current (#{output})." end end # Reset output directory, marking it as out-of-date. def reset if File.directory?(output) File.utime(0,0,output) report "reset #{output}" #unless dryrun? end end # Remove rdocs products. def clean if File.directory?(output) rm_r(output) status "removed #{output}" #unless dryrun? end end private # Generate rdocs for input targets. # # TODO: Use RDoc programmatically rather than via shell. # def rdoc_target(output, input, argv=[]) #if outofdate?(output, *input) or force? rm_r(output) if exist?(output) and safe?(output) # remove old rdocs #rdocopt['op'] = output #if template == 'hanna' # cmd = "hanna #{extra} " + [input, rdocopt].to_console #else # cmd = "rdoc #{extra} " + [input, rdocopt].to_console #end #argv = ("#{extra}" + [input, rdocopt].to_console).split(/\s+/) if verbose? or dryrun? puts "webri " + argv.join(" ") #sh(cmd) #shell(cmd) else - puts "webri " + argv.join(" ") if trace? - rdoc = ::RDoc::RDoc.new - rdoc.document(argv) + cmd = "webri " + argv.join(" ") + puts cmd #if trace? + #rdoc = ::RDoc::RDoc.new + #rdoc.document(argv) #silently do - # sh(cmd) #shell(cmd) + sh(cmd) #shell(cmd) #end end #else # puts "RDocs are current -- #{output}" #end end =begin (let webri handle this if desired) # Insert an ad into rdocs, if exists. # # Note that this code is needs work, as is it # was designed to work with an old version of RDoc. # def rdoc_insert_ads(site, adfile) return if dryrun? return unless adfile && File.file?(adfile) adtext = File.read(adfile) #puts dirs = Dir.glob(File.join(site,'*/')) dirs.each do |dir| files = Dir.glob(File.join(dir, '**/*.html')) files.each do |file| html = File.read(file) bodi = html.index('<body>') next unless bodi html[bodi + 7] = "\n" + adtext File.write(file, html) unless dryrun? end end end =end end end diff --git a/site/assets/img/tiger_logo.png b/site/assets/img/tiger_logo.png deleted file mode 100644 index 60d0fbb..0000000 Binary files a/site/assets/img/tiger_logo.png and /dev/null differ
razerbeans/webri
97bb17d9dea08f0f32e091895014df1596dad4e4
fix minute in times.rb [bug]
diff --git a/lib/webri/generators/abstract/erbtemplate.rb b/lib/webri/generators/abstract/erbtemplate.rb index 0b562ad..6893f28 100644 --- a/lib/webri/generators/abstract/erbtemplate.rb +++ b/lib/webri/generators/abstract/erbtemplate.rb @@ -1,118 +1,117 @@ require 'erb' module WebRI # ERBTemplate is used by the generator to build # template files. It has access to all the # the <i>data methods</i> in the generator. class ERBTemplate include ERB::Util - include TimeDelta # New ERBTemplate instance. def initialize(generator, provisions) @generator = generator # add component provisions provisions.each do |name, block| (class << self; self; end).class_eval do define_method(name){ |*a,&b| block.call(*a,&b) } end end end # Render a template. def render(template_file, local_assigns={}) template_source = template_file.read erb = ERB.new(template_source, nil, '<>') erb.filename = template_file.to_s local_assigns.each do |key, val| (class << self; self; end).class_eval do define_method(key){ val } end end begin erb_binding = binding #eval code, b erb.result(erb_binding) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ template_file.to_s, err.message, eval("_erbout[-50,50]", erb_binding) ], err.backtrace end end # FIXME: this probably goes not need to double dispatch via generator def include_template(*a,&b) @generator.include_template(*a,&b) end def options ; @generator.options ; end def title ; @generator.title ; end def copyright ; @generator.copyright ; end def class_dir ; @generator.class_dir ; end def file_dir ; @generator.file_dir ; end #def all_classes_and_modules ; @generator.all_classes_and_modules ; end # classes and modules def classes ; @generator.classes ; end def classes_toplevel ; @generator.classes_toplevel ; end def classes_salient ; @generator.classes_salient ; end def classes_hash ; @generator.classes_hash ; end # just modules, no classes def modules ; @generator.modules ; end def modules_toplevel ; @generator.modulews_toplevel ; end def modules_salient ; @generator.modules_salient ; end def modules_hash ; @generator.modules_hash ; end # just classes w/o modules def types ; @generator.types ; end def types_toplevel ; @generator.types_toplevel ; end def types_salient ; @generator.types_salient ; end def types_hash ; @generator.types_hash ; end # def methods_all ; @generator.methods_all ; end # def files ; @generator.files ; end def files_toplevel ; @generator.files_toplevel ; end def files_hash ; @generator.files_hash ; end def find_class_named(*a,&b) ; @generator.find_class_named(*a,&b) ; end def find_module_named(*a,&b) ; @generator.find_module_named(*a,&b) ; end def find_type_named(*a,&b) ; @generator.find_type_named(*a,&b) ; end def find_file_named(*a,&b) ; @generator.find_file_named(*a,&b) ; end # Load and render the erb template with the given +template_name+ within # current context. Adds all +local_assigns+ to context def include_template(template_name, local_assigns={}) #source = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join #eval("#{source}; templatefile = path_template + template_name;eval_template(templatefile, binding)") template_file = @generator.__send__(:path_template) + template_name render(template_file, local_assigns) end # def method_missing(s, *a, &b) if @generator.respond_to?(s) @generator.__send__(s, *a, &b) end end end end
razerbeans/webri
86f3fc31563ed7f3cc9b52c3a34791de1aff9f4b
fix minute in times.rb [bug]
diff --git a/lib/webri/components/subversion.rb b/lib/webri/components/subversion.rb index 7d58eb1..657a327 100644 --- a/lib/webri/components/subversion.rb +++ b/lib/webri/components/subversion.rb @@ -1,65 +1,65 @@ require 'webri/components/abstract' module WebRI # class Subversion < Component # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :svninfo end # def svninfo(klass) @svninfo ||= {} @svninfo[klass] ||= get_svninfo(klass) end # Try to extract Subversion information out of the first constant whose value looks like # a subversion Id tag. If no matching constant is found, and empty hash is returned. def get_svninfo(klass) constants = klass.constants or return {} constants.find {|c| c.value =~ SVNID_PATTERN } or return {} filename, rev, date, time, committer = $~.captures commitdate = Time.parse( date + ' ' + time ) return { :filename => filename, :rev => Integer( rev ), :commitdate => commitdate, - :commitdelta => time_delta_string( Time.now.to_i - commitdate.to_i ), + :commitdelta => (Time.now.to_i - commitdate.to_i).time_delta_string, :committer => committer, } end # Subversion rev #SVNRev = %$Rev: 52 $ # Subversion ID #SVNId = %$Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $ # SVNID_PATTERN = / \$Id:\s (\S+)\s # filename (\d+)\s # rev (\d{4}-\d{2}-\d{2})\s # Date (YYYY-MM-DD) (\d{2}:\d{2}:\d{2}Z)\s # Time (HH:MM:SSZ) (\w+)\s # committer \$$ /x end end
razerbeans/webri
6ab655abc6e4d964b1ed21dc132f1e5847eb2910
fix minute in times.rb [bug]
diff --git a/lib/webri/extensions/times.rb b/lib/webri/extensions/times.rb new file mode 100644 index 0000000..a24792e --- /dev/null +++ b/lib/webri/extensions/times.rb @@ -0,0 +1,110 @@ +# Extend Numeric with time constants +class Numeric # :nodoc: + + # Time constants + # + # TODO: Use RichUnits instead (?) + # + module Times # :nodoc: + + MINUTES = 60 + HOURS = 60 * MINUTES + DAYS = 24 * HOURS + WEEKS = 7 * DAYS + MONTHS = 30 * DAYS + YEARS = 365.25 * DAYS + + # Number of seconds (returns receiver unmodified) + def seconds + return self + end + alias_method :second, :seconds + + # Returns number of seconds in <receiver> minutes + def minutes + MINUTES + end + alias_method :minute, :minutes + + # Returns the number of seconds in <receiver> hours + def hours + HOURS + end + alias_method :hour, :hours + + # Returns the number of seconds in <receiver> days + def days + DAYS + end + alias_method :day, :days + + # Return the number of seconds in <receiver> weeks + def weeks + WEEKS + end + alias_method :week, :weeks + + # Returns the number of seconds in <receiver> fortnights + def fortnights + return self * 2.weeks + end + alias_method :fortnight, :fortnights + + # Returns the number of seconds in <receiver> months (approximate) + def months + MONTHS + end + alias_method :month, :months + + # Returns the number of seconds in <receiver> years (approximate) + def years + YEARS #return (self * 365.25.days).to_i + end + alias_method :year, :years + + # Returns the Time <receiver> number of seconds before the + # specified +time+. E.g., 2.hours.before( header.expiration ) + def before( time ) + return time - self + end + + # Returns the Time <receiver> number of seconds ago. (e.g., + # expiration > 2.hours.ago ) + def ago + return self.before( ::Time.now ) + end + + # Returns the Time <receiver> number of seconds after the given +time+. + # E.g., 10.minutes.after( header.expiration ) + def after( time ) + return time + self + end + + # Reads best without arguments: 10.minutes.from_now + def from_now + return self.after( ::Time.now ) + end + + # Return a string describing the amount of time in the given number of + # seconds in terms a human can understand easily. + def time_delta_string + seconds = self + return 'less than a minute' if seconds < MINUTES + return (seconds / MINUTES).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < (50 * MINUTES) + return 'about one hour' if seconds < (90 * MINUTES) + return (seconds / HOURS).to_s + ' hours' if seconds < (18 * HOURS) + return 'one day' if seconds < DAYS + return 'about one day' if seconds < (2 * DAYS) + return (seconds / DAYS).to_s + ' days' if seconds < WEEKS + return 'about one week' if seconds < (2 * WEEKS) + return (seconds / WEEKS).to_s + ' weeks' if seconds < (3 * MONTHS) + return (seconds / MONTHS).to_s + ' months' if seconds < YEARS + return (seconds / YEARS).to_s + ' years' + end + + end # module TimeConstantMethods + + include Times +end + +
razerbeans/webri
6153d186ab7bb925ccf5c79a84f7cf1467b842a4
added onefish template
diff --git a/lib/webri.rb b/lib/webri.rb index ebfb538..bece65b 100644 --- a/lib/webri.rb +++ b/lib/webri.rb @@ -1,46 +1,46 @@ #$:.unshift File.dirname(__FILE__) begin require "rubygems" gem "rdoc", ">= 2.4.2" require "rdoc/rdoc" module WebRI LOADPATH = File.dirname(__FILE__) VERSION = "1.0.0" #:till: VERSION="<%= version %>" end require "rdoc/c_parser_fix" unless defined? $WEBRI_FIXED_RDOC_OPTIONS $WEBRI_FIXED_RDOC_OPTIONS = 1 class RDoc::Options #alias_method :rdoc_initialize, :initialize #def initialize # rdoc_initialize # @generator = RDoc::Generator::RDazzle #end alias_method :rdoc_parse, :parse #FIXME: look up templates dynamically def parse(argv) rdoc_parse(argv) - if %w{redfish twofish blackfish longfish}.include?(@template) + if %w{redfish twofish blackfish longfish onefish}.include?(@template) require "webri/generators/#{template}" @generator = WebRI.const_get(@template.capitalize) end end end end rescue Exception warn "WebRI requires RDoc v2.4.2 or greater." end diff --git a/lib/webri/generators/onefish.rb b/lib/webri/generators/onefish.rb new file mode 100644 index 0000000..01a6dd3 --- /dev/null +++ b/lib/webri/generators/onefish.rb @@ -0,0 +1 @@ +require 'webri/generators/onefish/generator' diff --git a/lib/webri/generators/onefish/generator.rb b/lib/webri/generators/onefish/generator.rb new file mode 100644 index 0000000..0720bf9 --- /dev/null +++ b/lib/webri/generators/onefish/generator.rb @@ -0,0 +1,59 @@ +require 'webri/generators/abstract' +#require 'webri/components/search' +#require 'webri/components/github' + +module WebRI + + # Onefishm as teh name suggests builds + # a single page. + # + class Onefish < WebRI::Generator + + def generate_files + end + + def generate_classes + end + + # + #def path + # @path ||= Pathname.new(__FILE__).parent + #end + + #def generate_template + # super + #end + +# # TODO: Does this belong here or in the quicksearch component? +# def each_letter_group(methods, &block) +# group = {:name => '', :methods => []} +# methods.sort{ |a, b| a.name <=> b.name }.each do |method| +# gname = group_name method.name +# if gname != group[:name] +# yield group unless group[:methods].size == 0 +# group = { +# :name => gname, +# :methods => [] +# } +# end +# group[:methods].push(method) +# end +# yield group unless group[:methods].size == 0 +# end + +# protected + +# ## + +# def group_name(name) +# if match = name.match(/^([a-z])/i) +# match[1].upcase +# else +# '#' +# end +# end + + end + +end + diff --git a/lib/webri/generators/onefish/template/context.rhtml b/lib/webri/generators/onefish/template/context.rhtml new file mode 100644 index 0000000..7ecfbb4 --- /dev/null +++ b/lib/webri/generators/onefish/template/context.rhtml @@ -0,0 +1,162 @@ +<div id="content"> + <% unless (desc = context.description).empty? %> + <div class="description"><%= desc %></div> + <% end %> + + <% unless context.requires.empty? %> + <div class="sectiontitle">Required Files</div> + <ul> + <% context.requires.each do |req| %> + <li><%= h req.name %></li> + <% end %> + </ul> + <% end %> + + <% sections = context.sections.select { |section| section.title } %> + <% unless sections.empty? %> + <div class="sectiontitle">Contents</div> + <ul> + <% sections.each do |section| %> + <li><a href="#<%= section.sequence %>"><%= h section.title %></a></li> + <% end %> + </ul> + <% end %> + + <% + list = context.method_list + unless options.show_all + list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } + end + %> + <% unless list.empty? %> + <div class="sectiontitle">Methods</div> + <% list.sort{ |a, b| a.name <=> b.name }.each do |method| %> + <a href="#<%= method.aref %>"><%= method.name %></a> + <% end %> + <% end %> + + <% unless context.includes.empty? %> + <div class="sectiontitle">Included Modules</div> + <ul> + <% context.includes.each do |inc| %> + <li> + <% unless String === inc.module %> + <a href="<%= context.aref_to inc.module.path %>"><%= h inc.module.full_name %></a> + <% else %> + <span><%= h inc.name %></span> + <% end %> + START:includes + </li> + <% end %> + </ul> + <% end %> + + <% sections.each do |section| %> + <div class="sectiontitle"><a name="<%= h section.sequence %>"><%= h section.title %></a></div> + <% unless (description = section.description).empty? %> + <div class="description"> + <%= description %> + </div> + <% end %> + <% end %> + + <% unless context.classes_and_modules.empty? %> + <div class="sectiontitle">Classes and Modules</div> + <ul> + <% (context.modules.sort + context.classes.sort).each do |mod| %> + <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= context.aref_to mod.path %>"><%= mod.full_name %></a></li> + <% end %> + </ul> + <% end %> + + <% unless context.constants.empty? %> + <div class="sectiontitle">Constants</div> + <table border='0' cellpadding='5'> + <% context.each_constant do |const| %> + <tr valign='top'> + <td class="attr-name"><%= h const.name %></td> + <td>=</td> + <td class="attr-value"><%= h const.value %></td> + </tr> + <% unless (description = const.description).empty? %> + <tr valign='top'> + <td>&nbsp;</td> + <td colspan="2" class="attr-desc"><%= description %></td> + </tr> + <% end %> + <% end %> + </table> + <% end %> + + <% unless context.attributes.empty? %> + <div class="sectiontitle">Attributes</div> + <table border='0' cellpadding='5'> + <% context.each_attribute do |attrib| %> + <tr valign='top'> + <td class='attr-rw'> + [<%= attrib.rw %>] + </td> + <td class='attr-name'><%= h attrib.name %></td> + <td class='attr-desc'><%= attrib.description.strip %></td> + </tr> + <% end %> + </table> + <% end %> + + <% context.methods_by_type.each do |type, visibilities| + next if visibilities.empty? + visibilities.each do |visibility, methods| + next if methods.empty? + next unless options.show_all || visibility == :public || visibility == :protected || methods.any? {|m| m.force_documentation } + %> + <div class="sectiontitle"><%= type.capitalize %> <%= visibility.to_s.capitalize %> methods</div> + <% methods.each do |method| %> + <div class="method"> + <div class="title"> + <% if method.call_seq %> + <a name="<%= method.aref %>"></a><b><%= method.call_seq.gsub(/->/, '&rarr;') %></b> + <% else %> + <a name="<%= method.aref %>"></a><b><%= h method.name %></b><%= h method.params %> + <% end %> + </div> + <% unless (description = method.description).empty? %> + <div class="description"> + <%# TODO delete this dirty hack when documentation for example for JavaScriptHelper will not be cutted off by <script> tag %> + <%= description.gsub('<script>'){ |m| h(m) } %> + </div> + <% end %> + <% unless method.aliases.empty? %> + <div class="aka"> + This method is also aliased as + <% method.aliases.each do |aka| %> + <a href="<%= context.aref_to aka.path %>"><%= h aka.name %></a> + <% end %> + </div> + <% end %> + <% if method.token_stream %> + <% markup = method.markup_code %> + <div class="sourcecode"> + <p class="source-link"> + Source: <a href="javascript:toggleSource('<%= method.aref %>_source')" id="l_<%= method.aref %>_source">show</a> + <% + if markup =~ /File\s(\S+), line (\d+)/ + path = $1 + line = $2.to_i + end + github = github_url(path) + if github + %> + | <a href="<%= "#{github}#L#{line}" %>" target="_blank" class="github_url">on GitHub</a> + <% end %> + </p> + <div id="<%= method.aref %>_source" class="dyn-source"> + <pre><%= method.markup_code %></pre> + </div> + </div> + <% end %> + </div> + <% end + end + end + %> +</div> diff --git a/lib/webri/generators/onefish/template/index.rhtml b/lib/webri/generators/onefish/template/index.rhtml new file mode 100644 index 0000000..928751c --- /dev/null +++ b/lib/webri/generators/onefish/template/index.rhtml @@ -0,0 +1,182 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html> + +<head> +<title><%= title %></title> +<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> +<link rel="icon" href="http://www.ruby-lang.org/favicon.ico" type="image/x-icon"> + +<link href="assets/css/style.css" rel="stylesheet" type="text/css"> + +<!-- RESET --> +<style type="text/css"> + html, body, div, span, applet, object, iframe, + h1, h2, h3, h4, h5, h6, p, blockquote, pre, + a, abbr, acronym, address, big, cite, code, + del, dfn, em, font, img, ins, kbd, q, s, samp, + small, strike, strong, sub, sup, tt, var, + b, u, i, center, + dl, dt, dd, ol, ul, li, + fieldset, form, label, legend, + table, caption, tbody, tfoot, thead, tr, th, td { + margin: 0; padding: 0; border: 0; outline: 0; + font-size: 100%; vertical-align: baseline; + background: transparent; } + body { line-height: 1; } + ol, ul { list-style: none; } + blockquote, q { quotes: none; } + blockquote:before, blockquote:after, + q:before, q:after { content: ''; content: none; } + /* remember to define focus styles! */ + :focus { outline: 0; } + /* remember to highlight inserts somehow! */ + ins { text-decoration: none; } + del { text-decoration: line-through; } + /* tables still need 'cellspacing="0"' in the markup */ + table { border-collapse: collapse; border-spacing: 0; } +</style> + +<style type="text/css"> + a { color: #303; text-decoration: underline; } + a:hover { color: #777; text-decoration: underline; } + body, td, p { font-family: "Bitstream Vera Sans", Verdana, Arial, Helvetica, sans-serif; background: #FFF; color: #222; margin: 0px; font-size: small; } + p { margin-top: 0.5em; margin-bottom: 0.5em; } + + #main { width: 1024px; margin: 0 auto; } + #content { margin: 2em; margin-left: 3.5em; margin-right: 3.5em; } + #description p { margin-bottom: 0.5em; } + .sectiontitle { margin-top: 1em; margin-bottom: 1em; padding: 0.5em; padding-left: 1em; background: #EFEFEF; color: #555; font-weight: bold; font-size: 150%; } + .attr-rw { padding-left: 1em; padding-right: 1em; text-align: center; color: #055; } + .attr-name { font-weight: bold; } + .attr-desc { } + .attr-desc p { margin-top: 0; } + .attr-value { font-family: monospace; } +.file-title-prefix { font-size: large; } + .file-title { font-size: large; font-weight: bold; background: #CCC; color: #FFF; } + .banner { background: #ffffff; color: #222; border-bottom: 2px solid #99B; padding: 1em; } + .banner td { background: transparent; color: #444; font-weight: bold; } + + h1 a, h2 a, .sectiontitle a { color: #404; text-decoration: none; } +h1 a:hover, h2 a:hover, .sectiontitle a:hover { color: #333; } + + .banner a { color: #DFD; } + .banner a:hover { color: #BFB; } + .dyn-source { display: none; background: #fffde8; color: #333; border: #ffe0bb dotted 1px; margin: 0.5em 2em 0.5em 2em; padding: 0.5em; } + .dyn-source .cmt { color: #999; font-style: italic; } + .dyn-source .kw { color: #070; font-weight: bold; } + .method { margin-left: 1em; margin-right: 1em; margin-bottom: 1em; } + .description pre { padding: 0.5em; border: #ffe0bb dotted 1px; background: #fffde8; } + .method .title { font-family: monospace; font-size: large; border-bottom: 1px dashed black; margin-bottom: 0.3em; margin-left: 0.5em; padding-bottom: 0.1em; color: #444; } + +.method .description, .method .sourcecode { margin-left: 1em; } + .description p, .sourcecode p { margin-bottom: 0.5em; } + .method .sourcecode p.source-link { text-indent: 0em; margin-top: 0.5em; } + + .method .aka { margin-top: 0.3em; margin-left: 1em; font-style: italic; text-indent: 2em; } + h1 { padding: 20px 30px; margin-left: -1.0em; font-size: 3em; font-weight: bold; color: #444; background: #EFEFEF; } + h2 { padding:0.5em 1em 0.5em 1em; margin-left:-1.5em; font-size:large; font-weight:bold; color:#666; background:#EFEFEF; } + h3, h4, h5, h6 { color: #440044; border-bottom: #5522bb solid 1px; } + .sourcecode > pre { padding: 0.5em; border: 1px dotted black; background: #FFE; } + dt { font-weight: bold } + dd { margin-bottom: 0.7em; } +</style> + +</head> + +<body> +<div id="screen"> + + <div id="tree"> + <%= tree %> + </div> + + <div style="clear: both;"></div> + + <div id="main"> + + <div id="header"> + <div class="small ad"> + </div> + <div> + <img src="assets/img/ruby_logo.png" align="left"/> + <h1><%= title %> v.<%= metadata.version %></h1> + <% if metadata.subtitle %> + <h2><%= metadata.subtitle %></h2> + <% end %> + <h2><span class="small"><%= copyright %></span></h1> + </div> + </div> + + <!-- TOPLEVEL FILES --> + + <% files_toplevel.each do |file| %> + <table border='0' cellpadding='0' cellspacing='0' width="100%" class='banner'> + <tr><td> + <table width="100%" border='0' cellpadding='0' cellspacing='0'><tr> + <td class="file-title" colspan="2"><span class="file-title-prefix">File</span><br /><%= h file.name %></td> + <td align="right"> + <table border='0' cellspacing="0" cellpadding="2"> + <tr> + <td>Path:</td> + <td><%= h file.relative_name %></td> + </tr> + <tr> + <td>Modified:</td> + <td><%= file.file_stat.mtime %></td> + </tr> + </table> + </td></tr> + </table> + </td></tr> + </table> + <div id="bodyContent"> + <%= include_template 'context.rhtml', {:context => file, :rel_prefix => rel_prefix} %> + </div> + <% end %> + + <!-- CLASSES/MODULES --> + + <% classes.each do |klass| %> + <table width="100%" border='0' cellpadding='0' cellspacing='0' class='banner'> + <tr> + <td class="file-title"><span class="file-title-prefix"><%= klass.module? ? 'Module' : 'Class' %></span><br /><%= h klass.full_name %></td> + <td align="right"> + <table cellspacing="0" cellpadding="2"> + <tr valign="top"> + <td>In:</td> + <td> + <% klass.in_files.each do |file| %> + <a href="<%= "#{rel_prefix}/#{h file.path}" %>"><%= h file.absolute_name %></a> + <% end %> + </td> + </tr> + <% if klass.type == 'class' %> + <tr> + <td>Parent:</td> + <td> + <% if String === klass.superclass %> + <%= klass.superclass %> + <% elsif !klass.superclass.nil? %> + <a href="<%= klass.aref_to klass.superclass.path %>"><%= h klass.superclass.full_name %></a> + <% end %> + </td> + </tr> + <% end %> + </table> + </td> + </tr> + </table> + <div id="bodyContent"> + <%= include_template 'context.rhtml', {:context => klass, :rel_prefix => rel_prefix} %> + </div> + <% end %> + + <div class="slot"> + <p>Generated with <a href="http://">WebRI OneFish</a> <%= WebRI::VERSION %></p> + <div> + </div> + +</div> +</body> +</html> +
razerbeans/webri
3ba2b875e4a925082fffac1b9eeb0b95742a8a46
rename quicksearch to search
diff --git a/lib/webri/components/quicksearch.rb b/lib/webri/components/search.rb similarity index 99% rename from lib/webri/components/quicksearch.rb rename to lib/webri/components/search.rb index bcc476a..c829b65 100644 --- a/lib/webri/components/quicksearch.rb +++ b/lib/webri/components/search.rb @@ -1,234 +1,234 @@ require 'webri/components/abstract' require 'iconv' module WebRI # - class QuickSearch < Component + class Search < Component # SEARCH_TREE_FILE = 'search_tree.js' # SEARCH_INDEX_FILE = 'search_index.js' # Used in js to reduce index sizes TYPE_CLASS = 1 TYPE_METHOD = 2 TYPE_FILE = 3 # def path @path ||= Pathname.new(File.dirname(__FILE__)) end # Generate class tree and serach index. def generate generate_static generate_search_tree generate_search_index end # Create class tree structure and write it as json def generate_search_tree debug_msg "Generating Class Tree:" topclasses = classes.select {|klass| !(RDoc::ClassModule === klass.parent) } tree = generate_file_tree + generate_search_tree_level(topclasses) debug_msg "writing class tree to %s" % SEARCH_TREE_FILE File.open(SEARCH_TREE_FILE, "w", 0644) do |f| f.write('var tree = '); f.write(tree.to_json) end unless $dryrun end # Recursivly build class tree structure def generate_search_tree_level(classes) tree = [] classes.select{|c| c.with_documentation? }.sort.each do |klass| item = [ klass.name, klass.document_self_or_methods ? klass.path : '', klass.module? ? '' : (klass.superclass ? " < #{String === klass.superclass ? klass.superclass : klass.superclass.full_name}" : ''), generate_search_tree_level(klass.classes_and_modules) ] tree << item end tree end # Create search index for all classes, methods and files # Write as json. def generate_search_index debug_msg "Generating Search Index:" index = { :searchIndex => [], :longSearchIndex => [], :info => [] } add_class_search_index(index) add_method_search_index(index) add_file_search_index(index) debug_msg "writing search index to %s" % SEARCH_INDEX_FILE data = { :index => index } File.open(SEARCH_INDEX_FILE, "w", 0644) do |f| f.write('var search_data = '); f.write(data.to_json) end unless $dryrun end # Add files to search +index+ array. def add_file_search_index(index) debug_msg "generating file search index" files.select { |file| file.document_self }.sort.each do |file| index[:searchIndex].push( search_string(file.name) ) index[:longSearchIndex].push( search_string(file.path) ) index[:info].push([ file.name, file.path, file.path, '', snippet(file.comment), TYPE_FILE ]) end end # Add classes to search +index+ array. def add_class_search_index(index) debug_msg "generating class search index" classes.select { |klass| klass.document_self_or_methods }.sort.each do |klass| modulename = klass.module? ? '' : (klass.superclass ? (String === klass.superclass ? klass.superclass : klass.superclass.full_name) : '') index[:searchIndex].push( search_string(klass.name) ) index[:longSearchIndex].push( search_string(klass.parent.full_name) ) index[:info].push([ klass.name, klass.parent.full_name, klass.path, modulename ? " < #{modulename}" : '', snippet(klass.comment), TYPE_CLASS ]) end end # Add methods to search +index+ array. def add_method_search_index(index) debug_msg "generating method search index" list = classes.map { |klass| klass.method_list }.flatten.sort{ |a, b| a.name == b.name ? a.parent.full_name <=> b.parent.full_name : a.name <=> b.name }.select { |method| method.document_self } unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end list.each do |method| index[:searchIndex].push( search_string(method.name) + '()' ) index[:longSearchIndex].push( search_string(method.parent.full_name) ) index[:info].push([ method.name, method.parent.full_name, method.path, method.params, snippet(method.comment), TYPE_METHOD ]) end end # Build search index key. def search_string(string) string ||= '' string.downcase.gsub(/\s/,'') end # def generate_file_tree if files.length > 1 @files_tree = FilesTree.new files.each do |file| @files_tree.add(file.relative_name, file.path) end [['', '', 'files', generate_file_tree_level(@files_tree)]] else [] end end # def generate_file_tree_level(tree) tree.children.keys.sort.map do |name| child = tree.children[name] if String === child [name, child, '', []] else ['', '', name, generate_file_tree_level(child)] end end end # class FilesTree attr_reader :children def add(path, url) path = path.split(File::SEPARATOR) unless Array === path @children ||= {} if path.length == 1 @children[path.first] = url else @children[path.first] ||= FilesTree.new @children[path.first].add(path[1, path.length], url) end end end # Strip comments on a space after 100 chars def snippet(str) str ||= '' if str =~ /^(?>\s*)[^\#]/ content = str else content = str.gsub(/^\s*(#+)\s*/, '') end content = content.sub(/^(.{100,}?)\s.*/m, "\\1").gsub(/\r?\n/m, ' ') begin content.to_json rescue # might fail on non-unicode string begin # remove all non-unicode chars content = Iconv.conv('latin1//ignore', "UTF8", content) content.to_json rescue content = '' # something hugely wrong happend end end content end end end diff --git a/lib/webri/components/quicksearch/static/assets/css/panel.css b/lib/webri/components/search/static/assets/css/panel.css similarity index 100% rename from lib/webri/components/quicksearch/static/assets/css/panel.css rename to lib/webri/components/search/static/assets/css/panel.css diff --git a/lib/webri/components/quicksearch/static/assets/js/searchdoc.js b/lib/webri/components/search/static/assets/js/searchdoc.js similarity index 100% rename from lib/webri/components/quicksearch/static/assets/js/searchdoc.js rename to lib/webri/components/search/static/assets/js/searchdoc.js diff --git a/lib/webri/components/quicksearch/static/panel.html b/lib/webri/components/search/static/panel.html similarity index 100% rename from lib/webri/components/quicksearch/static/panel.html rename to lib/webri/components/search/static/panel.html diff --git a/lib/webri/generators/blackfish/generator.rb b/lib/webri/generators/blackfish/generator.rb index ea1ff94..deab00d 100644 --- a/lib/webri/generators/blackfish/generator.rb +++ b/lib/webri/generators/blackfish/generator.rb @@ -1,65 +1,66 @@ require 'webri/generators/abstract' -require 'webri/components/quicksearch' +require 'webri/components/search' require 'webri/components/github' module WebRI - # Blackfish is based on Володя Колесников's SDoc + # Blackfish is based on Vladimir Kolesnikov's SDoc # (Copyright (c) 2009 Vladimir Kolesnikov). # # The SDoc code base was helpful in understanding how to # build an RDoc generator. It was convenient to keep a # copy in with the WebRI code for reference. Later, it was # easy enough to integrate it with the rest of WebRI - # (eg. splitting QuickSearch into a separate component), - # and so it stayed as an alernate template. + # (eg. splitting Search into a separate component), + # and so it has stayed as an alernate template with + # a few style modifications. # class Blackfish < WebRI::Generator - include QuickSearch + include Search include GitHub # def path @path ||= Pathname.new(__FILE__).parent end #def generate_template # super #end # TODO: Does this belong here or in the quicksearch component? def each_letter_group(methods, &block) group = {:name => '', :methods => []} methods.sort{ |a, b| a.name <=> b.name }.each do |method| gname = group_name method.name if gname != group[:name] yield group unless group[:methods].size == 0 group = { :name => gname, :methods => [] } end group[:methods].push(method) end yield group unless group[:methods].size == 0 end protected # def group_name(name) if match = name.match(/^([a-z])/i) match[1].upcase else '#' end end end end
razerbeans/webri
b149b471a3154ba0f15fb1672193138070b21aa4
ignore demo doc directory
diff --git a/.gitignore b/.gitignore index 9d0f21c..0407676 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ MANIFEST .cache log pkg +demo/fish-sampler/doc doc/rdoc doc/ri doc/webri doc/webri.html work/sandbox
razerbeans/webri
89098ab545d02d7e4f94dfae779850382450b27d
imporved redfish template
diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index 817f2ba..7b82b8e 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,660 +1,659 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' require 'webri/extensions/fileutils' require 'webri/generators/abstract/timedelta' require 'webri/generators/abstract/erbtemplate' # module WebRI # = Abstract Generator Base Class # class Generator #include ERB::Util include TimeDelta # # C O N S T A N T S # #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. - PATH_STATIC = Pathname.new(LOADPATH + 'webri/generators/abstract/static') + PATH_STATIC = Pathname.new(LOADPATH + '/webri/generators/abstract/static') # Common template directory. - PATH_TEMPLATE = Pathname.new(LOADPATH + 'webri/generators/abstract/template') + PATH_TEMPLATE = Pathname.new(LOADPATH + '/webri/generators/abstract/template') # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # TODO: Get from metadata -- use POM if available. def title options.title end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(toplevel_files) @files_toplevel = toplevel_files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template -p LOADPATH + "webri/generators/#{template}/template" Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s - show_from = PATH_STATIC.to_s.sub(PATH.parent.to_s+'/','') + show_from = PATH_STATIC.to_s.sub(LOADPATH.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(path.parent.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files_toplevel.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template @erb_template ||= ERBTemplate.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end # Output progress information if rdoc debugging is enabled def debug_msg(msg) return unless $DEBUG_RDOC case msg[-1,1] when '.' then tab = "= " when ':' then tab = "== " else tab = "* " end $stderr.puts(tab + msg) end end end diff --git a/lib/webri/generators/redfish/static/assets/css/rdoc.css b/lib/webri/generators/redfish/static/assets/css/rdoc.css index 3400325..81ba389 100644 --- a/lib/webri/generators/redfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/redfish/static/assets/css/rdoc.css @@ -1,794 +1,831 @@ /* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Base Red is: color: #FF226C; */ *{ padding: 0; margin: 0; } body { background: #efefef; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; - padding: 15px 40px; + padding: 0 40px 15px 40px; +} + +#main { + width: 1024px; + margin: 0 auto; } /* body.class, body.module, body.file { margin-left: 40px; } */ body.file-popup { font-size: 90%; margin-left: 0; } +img { border: none; } + h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: #FF226C; } h2,h3,h4 { margin-top: 1.5em; } a { color: #FF226C; text-decoration: none; } a:hover { border-bottom: 1px dotted #FF226C; } pre { padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; - border: 0px solid #aaa; - padding: 0 10px; - margin: 0 8px 5px 8px; + border-bottom: 0px solid #aaa; + border-left: 0px solid #aaa; + border-right: 0px solid #aaa; + padding: 10px 10px; + margin: 0 8px -0.5em 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; background: url(images/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; background: url(images/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; background: url(images/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; background: url(images/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; background: url(images/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { - float: left; + float: right; width: 320px; margin-top: 10px; } #documentation { - margin: 0 1em 5em 360px; + margin: 0 360px 5em 1em; min-width: 340px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } +.method-parent-aside { + float: right; font-size: 0.7em; + font-weight: bold; + padding: 0 20px; + color: #999; +} + /* @end */ /* @group Documentation Section */ + +#documentation h1 { + margin: 10px 0 10px 0; + padding: 0.5em 0.5em; + background-color: #dedede; + border: 1px solid #bbb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; +} + #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 150%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ -.file #documentation { +/* .file #documentation { margin: 0; -} +} */ .file #metadata { - float: left; + float: right; } .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } .file h2 { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 120%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } /* @end */ +/* @group Debugging Section */ + +#debugging-toggle { + text-align: center; +} +#debugging-toggle img { + cursor: pointer; +} + +#rdoc-debugging-section-dump { + display: none; + margin: 0 2em 2em; + background: #ccc; + border: 1px solid #999; +} + +/* @end */ + + + + + + + + + + + + /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ -/* @group Debugging Section */ -#debugging-toggle { - text-align: center; -} -#debugging-toggle img { - cursor: pointer; -} - -#rdoc-debugging-section-dump { - display: none; - margin: 0 2em 2em; - background: #ccc; - border: 1px solid #999; -} - - - -/* @end */ diff --git a/lib/webri/generators/redfish/static/assets/js/darkfish.js b/lib/webri/generators/redfish/static/assets/js/darkfish.js index 43528fd..0020f25 100644 --- a/lib/webri/generators/redfish/static/assets/js/darkfish.js +++ b/lib/webri/generators/redfish/static/assets/js/darkfish.js @@ -1,116 +1,107 @@ /** * * Darkfish Page Functions * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ * * Author: Michael Granger <[email protected]> * */ /* Provide console simulation for firebug-less environments */ if (!("console" in window) || !("firebug" in console)) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; }; /** * Unwrap the first element that matches the given @expr@ from the targets and return them. */ $.fn.unwrap = function( expr ) { return this.each( function() { $(this).parents( expr ).eq( 0 ).after( this ).remove(); }); }; function showSource( e ) { var target = e.target; var codeSections = $(target). parents('.method-detail'). find('.method-source-code'); $(target). parents('.method-detail'). find('.method-source-code'). slideToggle(); }; function hookSourceViews() { $('.method-description,.method-heading').click( showSource ); }; function toggleDebuggingSection() { $('.debugging-section').slideToggle(); }; function hookDebuggingToggle() { $('#debugging-toggle img').click( toggleDebuggingSection ); }; function hookQuickSearch() { $('.quicksearch-field').each( function() { var searchElems = $(this).parents('.section').find( 'li' ); var toggle = $(this).parents('.section').find('h3 .search-toggle'); // console.debug( "Toggle is: %o", toggle ); var qsbox = $(this).parents('form').get( 0 ); $(this).quicksearch( this, searchElems, { noSearchResultsIndicator: 'no-class-search-results', focusOnLoad: false }); $(toggle).click( function() { // console.debug( "Toggling qsbox: %o", qsbox ); $(qsbox).toggle(); }); }); }; function highlightTarget( anchor ) { console.debug( "Highlighting target '%s'.", anchor ); $("a[name=" + anchor + "]").each( function() { if ( !$(this).parent().parent().hasClass('target-section') ) { console.debug( "Wrapping the target-section" ); $('div.method-detail').unwrap( 'div.target-section' ); $(this).parent().wrap( '<div class="target-section"></div>' ); } else { console.debug( "Already wrapped." ); } }); }; function highlightLocationTarget() { console.debug( "Location hash: %s", window.location.hash ); if ( ! window.location.hash || window.location.hash.length == 0 ) return; var anchor = window.location.hash.substring(1); console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" ); highlightTarget( anchor ); }; function highlightClickTarget( event ) { console.debug( "Highlighting click target for event %o", event.target ); try { var anchor = $(event.target).attr( 'href' ).substring(1); console.debug( "Found target anchor: %s", anchor ); highlightTarget( anchor ); } catch ( err ) { console.error( "Exception while highlighting: %o", err ); }; }; - -$(document).ready( function() { - hookSourceViews(); - hookDebuggingToggle(); - hookQuickSearch(); - highlightLocationTarget(); - - $('ul.link-list a').bind( "click", highlightClickTarget ); -}); diff --git a/lib/webri/generators/redfish/static/assets/js/quicksearch.js b/lib/webri/generators/redfish/static/assets/js/quicksearch.js new file mode 100644 index 0000000..332772a --- /dev/null +++ b/lib/webri/generators/redfish/static/assets/js/quicksearch.js @@ -0,0 +1,114 @@ +/** + * + * JQuery QuickSearch - Hook up a form field to hide non-matching elements. + * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $ + * + * Author: Michael Granger <[email protected]> + * + */ +jQuery.fn.quicksearch = function( target, searchElems, options ) { + // console.debug( "Quicksearch fn" ); + + var settings = { + delay: 250, + clearButton: false, + highlightMatches: false, + focusOnLoad: false, + noSearchResultsIndicator: null + }; + if ( options ) $.extend( settings, options ); + + return jQuery(this).each( function() { + // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems ); + new jQuery.quicksearch( this, searchElems, settings ); + }); +}; + + +jQuery.quicksearch = function( searchBox, searchElems, settings ) { + var timeout; + var boxdiv = $(searchBox).parents('div').eq(0); + + function init() { + setupKeyEventHandlers(); + focusOnLoad(); + }; + + function setupKeyEventHandlers() { + // console.debug( "Hooking up the 'keypress' event to %o", searchBox ); + $(searchBox). + unbind( 'keyup' ). + keyup( function(e) { return onSearchKey( e.keyCode ); }); + $(searchBox). + unbind( 'keypress' ). + keypress( function(e) { + switch( e.which ) { + // Execute the search on Enter, Tab, or Newline + case 9: + case 13: + case 10: + clearTimeout( timeout ); + e.preventDefault(); + doQuickSearch(); + break; + + // Allow backspace + case 8: + return true; + break; + + // Only allow valid search characters + default: + return validQSChar( e.charCode ); + } + }); + }; + + function focusOnLoad() { + if ( !settings.focusOnLoad ) return false; + $(searchBox).focus(); + }; + + function onSearchKey ( code ) { + clearTimeout( timeout ); + // console.debug( "...scheduling search." ); + timeout = setTimeout( doQuickSearch, settings.delay ); + }; + + function validQSChar( code ) { + var c = String.fromCharCode( code ); + return ( + (c == ':') || + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') + ); + }; + + function doQuickSearch() { + var searchText = searchBox.value; + var pat = new RegExp( searchText, "im" ); + var shownCount = 0; + + if ( settings.noSearchResultsIndicator ) { + $('#' + settings.noSearchResultsIndicator).hide(); + } + + // All elements start out hidden + $(searchElems).each( function(index) { + var str = $(this).text(); + + if ( pat.test(str) ) { + shownCount += 1; + $(this).fadeIn(); + } else { + $(this).hide(); + } + }); + + if ( shownCount == 0 && settings.noSearchResultsIndicator ) { + $('#' + settings.noSearchResultsIndicator).slideDown(); + } + }; + + init(); +}; diff --git a/lib/webri/generators/redfish/static/assets/js/ready.js b/lib/webri/generators/redfish/static/assets/js/ready.js new file mode 100644 index 0000000..5d27860 --- /dev/null +++ b/lib/webri/generators/redfish/static/assets/js/ready.js @@ -0,0 +1,13 @@ +$(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); +}); + diff --git a/lib/webri/generators/redfish/template/class.rhtml b/lib/webri/generators/redfish/template/class.rhtml index 3f9563c..3cc5cb8 100644 --- a/lib/webri/generators/redfish/template/class.rhtml +++ b/lib/webri/generators/redfish/template/class.rhtml @@ -1,304 +1,325 @@ <?xml version="1.0" encoding="utf-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> <% if klass.type == "class" %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> <% else %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> <% end %> - <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> - <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> </head> <body class="<%= klass.type %>"> +<div id="main"> <div class="head"> <h1> <% if klass.type == "class" %> <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; <% end %> <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <ul> <% klass.in_files.each do |tl| %> <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> <% end %> </ul> </div> </div> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <!-- TODO: generalize this for all SCMs --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> </div> <div id="class-metadata"> <!-- Parent Class --> <% if klass.type == 'class' %> <div id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <ul> <% unless String === klass.superclass %> <!-- why was this class="link" ? --> <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> <% else %> <li class="class"><%= klass.superclass %></li> <% end %> </ul> </div> <% end %> <!-- Namespace Contents --> <% unless klass.classes_and_modules.empty? %> <div id="namespace-list-section" class="section"> <h3 class="section-header">Namespace</h3> <ul class="link-list"> <% (klass.modules.sort + klass.classes.sort).each do |mod| %> <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> </div> <% end %> <!-- Method Quickref --> <% unless klass.method_list.empty? %> <div id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <% klass.each_method do |meth| %> <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> <% end %> </ul> </div> <% end %> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> </div> <div id="project-metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <!-- classpage.html : classes --> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> - <div id="debugging-toggle" style="float: right;"><img src="<%= rel_prefix %>/assets/img/bug.png" - alt="toggle debugging" height="16" width="16" /></div> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> + </div> <% end %> + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> - <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> <div id="documentation"> <div id="description"> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC require 'pp' %> <pre><%= h PP.pp(klass, _erbout) %></pre> </div> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> +</main> </body> </html> + diff --git a/lib/webri/generators/redfish/template/file.rhtml b/lib/webri/generators/redfish/template/file.rhtml index f8af213..06516c0 100644 --- a/lib/webri/generators/redfish/template/file.rhtml +++ b/lib/webri/generators/redfish/template/file.rhtml @@ -1,125 +1,141 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= options.title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> - <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="<%= rel_prefix %>/assets/js/github.css" title="GitHub" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> - <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> + <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/highlight.js"></script> + + <script type="text/javascript"> + $(document).ready( function() { + $('#documentation pre').wrapInner('<code></code>'); + hljs.tabReplace = ' '; + hljs.initHighlightingOnLoad('ruby'); + + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); + + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> </head> -<% if file.parser == RDoc::Parser::Simple %> -<body class="file"> +<body class="file"> <!-- .file-popup is no more --> +<div id="main"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> - <div id="project-metadata"> + <div id="file-stats-section" class="section"> + <h3 class="section-header">File Stats</h3> + <dl> + <dt class="modified-date">Last Modified</dt> + <dd class="modified-date"><%= file.last_modified %></dd> + + <% if !file.requires.empty? %> + <dt class="requires">Requires</dt> + <dd class="requires"> + <ul> + <% file.requires.each do |require| %> + <li><%= require.name %></li> + <% end %> + </ul> + </dd> + <% end %> + + <% if options.webcvs %> + <dt class="scs-url">Trac URL</dt> + <dd class="scs-url"><a target="_top" + href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> + <% end %> + </dl> + </div> + <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> - <h3 class="section-header">Files</h3> + <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> - <div id="debugging-toggle" style="float: right;"> - <img src="<%= rel_prefix %>/assets/img/bug.png" alt="toggle debugging" height="16" width="16" /> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="<%= rel_prefix %>/assets/img/bug.png" alt="[Debug]" height="16" width="16" /> </div> <% end %> + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="<%= rel_prefix %>/assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> - <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> - <div id="documentation"> - <%= file.description %> - </div> - -</body> - -<% else %> - -<body class="file file-popup"> - <div id="metadata"> - <dl> - <dt class="modified-date">Last Modified</dt> - <dd class="modified-date"><%= file.last_modified %></dd> - - <% if file.requires %> - <dt class="requires">Requires</dt> - <dd class="requires"> - <ul> - <% file.requires.each do |require| %> - <li><%= require.name %></li> - <% end %> - </ul> - </dd> - <% end %> - - <% if options.webcvs %> - <dt class="scs-url">Trac URL</dt> - <dd class="scs-url"><a target="_top" - href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> + <!-- .file-popup was wrapped: + <div id="documentation"> + <% if file.comment %> + <div class="description"> + ... file.description ... + </div> <% end %> - </dl> - </div> + </div> + So maybe that css is no longer needed. + --> <div id="documentation"> - <% if file.comment %> - <div class="description"> - <%= file.description %> - </div> - <% end %> + <%= file.description %> </div> -</body> - -<% end %> +</div> +</body> </html> + diff --git a/lib/webri/generators/redfish/template/index.rhtml b/lib/webri/generators/redfish/template/index.rhtml index 612601e..c28948c 100644 --- a/lib/webri/generators/redfish/template/index.rhtml +++ b/lib/webri/generators/redfish/template/index.rhtml @@ -1,143 +1,153 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= h options.title %></title> <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> + <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> + <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> + <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> - <script type="text/javascript" charset="utf-8" src="assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> <script type="text/javascript"> - $(document).ready(function() { + $(document).ready( function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); - }); - </script> - <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> - <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> + hookSourceViews(); + hookDebuggingToggle(); + hookQuickSearch(); + highlightLocationTarget(); - <% $stderr.sync = true %> + $('ul.link-list a').bind( "click", highlightClickTarget ); + }); + </script> </head> <body class="indexpage"> +<div id="main"> + <% $stderr.sync = true %> <div class="head"> <h1> <img src="assets/img/project.png" align="absmiddle">&nbsp; <a href="index.html"><%= h options.title %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> - <h3 class="section-header">Files</h3> + <h3 class="section-header">Information</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li class="method" style="clear: both;"> - <span style="float: right; font-size: 0.8em;">&nbsp;<%= method.parent.full_name %></span> + <span class="method-parent-aside"><%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> - <div id="debugging-toggle" style="float: right;"><img src="assets/img/bug.png" alt="toggle debugging" height="16" width="16" /></div> + <div id="debugging-toggle" style="float: right; margin-right: 5px;"> + <img src="assets/img/bug.png" alt="[Debug]" height="16" width="16" /> + </div> <% end %> - + <div style="float: right; margin-right: 5px;"> + <a href="http://validator.w3.org/check/referer"><img src="assets/img/check.png" alt="[Validate]" height="16" width="16" /> + </div> Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> - <br/><br/> - <a href="http://validator.w3.org/check/referer">[Validate]</a> + <br/><br/> </div> </div> <!-- <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <h2>Files</h2> <ul> <% simple_files.sort.each do |file| %> <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> <% end %> <h2>Classes/Modules</h2> <ul> <% classes_salient.each do |klass| %> <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> <% end %> </ul> <h2>Methods</h2> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> <% end %> </ul> --> <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> <div id="documentation"> <%= main_page.description %> </div> <% else %> <p>This is the API documentation for '<%= options.title %>'.</p> <% end %> +</div> </body> </html>
razerbeans/webri
eb3ae65820b01e0ec2aec9ccb9306df4d7e6eac0
added demo
diff --git a/README b/README index e32fd01..5e83ce5 100644 --- a/README +++ b/README @@ -1,114 +1,112 @@ = WebRI * http://proutils.github.com/webri * http://github.com/proutils/webri * http://googlegroups/group/proutils == DESCRIPTION WebRI is both a dynamic web-based ri-browser which can provided ri documentation dynamically, by running a webrick server, and a superalatvie Ruby documentation generator with a variety of built in templates. == FEATURES -* WebRI provides Beautiful Templates, enhanced renditions of some of -the best designs currently in use. +* WebRI provides Beautiful Templates, enhanced renditions of some of the best designs currently in use. * Variety of templates built-in, to meet a varitey of tastes and needs. -* Under the hood, a component system allows geneators to be more -easily extended. +* Under the hood, a component system allows geneators to be more easily extended. == LIMITATIONS Please note that the ri web server and the generation system were developed separately, and are not well integrated. For this reason (at the very least) the ri server cannot use the templates available to the generators. If possible, a future version will allow this. == USAGE SYNOPSIS === Generate Documentation WebRI provides a <tt>webri</tt> executable you can use to generate documentation. The interface is identical to <tt>rdoc</tt>. Use the -T option to specify a template type. $ webri -T redfish README lib/ You can use <tt>rdoc</tt> command if you prefer (though in far off future versions this may not be the case). $ rdoc -T redfish README lib/ WebRI extend RIDoc to recognize the templates that WebRI will handle and transfers control to appropriate WebRI generator accordingly. === Using the Web Server WebRI can be used as a dynamic ri browser, either for a single project or for a collection of libraries. Indeed, the WebRI server can be used to browse the entire installed object system --eveything documented in your central install locations. To do the later, simply execute <tt>webri-server</tt> with no arguments and open a webrowser to the local port designated (see below). $ webr-server To browse per-project ri documentation, you will first need to locate the project's ri files, either by locating them in your system installation or by generating them for a project, which can be done using rdoc, eg. $ rdoc --ri --op "doc/ri" lib/ Sometimes a package will include a convenience script for generating these. Try running 'rake -T', or look for a 'script/' or 'task/' executable that does the job. Usually the generated documentation is placed in either ri/ or doc/ri/. I will use doc/ri/ in the following example, adjust your directory as needed. With ri files loacted you can view them with: $ webri-server doc/ri You will see a Webrick server start up, informing you of the port being used. [2008-03-28 12:11:16] INFO WEBrick 1.3.1 [2008-03-28 12:11:16] INFO ruby 1.8.6 (2007-06-07) [x86_64-linux] [2008-03-28 12:11:21] INFO WEBrick::HTTPServer#start: pid=8870 port=8888 In this example we see the port is the default 8888. Simply open your browser and navigate to: http://localhost:8888/ On the left side of the screen you will see a navigation tree, and the right side contans an infromation panel. NOTE: Becuase <tt>ri</tt> itself isn't very fast, if you use WebRI against the entire set of installed Ruby libraries it can take a few seconds to load up. (Sure wish FastRI turned out for the better.) == INSTALLATION Installing via RubyGems is per the usual: $ sudo gem install webri == COPYING WebRI Copyright (c) 2009 Thomas Sawyer, MIT License THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/demo/fish-sampler/README b/demo/fish-sampler/README new file mode 100644 index 0000000..073eac2 --- /dev/null +++ b/demo/fish-sampler/README @@ -0,0 +1,112 @@ += WebRI Fish Sampler + +* http://proutils.github.com/webri +* http://github.com/proutils/webri +* http://googlegroups/group/proutils + + +== DESCRIPTION + +WebRI is both a dynamic web-based ri-browser which can provided +ri documentation dynamically, by running a webrick server, and +a superalatvie Ruby documentation generator with a variety of +built in templates. + +== FEATURES + +* WebRI provides Beautiful Templates, enhanced renditions of some of the best designs currently in use. +* Variety of templates built-in, to meet a varitey of tastes and needs. +* Under the hood, a component system allows geneators to be more easily extended. + + +== LIMITATIONS + +Please note that the ri web server and the generation system +were developed separately, and are not well integrated. +For this reason (at the very least) the ri server cannot use +the templates available to the generators. If possible, a future +version will allow this. + + +== USAGE SYNOPSIS + +=== Generate Documentation + +WebRI provides a <tt>webri</tt> executable you can use to generate +documentation. The interface is identical to <tt>rdoc</tt>. Use +the -T option to specify a template type. + + $ webri -T redfish README lib/ + +You can use <tt>rdoc</tt> command if you prefer (though in far +off future versions this may not be the case). + + $ rdoc -T redfish README lib/ + +WebRI extend RIDoc to recognize the templates that WebRI will handle +and transfers control to appropriate WebRI generator accordingly. + +=== Using the Web Server + +WebRI can be used as a dynamic ri browser, either for a single project +or for a collection of libraries. Indeed, the WebRI server can be used +to browse the entire installed object system --eveything documented in +your central install locations. To do the later, simply execute +<tt>webri-server</tt> with no arguments and open a webrowser to +the local port designated (see below). + + $ webr-server + +To browse per-project ri documentation, you will first need to locate +the project's ri files, either by locating them in your system installation +or by generating them for a project, which can be done using rdoc, eg. + + $ rdoc --ri --op "doc/ri" lib/ + +Sometimes a package will include a convenience script for generating these. +Try running 'rake -T', or look for a 'script/' or 'task/' executable that does +the job. Usually the generated documentation is placed in either ri/ or doc/ri/. +I will use doc/ri/ in the following example, adjust your directory as needed. + +With ri files loacted you can view them with: + + $ webri-server doc/ri + +You will see a Webrick server start up, informing you of the port being used. + + [2008-03-28 12:11:16] INFO WEBrick 1.3.1 + [2008-03-28 12:11:16] INFO ruby 1.8.6 (2007-06-07) [x86_64-linux] + [2008-03-28 12:11:21] INFO WEBrick::HTTPServer#start: pid=8870 port=8888 + +In this example we see the port is the default 8888. Simply open your browser and +navigate to: + + http://localhost:8888/ + +On the left side of the screen you will see a navigation tree, and the right side +contans an infromation panel. + +NOTE: Becuase <tt>ri</tt> itself isn't very fast, if you use WebRI against the +entire set of installed Ruby libraries it can take a few seconds to load up. +(Sure wish FastRI turned out for the better.) + + +== INSTALLATION + +Installing via RubyGems is per the usual: + + $ sudo gem install webri + + +== COPYING + +WebRI Copyright (c) 2009 Thomas Sawyer, MIT License + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/demo/fish-sampler/lib/fish.rb b/demo/fish-sampler/lib/fish.rb new file mode 100644 index 0000000..6690fcc --- /dev/null +++ b/demo/fish-sampler/lib/fish.rb @@ -0,0 +1,116 @@ +# = Fish Sampler +# +# Let us review... Red fish, Blue fish, One fish, Two fish... +# +module FishSampler + + # Every fish is scaly. + DEFALULT_QUALITIES = [ :scaly ] + + # A fish is any aquatic vertebrate animal that is typically ectothermic (or cold-blooded), + # covered with scales, and equipped with two sets of paired fins and several unpaired fins. + # Fish are abundant in the sea and in fresh water, with species being known from mountain + # streams (e.g., char and gudgeon) as well as in the deepest depths of the ocean + # (e.g., gulpers and anglerfish). + + class Fish + # List of various fish qualities. + attr_accessor :qualities + + # New Fish + def initialize + @qualties = DEFALULT_QUALITIES + initialize_qualities + end + + # Override to add qualties. + def initialize_qualities + end + end + + # = Brite Red Fish + # + # Red fish are quite pretty a fairly common. + class RedFish + # List of various fish qualities. + attr_accessor :qualities + + # New Red Fish + def initialize_qualities + super + @qualties << :red + end + end + + # = Blue Fish + # + # Despite their name most Bluefish aren't very blue. + class BlueFish < Fish + # List of various fish qualities. + attr_accessor :qualities + + # New Blue Fish + def initialize_qualities + super + @qualties << :blue + end + end + + # Fish get old too. + class OldFish < Fish + # List of various fish qualities. + attr_accessor :qualities + + # New Old Fish + def initialize_qualities + super + @qualties = << :old + end + end + + # It's hard to tell new fish form small fish. + class NewFish < Fish + # List of various fish qualities. + attr_accessor :qualities + + # New NewFish + def initialize_qualities + super + @qualties << :new + end + end + + # Some fish will eat a man! + module ManEater + # Man Eaters are scary! + def initialize_qualities + super + @qualties << :scary + end + end + + # = Shark (Yikes!) + # + # Sharks (superorder Selachimorpha) are a type of fish with a full cartilaginous skeleton + # and a highly streamlined body. The earliest known sharks date from more than 420 million + # years ago, before the time of the dinosaurs. + # + class Shark < Fish + include ManEater + + # New Shark + def initialize_qualities + super + @qualties << :big + end + + private + + def secret + puts "Shh... shark secrets!" + end + + end + +end + diff --git a/demo/fish-sampler/lib/multipliers.rb b/demo/fish-sampler/lib/multipliers.rb new file mode 100644 index 0000000..2afa247 --- /dev/null +++ b/demo/fish-sampler/lib/multipliers.rb @@ -0,0 +1,97 @@ +# = Multipliers +# +# == Synopsis +# +# Adds methods to Numeric to make working with magnitudes +# (kilo, mega, giga, milli, micro, etc.) +# +# == History +# +# Thanks to Rich Kilmer and bytes.rb which inspired this library. +# +# == Notes +# +# * This library is not compatible with STICK's units.rb (an spin-off +# of Facets old units.rb library). Do not attempt to use both at +# the same time. +# +# == Authors +# +# * Thomas Sawyer +# +# == Copying +# +# Copyright (c) 2005 Thomas Sawyer +# +# Ruby License +# +# This module is free software. You may use, modify, and/or redistribute this +# software under the same terms as Ruby. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. + +# +class Numeric + + # = Multipliers + # + # Adds methods to Numeric to make working with + # magnitudes (kilo, mega, giga, milli, micro, etc.) + # + # 1.kilo #=> 1000 + # 1.milli #=> 0.001 + # 1.kibi #=> 1024 + # + # To display a value in a certain denomination, simply + # perform the inverse operation by placing the + # multiplier called on unit (1) in the denominator. + # + # 1000 / 1.kilo #=> 1 + # 1024 / 1.kibi #=> 1 + # + module Multipliers + + # SI Multipliers + + def deka ; self * 10 ; end + def hecto ; self * 100 ; end + def kilo ; self * 1000 ; end + def mega ; self * 1000000 ; end + def giga ; self * 1000000000 ; end + def tera ; self * 1000000000000 ; end + def peta ; self * 1000000000000000 ; end + def exa ; self * 1000000000000000000 ; end + + # SI Fractional + + def deci ; self.to_f / 10 ; end + def centi ; self.to_f / 100 ; end + def milli ; self.to_f / 1000 ; end + def micro ; self.to_f / 1000000 ; end + def nano ; self.to_f / 1000000000 ; end + def pico ; self.to_f / 1000000000000 ; end + def femto ; self.to_f / 1000000000000000 ; end + def atto ; self.to_f / 1000000000000000000 ; end + + # SI Binary + + def kibi ; self * 1024 ; end + def mebi ; self * 1024**2 ; end + def gibi ; self * 1024**3 ; end + def tebi ; self * 1024**4 ; end + def pebi ; self * 1024**5 ; end + def exbi ; self * 1024**6 ; end + + # Bits and Bytes + + #def bit ; self ; end + #def bits ; self ; end + #def byte ; self * 8 ; end + #def bytes ; self * 8 ; end + end + + include Multipliers +end + diff --git a/demo/fish-sampler/meta/active b/demo/fish-sampler/meta/active new file mode 100644 index 0000000..c508d53 --- /dev/null +++ b/demo/fish-sampler/meta/active @@ -0,0 +1 @@ +false diff --git a/demo/fish-sampler/meta/blog b/demo/fish-sampler/meta/blog new file mode 100644 index 0000000..8e1c8b8 --- /dev/null +++ b/demo/fish-sampler/meta/blog @@ -0,0 +1 @@ +http://proutils.github.com diff --git a/demo/fish-sampler/meta/devsite b/demo/fish-sampler/meta/devsite new file mode 100644 index 0000000..a297638 --- /dev/null +++ b/demo/fish-sampler/meta/devsite @@ -0,0 +1 @@ +http://github.com/proutils/webri diff --git a/demo/fish-sampler/meta/homepage b/demo/fish-sampler/meta/homepage new file mode 100644 index 0000000..58bcfa2 --- /dev/null +++ b/demo/fish-sampler/meta/homepage @@ -0,0 +1 @@ +http://proutils.github.com/webri diff --git a/demo/fish-sampler/meta/mailinglist b/demo/fish-sampler/meta/mailinglist new file mode 100644 index 0000000..9b55ea5 --- /dev/null +++ b/demo/fish-sampler/meta/mailinglist @@ -0,0 +1 @@ +http://googlegroups.com/group/proutils diff --git a/demo/fish-sampler/meta/name b/demo/fish-sampler/meta/name new file mode 100644 index 0000000..a4fdad4 --- /dev/null +++ b/demo/fish-sampler/meta/name @@ -0,0 +1 @@ +webri-example diff --git a/demo/fish-sampler/meta/suite b/demo/fish-sampler/meta/suite new file mode 100644 index 0000000..a8ab384 --- /dev/null +++ b/demo/fish-sampler/meta/suite @@ -0,0 +1 @@ +proutils diff --git a/demo/fish-sampler/meta/title b/demo/fish-sampler/meta/title new file mode 100644 index 0000000..573e1a5 --- /dev/null +++ b/demo/fish-sampler/meta/title @@ -0,0 +1 @@ +Fish Sampler diff --git a/demo/fish-sampler/meta/wiki b/demo/fish-sampler/meta/wiki new file mode 100644 index 0000000..c6325c3 --- /dev/null +++ b/demo/fish-sampler/meta/wiki @@ -0,0 +1 @@ +http://proutils.github.com/webri/wiki
razerbeans/webri
c9c60e6b5e14f01ee10714be728994b98f072720
added SDoc notice to COPYING
diff --git a/.gitignore b/.gitignore index 7ba5e3c..9d0f21c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,9 @@ MANIFEST .cache log -pack +pkg doc/rdoc doc/ri doc/webri doc/webri.html work/sandbox diff --git a/COPYING b/COPYING index 9d32d2a..e7f16f9 100644 --- a/COPYING +++ b/COPYING @@ -1,49 +1,74 @@ = WebRI, Copyright (c) 2009 Thomas Sawyer WebRI is partialy based on: + == Darkfish RDoc HTML Generator === Author/s * Michael Granger ([email protected]) === Contributors * Mahlon E. Smith ([email protected]) * Eric Hodel ([email protected]) === License Copyright (c) 2007, 2008, Michael Granger. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author/s, nor the names of the project's contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -== SDoc + +== SDoc - Standalone SDoc Generator === Author/s -* Volkoro +* Vladimir Kolesnikov + +=== Licesne + + Copyright (c) 2009 Vladimir Kolesnikov + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
razerbeans/webri
2d41d39f882151ccafd242ee3044748bb7a41a52
adjust namespaces
diff --git a/lib/webri.rb b/lib/webri.rb index 900a8cc..ebfb538 100644 --- a/lib/webri.rb +++ b/lib/webri.rb @@ -1,46 +1,46 @@ #$:.unshift File.dirname(__FILE__) begin require "rubygems" gem "rdoc", ">= 2.4.2" require "rdoc/rdoc" module WebRI LOADPATH = File.dirname(__FILE__) VERSION = "1.0.0" #:till: VERSION="<%= version %>" end require "rdoc/c_parser_fix" unless defined? $WEBRI_FIXED_RDOC_OPTIONS $WEBRI_FIXED_RDOC_OPTIONS = 1 class RDoc::Options #alias_method :rdoc_initialize, :initialize #def initialize # rdoc_initialize # @generator = RDoc::Generator::RDazzle #end alias_method :rdoc_parse, :parse #FIXME: look up templates dynamically def parse(argv) rdoc_parse(argv) - if %w{redfish twofish foxsocks rubylong}.include?(@template) + if %w{redfish twofish blackfish longfish}.include?(@template) require "webri/generators/#{template}" @generator = WebRI.const_get(@template.capitalize) end end end end rescue Exception warn "WebRI requires RDoc v2.4.2 or greater." end diff --git a/lib/webri/generators/abstract.rb b/lib/webri/generators/abstract.rb new file mode 100644 index 0000000..bf0d263 --- /dev/null +++ b/lib/webri/generators/abstract.rb @@ -0,0 +1 @@ +require 'webri/generators/abstract/generator' diff --git a/lib/webri/generators/abstract/erbtemplate.rb b/lib/webri/generators/abstract/erbtemplate.rb index f2ee2bb..0b562ad 100644 --- a/lib/webri/generators/abstract/erbtemplate.rb +++ b/lib/webri/generators/abstract/erbtemplate.rb @@ -1,120 +1,118 @@ require 'erb' module WebRI -module Abstract # ERBTemplate is used by the generator to build # template files. It has access to all the # the <i>data methods</i> in the generator. class ERBTemplate include ERB::Util include TimeDelta # New ERBTemplate instance. def initialize(generator, provisions) @generator = generator # add component provisions provisions.each do |name, block| (class << self; self; end).class_eval do define_method(name){ |*a,&b| block.call(*a,&b) } end end end # Render a template. def render(template_file, local_assigns={}) template_source = template_file.read erb = ERB.new(template_source, nil, '<>') erb.filename = template_file.to_s local_assigns.each do |key, val| (class << self; self; end).class_eval do define_method(key){ val } end end begin erb_binding = binding #eval code, b erb.result(erb_binding) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ template_file.to_s, err.message, eval("_erbout[-50,50]", erb_binding) ], err.backtrace end end # FIXME: this probably goes not need to double dispatch via generator def include_template(*a,&b) @generator.include_template(*a,&b) end def options ; @generator.options ; end def title ; @generator.title ; end def copyright ; @generator.copyright ; end def class_dir ; @generator.class_dir ; end def file_dir ; @generator.file_dir ; end #def all_classes_and_modules ; @generator.all_classes_and_modules ; end # classes and modules def classes ; @generator.classes ; end def classes_toplevel ; @generator.classes_toplevel ; end def classes_salient ; @generator.classes_salient ; end def classes_hash ; @generator.classes_hash ; end # just modules, no classes def modules ; @generator.modules ; end def modules_toplevel ; @generator.modulews_toplevel ; end def modules_salient ; @generator.modules_salient ; end def modules_hash ; @generator.modules_hash ; end # just classes w/o modules def types ; @generator.types ; end def types_toplevel ; @generator.types_toplevel ; end def types_salient ; @generator.types_salient ; end def types_hash ; @generator.types_hash ; end # def methods_all ; @generator.methods_all ; end # def files ; @generator.files ; end def files_toplevel ; @generator.files_toplevel ; end def files_hash ; @generator.files_hash ; end def find_class_named(*a,&b) ; @generator.find_class_named(*a,&b) ; end def find_module_named(*a,&b) ; @generator.find_module_named(*a,&b) ; end def find_type_named(*a,&b) ; @generator.find_type_named(*a,&b) ; end def find_file_named(*a,&b) ; @generator.find_file_named(*a,&b) ; end # Load and render the erb template with the given +template_name+ within # current context. Adds all +local_assigns+ to context def include_template(template_name, local_assigns={}) #source = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join #eval("#{source}; templatefile = path_template + template_name;eval_template(templatefile, binding)") template_file = @generator.__send__(:path_template) + template_name render(template_file, local_assigns) end # def method_missing(s, *a, &b) if @generator.respond_to?(s) @generator.__send__(s, *a, &b) end end end end -end diff --git a/lib/webri/generators/abstract/generator.rb b/lib/webri/generators/abstract/generator.rb index 359fe62..817f2ba 100644 --- a/lib/webri/generators/abstract/generator.rb +++ b/lib/webri/generators/abstract/generator.rb @@ -1,564 +1,564 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' #require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' require 'webri/extensions/rdoc' require 'webri/extensions/fileutils' require 'webri/generators/abstract/timedelta' require 'webri/generators/abstract/erbtemplate' # module WebRI # = Abstract Generator Base Class # class Generator #include ERB::Util include TimeDelta # # C O N S T A N T S # - PATH = Pathname.new(File.dirname(__FILE__)) + #PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. - PATH_STATIC = PATH + 'abstract/static' + PATH_STATIC = Pathname.new(LOADPATH + 'webri/generators/abstract/static') # Common template directory. - PATH_TEMPLATE = PATH + 'abstract/template' + PATH_TEMPLATE = Pathname.new(LOADPATH + 'webri/generators/abstract/template') # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # TODO: Get from metadata -- use POM if available. def title options.title end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(toplevel_files) @files_toplevel = toplevel_files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static Pathname.new(LOADPATH + "/webri/generators/#{template}/static") #path + '#{template}/static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template p LOADPATH + "webri/generators/#{template}/template" Pathname.new(LOADPATH + "/webri/generators/#{template}/template") #path + '#{template}/template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s show_from = PATH_STATIC.to_s.sub(PATH.parent.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(path.parent.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files_toplevel.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. diff --git a/lib/webri/generators/abstract/timedelta.rb b/lib/webri/generators/abstract/timedelta.rb index a81e95e..bd56ee5 100644 --- a/lib/webri/generators/abstract/timedelta.rb +++ b/lib/webri/generators/abstract/timedelta.rb @@ -1,116 +1,114 @@ module WebRI -module Abstract # module TimeDelta MINUTES = 60 HOURS = 60 * MINUTES DAYS = 24 * HOURS WEEKS = 7 * DAYS MONTHS = 30 * DAYS YEARS = 365.25 * DAYS # Return a string describing the amount of time in the given number of # seconds in terms a human can understand easily. def time_delta_string( seconds ) return 'less than a minute' if seconds < MINUTES return (seconds / MINUTES).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < (50 * MINUTES) return 'about one hour' if seconds < (90 * MINUTES) return (seconds / HOURS).to_s + ' hours' if seconds < (18 * HOURS) return 'one day' if seconds < DAYS return 'about one day' if seconds < (2 * DAYS) return (seconds / DAYS).to_s + ' days' if seconds < WEEKS return 'about one week' if seconds < (2 * WEEKS) return (seconds / WEEKS).to_s + ' weeks' if seconds < (3 * MONTHS) return (seconds / MONTHS).to_s + ' months' if seconds < YEARS return (seconds / YEARS).to_s + ' years' end end end -end =begin # Extend Numeric with time constants class Numeric # :nodoc: # Time constants module TimeConstantMethods # :nodoc: # Number of seconds (returns receiver unmodified) def seconds return self end alias_method :second, :seconds # Returns number of seconds in <receiver> minutes def minutes return self * 60 end alias_method :minute, :minutes # Returns the number of seconds in <receiver> hours def hours return self * 60.minutes end alias_method :hour, :hours # Returns the number of seconds in <receiver> days def days return self * 24.hours end alias_method :day, :days # Return the number of seconds in <receiver> weeks def weeks return self * 7.days end alias_method :week, :weeks # Returns the number of seconds in <receiver> fortnights def fortnights return self * 2.weeks end alias_method :fortnight, :fortnights # Returns the number of seconds in <receiver> months (approximate) def months return self * 30.days end alias_method :month, :months # Returns the number of seconds in <receiver> years (approximate) def years return (self * 365.25.days).to_i end alias_method :year, :years # Returns the Time <receiver> number of seconds before the # specified +time+. E.g., 2.hours.before( header.expiration ) def before( time ) return time - self end # Returns the Time <receiver> number of seconds ago. (e.g., # expiration > 2.hours.ago ) def ago return self.before( ::Time.now ) end # Returns the Time <receiver> number of seconds after the given +time+. # E.g., 10.minutes.after( header.expiration ) def after( time ) return time + self end # Reads best without arguments: 10.minutes.from_now def from_now return self.after( ::Time.now ) end end # module TimeConstantMethods include TimeConstantMethods end =end diff --git a/lib/webri/generators/blackfish.rb b/lib/webri/generators/blackfish.rb new file mode 100644 index 0000000..571c08f --- /dev/null +++ b/lib/webri/generators/blackfish.rb @@ -0,0 +1 @@ +require 'webri/generators/blackfish/generator' diff --git a/lib/webri/generators/longfish.rb b/lib/webri/generators/longfish.rb new file mode 100644 index 0000000..6cd2162 --- /dev/null +++ b/lib/webri/generators/longfish.rb @@ -0,0 +1 @@ +require 'webri/generators/longfish/generator' diff --git a/lib/webri/generators/oldfish.rb b/lib/webri/generators/oldfish.rb new file mode 100644 index 0000000..a20ee08 --- /dev/null +++ b/lib/webri/generators/oldfish.rb @@ -0,0 +1 @@ +require 'webri/generators/oldfish/generator' diff --git a/lib/webri/generators/oldfish/generator.rb b/lib/webri/generators/oldfish/generator.rb index 8b13789..1e7d9e7 100644 --- a/lib/webri/generators/oldfish/generator.rb +++ b/lib/webri/generators/oldfish/generator.rb @@ -1 +1,16 @@ +require 'webri/generators/abstract' +module WebRI + + # = Oldfish Template + # + # This is intended to house the original 4-pane RDoc template design, + # for no other reason than for prosterity. + # + # TODO: Do this. + # + class Oldfish < Generator + + end + +end diff --git a/lib/webri/generators/redfish.rb b/lib/webri/generators/redfish.rb new file mode 100644 index 0000000..e404da2 --- /dev/null +++ b/lib/webri/generators/redfish.rb @@ -0,0 +1 @@ +require 'webri/generators/redfish/generator' diff --git a/lib/webri/generators/redfish/generator.rb b/lib/webri/generators/redfish/generator.rb index 84d30a7..d9f7dc1 100644 --- a/lib/webri/generators/redfish/generator.rb +++ b/lib/webri/generators/redfish/generator.rb @@ -1,24 +1,33 @@ require 'webri/generators/abstract' require 'webri/components/subversion' module WebRI + # = Redfish Template + # + # Redfish is based on RDoc's default Darkfish generator, + # heavily modified to provide only a single sidebar con + # document layout. And, as the name indicates, colorized + # to be red (instead of green). + # + # You can thank Darkfish, a by extension Redfish, for the + # "-fish" naming scheme :) # class Redfish < Generator include Subversion # def path @path ||= Pathname.new(__FILE__).parent end # #def generate_template # super #end end end diff --git a/lib/webri/generators/redfish/static/assets/css/rdoc.css b/lib/webri/generators/redfish/static/assets/css/rdoc.css index 4f2cca3..3400325 100644 --- a/lib/webri/generators/redfish/static/assets/css/rdoc.css +++ b/lib/webri/generators/redfish/static/assets/css/rdoc.css @@ -41,751 +41,754 @@ a { } a:hover { border-bottom: 1px dotted #FF226C; } pre { padding: 0.5em 0; border: 1px solid #ccc; } p { margin: 1em 0; } ul { margin-left: 20px; } .head { width: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 0px solid #aaa; padding: 0 10px; margin: 0 8px 5px 8px; } .head h1 { color: #FF226C; color: #666; font-weight: bold; font-size: 18px; } .head h1 a { color: #FF226C; font-weight: bold; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 0px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ /* body.indexpage { margin: 1em 3em; } */ /* body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } */ #metadata ul { font-size: 14px; } #metadata ul a { font-size: 14px; } /* .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } */ #metadata ul { list-style: none; margin-left: 0; } /* .indexpage ul a, .file #documentation ul a { font-size: 16px; } */ #metadata li { padding-left: 20px; background: url(images/bullet_black.png) no-repeat left 4px; color: #666; } #metadata li.method { padding-left: 20px; background: url(images/method.png) no-repeat left 2px; } #metadata li.module { padding-left: 20px; background: url(images/module.png) no-repeat left 2px; } #metadata li.class { padding-left: 20px; background: url(images/class.png) no-repeat left 2px; } #metadata li.file { padding-left: 20px; background: url(images/file.png) no-repeat left 2px; } /* @end */ /* @group Top-Level Structure */ #metadata { float: left; width: 320px; margin-top: 10px; } #documentation { margin: 0 1em 5em 360px; min-width: 340px; } /* .file #metadata { margin: 0.8em; } */ #validator-badges { clear: both; text-align: left; margin: 1em 1em 2em; font-weight: bold; font-size: 80%; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 0em; } /* .file #project-metadata { margin-top: 0em; } */ #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } /* @end */ /* @group Documentation Section */ #description { font-size: 100%; color: #333; } #description p { margin: 1em 0.4em; } #description ul { margin-left: 2em; } #description ul li { line-height: 1.4em; } #description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } #description dl { font-size: 14px; } #description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } #description dd, #documentation dd { padding: 2px 12px; } #description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h3.section-header { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 150%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-alias { font-style: oblique; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/method.png) no-repeat left bottom; } #documentation .method-heading a { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/alias.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; line-height: 1.2em; color: #666; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .attribute-method-heading { background: url(images/attribute.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ a.source-toggle { font-size: 90%; } a.source-toggle img { } div.method-source-code { background: #262626; background: #F6F6F6; color: #2f2f2f; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: #222; overflow: hidden; } /* @group Ruby keyword styles */ .standalone-code { background: #221111; color: #22dead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; background: transparent; font-weight: bold;} .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } .ruby-constant { color: #70004d; background: transparent; } .ruby-keyword { color: #000000; background: transparent; font-weight: bold;} .ruby-ivar { color: #11448e; background: transparent; } .ruby-operator { color: #ff0022; background: transparent; } .ruby-identifier { color: #00413d; background: transparent; } .ruby-node { color: #001f71; background: transparent; } .ruby-comment { color: #bbbbbb; background: transparent; } .ruby-regexp { color: #001f71; background: transparent; } .ruby-value { color: #70004d; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ .file #documentation { margin: 0; } -.file #metadata, +.file #metadata { + float: left; +} + .file-popup #metadata { float: right; } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #efefef; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(../img/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(../img/date.png) no-repeat left top; } .file dt.requires { background: url(../img/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(../img/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } .file h2 { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 120%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #FF226C; color: #dedede; height:40px; } #TB_title a { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ diff --git a/lib/webri/generators/redfish/template/class.rhtml b/lib/webri/generators/redfish/template/class.rhtml index f29f892..3f9563c 100644 --- a/lib/webri/generators/redfish/template/class.rhtml +++ b/lib/webri/generators/redfish/template/class.rhtml @@ -1,304 +1,304 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= klass.type.capitalize %>: <%= klass.full_name %></title> <% if klass.type == "class" %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/class.png"> <% else %> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/module.png"> <% end %> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> </head> <body class="<%= klass.type %>"> <div class="head"> <h1> <% if klass.type == "class" %> <img src="<%= rel_prefix %>/assets/img/class.png" align="absmiddle">&nbsp; <% else %> <img src="<%= rel_prefix %>/assets/img/module.png" align="absmiddle">&nbsp; <% end %> <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= klass.full_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <div id="file-list-section" class="section"> <h3 class="section-header">In Files</h3> <div class="section-body"> <ul> <% klass.in_files.each do |tl| %> <li class="file"><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785" class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li> <% end %> </ul> </div> </div> <!-- What about Git info, or Hg info? This seems almost silly, albeit kind of cool. --> <!-- TODO: generalize this for all SCMs --> <% if !svninfo(klass).empty? %> <div id="file-svninfo-section" class="section"> <h3 class="section-header">Subversion Info</h3> <div class="section-body"> <dl class="svninfo"> <dt>Rev</dt> <dd><%= svninfo(klass)[:rev] %></dd> <dt>Last Checked In</dt> <dd><%= svninfo(klass)[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> (<%= svninfo(klass)[:commitdelta] %> ago)</dd> <dt>Checked in by</dt> <dd><%= svninfo(klass)[:committer] %></dd> </dl> </div> </div> <% end %> </div> <div id="class-metadata"> <!-- Parent Class --> <% if klass.type == 'class' %> <div id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <ul> <% unless String === klass.superclass %> <!-- why was this class="link" ? --> <li class="class"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></li> <% else %> <li class="class"><%= klass.superclass %></li> <% end %> </ul> </div> <% end %> <!-- Namespace Contents --> <% unless klass.classes_and_modules.empty? %> <div id="namespace-list-section" class="section"> <h3 class="section-header">Namespace</h3> <ul class="link-list"> <% (klass.modules.sort + klass.classes.sort).each do |mod| %> <li class="<%= klass.type %>"><a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li> <% end %> </ul> </div> <% end %> <!-- Method Quickref --> <% unless klass.method_list.empty? %> <div id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <% klass.each_method do |meth| %> <li class="method"><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li> <% end %> </ul> </div> <% end %> <!-- Included Modules --> <% unless klass.includes.empty? %> <div id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <% klass.each_include do |inc| %> <% unless String === inc.module %> <li class="module"><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li> <% else %> <li class="module"><span class="include"><%= inc.name %></span></li> <% end %> <% end %> </ul> </div> <% end %> </div> <div id="project-metadata"> <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |file| %> <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <!-- classpage.html : classes --> <ul class="link-list"> - <% tree.modules_salient.each do |index_klass| %> + <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right;"><img src="<%= rel_prefix %>/assets/img/bug.png" alt="toggle debugging" height="16" width="16" /></div> <% end %> Generated with <a href="http://github.com/proutils/webri">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> <div id="documentation"> <div id="description"> <% if /\s*\<h1\>/ !~ klass.description %> <h1><%= klass.name %></h1> <% end %> <%= klass.description %> </div> <!-- Constants --> <% unless klass.constants.empty? %> <div id="constants-list" class="section"> <h3 class="section-header">Constants</h3> <dl> <% klass.each_constant do |const| %> <dt><a name="<%= const.name %>"><%= const.name %></a></dt> <% if const.comment %> <dd class="description"><%= const.description.strip %></dd> <% else %> <dd class="description missing-docs">(Not documented)</dd> <% end %> <% end %> </dl> </div> <% end %> <!-- Attributes --> <% unless klass.attributes.empty? %> <div id="attribute-method-details" class="method-section section"> <h3 class="section-header">Attributes</h3> <% klass.each_attribute do |attrib| %> <div id="<%= attrib.html_name %>-attribute-method" class="method-detail"> <a name="<%= h attrib.name %>"></a> <% if attrib.rw =~ /w/i %> <a name="<%= h attrib.name %>="></a> <% end %> <div class="method-heading attribute-method-heading"> <span class="method-name"><%= h attrib.name %></span><span class="attribute-access-type">[<%= attrib.rw %>]</span> </div> <div class="method-description"> <% if attrib.comment %> <%= attrib.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> </div> </div> <% end %> </div> <% end %> <!-- Methods --> <% klass.methods_by_type.each do |type, visibilities| next if visibilities.empty? visibilities.each do |visibility, methods| next if methods.empty? %> <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section"> <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3> <% methods.each do |method| %> <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>"> <a name="<%= h method.aref %>"></a> <div class="method-heading"> <% if method.call_seq %> <span class="method-callseq"><%= method.call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w.*?\./m, '') %></span> <span class="method-click-advice">click to toggle source</span> <% else %> <span class="method-name"><%= h method.name %></span><span class="method-args"><%= method.params %></span> <span class="method-click-advice">click to toggle source</span> <% end %> </div> <div class="method-description"> <% if method.comment %> <%= method.description.strip %> <% else %> <p class="missing-docs">(Not documented)</p> <% end %> <% if method.token_stream %> <div class="method-source-code" id="<%= method.html_name %>-source"> <pre> <%= method.markup_code %> </pre> </div> <% end %> </div> <% unless method.aliases.empty? %> <div class="aliases"> Also aliased as: <%= method.aliases.map do |aka| %{<a href="#{ klass.aref_to aka.path}">#{h aka.name}</a>} end.join(", ") %> </div> <% end %> </div> <% end %> </div> <% end end %> </div> <div id="rdoc-debugging-section-dump" class="debugging-section"> <% if $DEBUG_RDOC require 'pp' %> <pre><%= h PP.pp(klass, _erbout) %></pre> </div> <% else %> <p>Disabled; run with --debug to generate this.</p> <% end %> </div> </body> </html> diff --git a/lib/webri/generators/redfish/template/file.rhtml b/lib/webri/generators/redfish/template/file.rhtml index 1703b0a..f8af213 100644 --- a/lib/webri/generators/redfish/template/file.rhtml +++ b/lib/webri/generators/redfish/template/file.rhtml @@ -1,125 +1,125 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title>File: <%= file.base_name %> [<%= options.title %>]</title> <link rel="SHORTCUT ICON" href="<%= rel_prefix %>/assets/img/file.png"> <link type="text/css" media="screen" rel="stylesheet" href="<%= rel_prefix %>/assets/css/rdoc.css" /> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="<%= rel_prefix %>/assets/js/darkfish.js"></script> </head> <% if file.parser == RDoc::Parser::Simple %> <body class="file"> <div class="head"> <h1> <img src="<%= rel_prefix %>/assets/img/file.png" align="absmiddle">&nbsp; <a href="<%= rel_prefix %>/index.html"><%= h options.title %></a>&nbsp; <a href="/"><%= file.base_name %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="<%= rel_prefix %>/assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> - <% tree.modules_salient.each do |index_klass| %> + <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right;"> <img src="<%= rel_prefix %>/assets/img/bug.png" alt="toggle debugging" height="16" width="16" /> </div> <% end %> Generated with <a href="http://github.com/proutils/rdazzle">WebRI Redfish</a> <%= WebRI::VERSION %> <br/><br/> <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> <div id="documentation"> <%= file.description %> </div> </body> <% else %> <body class="file file-popup"> <div id="metadata"> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date"><%= file.last_modified %></dd> <% if file.requires %> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <% file.requires.each do |require| %> <li><%= require.name %></li> <% end %> </ul> </dd> <% end %> <% if options.webcvs %> <dt class="scs-url">Trac URL</dt> <dd class="scs-url"><a target="_top" href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd> <% end %> </dl> </div> <div id="documentation"> <% if file.comment %> <div class="description"> <%= file.description %> </div> <% end %> </div> </body> <% end %> </html> diff --git a/lib/webri/generators/redfish/template/index.rhtml b/lib/webri/generators/redfish/template/index.rhtml index b5166a8..612601e 100644 --- a/lib/webri/generators/redfish/template/index.rhtml +++ b/lib/webri/generators/redfish/template/index.rhtml @@ -1,143 +1,143 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=<%= options.charset %>" http-equiv="Content-Type" /> <title><%= h options.title %></title> <link rel="SHORTCUT ICON" href="assets/img/ruby.png"> <script type="text/javascript" charset="utf-8" src="assets/js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/thickbox.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/quicksearch.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/darkfish.js"></script> <script type="text/javascript" charset="utf-8" src="assets/js/highlight.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#documentation pre').wrapInner('<code></code>'); hljs.tabReplace = ' '; hljs.initHighlightingOnLoad('ruby'); }); </script> <link type="text/css" rel="stylesheet" href="assets/css/rdoc.css" media="screen" /> <link type="text/css" rel="stylesheet" href="assets/js/github.css" title="GitHub" /> <% $stderr.sync = true %> </head> <body class="indexpage"> <div class="head"> <h1> <img src="assets/img/project.png" align="absmiddle">&nbsp; <a href="index.html"><%= h options.title %></a> </h1> </div> <div id="metadata"> <div id="project-metadata"> <% simple_files = files.select { |f| f.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <div id="fileindex-section" class="section project-section"> <h3 class="section-header">Files</h3> <ul> <% simple_files.each do |f| %> <li class="file"><a href="<%= f.path %>"><%= h f.base_name %></a></li> <% end %> </ul> </div> <% end %> <div id="classindex-section" class="section project-section"> <h3 class="section-header">Class Index <span class="search-toggle"><img src="assets/img/find.png" height="16" width="16" alt="[+]" title="show/hide quicksearch" /></span></h3> <form action="#" method="get" accept-charset="utf-8" class="initially-hidden"> <fieldset> <legend>Quicksearch</legend> <input type="text" name="quicksearch" value="" class="quicksearch-field" /> </fieldset> </form> <ul class="link-list"> - <% tree.modules_salient.each do |index_klass| %> + <% classes_salient.each do |index_klass| %> <li class="<%= index_klass.type %>"><a href="<%= index_klass.path %>"><%= index_klass.full_name %></a></li> <% end %> </ul> <div id="no-class-search-results" style="display: none;">No matching classes.</div> </div> <!-- METHODS --> <div id="methodindex-section" class="section project-section"> <h3 class="section-header">Method Index</h3> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li class="method" style="clear: both;"> <span style="float: right; font-size: 0.8em;">&nbsp;<%= method.parent.full_name %></span> <a href="<%= method.path %>"><%= method.pretty_name %></a> </li> <% end %> </ul> </div> </div> <div id="validator-badges"> <% if $DEBUG_RDOC %> <div id="debugging-toggle" style="float: right;"><img src="assets/img/bug.png" alt="toggle debugging" height="16" width="16" /></div> <% end %> Generated with <a href="http://github.com/proutils/webri">WebRI RedFish</a> <%= WebRI::VERSION %> <br/><br/> <a href="http://validator.w3.org/check/referer">[Validate]</a> </div> </div> <!-- <% simple_files = files.select {|tl| tl.parser == RDoc::Parser::Simple } %> <% unless simple_files.empty? then %> <h2>Files</h2> <ul> <% simple_files.sort.each do |file| %> <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li> <% end %> </ul> <% end %> <h2>Classes/Modules</h2> <ul> - <% tree.modules_salient.each do |klass| %> + <% classes_salient.each do |klass| %> <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li> <% end %> </ul> <h2>Methods</h2> <ul> <% RDoc::TopLevel.all_classes_and_modules.map do |mod| mod.method_list end.flatten.sort.each do |method| %> <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li> <% end %> </ul> --> <% if options.main_page && main_page = files.find { |f| f.full_name == options.main_page } %> <div id="documentation"> <%= main_page.description %> </div> <% else %> <p>This is the API documentation for '<%= options.title %>'.</p> <% end %> </body> </html> diff --git a/lib/webri/generators/twofish.rb b/lib/webri/generators/twofish.rb new file mode 100644 index 0000000..4bf6a5d --- /dev/null +++ b/lib/webri/generators/twofish.rb @@ -0,0 +1 @@ +require 'webri/generators/twofish/generator' diff --git a/lib/webri/generators/twofish/generator.rb b/lib/webri/generators/twofish/generator.rb index adcada5..3e08584 100644 --- a/lib/webri/generators/twofish/generator.rb +++ b/lib/webri/generators/twofish/generator.rb @@ -1,116 +1,123 @@ require 'webri/generators/abstract' require 'webri/components/subversion' module WebRI + # = Twofish Template + # + # The Twofish template is a two pane layout, providing + # a navigation pane on the left and a document pane to + # the right. The navigation pane presents a collapsable + # namespace tree which updates the document pane, an iframe, + # via targeted a href links. # class Twofish < Generator include Subversion # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :html_tree end # #def generate_template # super #end #<ul> # <li class="trigger"> # <img src="assets/img/class.png" onClick="showBranch(this);"/> # # <span class="link" path="__path__" onClick="lookup_static(this);">__entry.name__</span> # # <div class="branch"> # <ul> # <li class="meta_leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # <ul> # <li class="leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # </li> #</ul> # def html_tree #%[<iframe src="tree.html"></iframe>] @html_tree ||= ( %[<div class="root">] + generate_html_tree(classes_toplevel) + %[</div>] #heirarchy) #heirarchy.to_html ) end # generate html tree # def generate_html_tree(classes) markup = ["<ul>"] classes = classes.sort{ |a,b| a.full_name <=> b.full_name } classes.each do |entry| path = entry.path #WebRI.entry_to_path(entry.full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <a class="link" href="#{path}" target="main">#{entry.name}</a> ] markup << %[<div class="branch">] markup << %[<ul>] cmethods, imethods = *entry.method_list.partition{ |m| m.singleton } cmethods = cmethods.sort{ |a,b| a.name <=> b.name } cmethods.each do |method| path = method.path #entry.full_name + ".#{method.name}" #WebRI.entry_to_path(entry.full_name + ".#{method}") markup << %[ <li class="meta_leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end imethods = imethods.sort{ |a,b| a.name <=> b.name } imethods.each do |method| path = method.path #WebRI.entry_to_path(entry.full_name + "##{method}") markup << %[ <li class="leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end #entry.classes.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << generate_html_tree(entry.classes_and_modules) if entry.classes #end markup << %[</ul>] #if entry.root? # markup << %[</div>] #else markup << %[</div>] markup << %[</li>] #end end markup << "</ul>" return markup.join("\n") end end end#module WebRI
razerbeans/webri
1e894661435289fd6c17ac5003d5b72e2fadd446
rearrange lib layout by class types
diff --git a/lib/webri.rb b/lib/webri.rb index 93d5585..900a8cc 100644 --- a/lib/webri.rb +++ b/lib/webri.rb @@ -1,47 +1,46 @@ #$:.unshift File.dirname(__FILE__) begin require "rubygems" gem "rdoc", ">= 2.4.2" require "rdoc/rdoc" module WebRI LOADPATH = File.dirname(__FILE__) VERSION = "1.0.0" #:till: VERSION="<%= version %>" end require "rdoc/c_parser_fix" - #require "webri/generator/rdazzle" unless defined? $WEBRI_FIXED_RDOC_OPTIONS $WEBRI_FIXED_RDOC_OPTIONS = 1 class RDoc::Options #alias_method :rdoc_initialize, :initialize #def initialize # rdoc_initialize # @generator = RDoc::Generator::RDazzle #end alias_method :rdoc_parse, :parse #FIXME: look up templates dynamically def parse(argv) rdoc_parse(argv) if %w{redfish twofish foxsocks rubylong}.include?(@template) - require "webri/#{template}/generator" + require "webri/generators/#{template}" @generator = WebRI.const_get(@template.capitalize) end end end end rescue Exception warn "WebRI requires RDoc v2.4.2 or greater." end diff --git a/lib/webri/abstract/commons.rb b/lib/webri/abstract/commons.rb deleted file mode 100644 index 7742eab..0000000 --- a/lib/webri/abstract/commons.rb +++ /dev/null @@ -1,31 +0,0 @@ -module WebRI - - module Abstract - - module Commons - - # - # TODO: options = { :verbose => $DEBUG_RDOC, :noop => $dryrun } - - def fileutils - $dryrun ? FileUtils::DryRun : FileUtils - end - - # Output progress information if debugging is enabled - - def debug_msg(msg) - return unless $DEBUG_RDOC - case msg[-1,1] - when '.' then tab = "= " - when ':' then tab = "== " - else tab = "* " - end - $stderr.puts(tab + msg) - end - - end - - end - -end - diff --git a/lib/webri/abstract/component.rb b/lib/webri/abstract/component.rb deleted file mode 100644 index d6861fa..0000000 --- a/lib/webri/abstract/component.rb +++ /dev/null @@ -1,108 +0,0 @@ -module WebRI - - module Abstract - - # = Abstract Generator Component - # - class Component - - include Commons - - # - - attr :generator - - # New component instance. Components require the generator - # they are augmenting. - - def initialize(generator) - @generator = generator - initialize_methods - end - - # Path to the component. This should be defined in the - # subclass as: - # - # def path - # @path ||= Pathname.new(__FILE__).parent - # end - # - def path - raise "Must be implemented by subclass!" - end - - # Subcomponents use this to setup template provisions. - # - # def initialize_methods - # provide :svninfo - # end - # - # See the #provide method. - - def initialize_methods - end - - # This is the method that is called by the generator, - # allowing the component in turn to generate the - # files it needs. By default this copies the components - # <tt>static</tt> directory. - - def generate - generate_static - end - - # Copy static files to output. All the common static content is - # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> - # directory more or less follows an <i>Abbreviated Monash</i> convention: - # - # assets/ - # css/ <- stylesheets - # json/ <- json data table (*maybe top level is better?) - # img/ <- images - # inc/ <- server-side includes - # js/ <- javascripts - # - # Components can utilize this method by providing a +path+. - - def generate_static - from = Dir[(path_static + '**').to_s] - dest = path_output.to_s - show_from = path_static.to_s.sub(path.parent.to_s+'/', '') - debug_msg "Copying #{show_from}/** to #{path_output_relative}:" - fileutils.cp_r from, dest, :preserve => true - end - - # - - def method_missing(s, *a, &b) - generator.__send__(s,*a,&b) - end - - # - - def path_static - path + 'static' - end - - # Provide a method interface(s) to the generator. This extends - # the generator's context with component methods. Since - # ERB templates are rendering in the generator scope, this - # is useful when a component needs to provide method access - # to templates. - - def provision(method, &block) - if block - generator.provision(method, &block) - else - generator.provision(method) do |*a, &b| - __send__(method, *a, &b) - end - end - end - - end - - end - -end - diff --git a/lib/webri/components/abstract.rb b/lib/webri/components/abstract.rb new file mode 100644 index 0000000..e9499a1 --- /dev/null +++ b/lib/webri/components/abstract.rb @@ -0,0 +1,114 @@ +module WebRI + + # = Abstract Generator Component + # + class Component + + # + + attr :generator + + # New component instance. Components require the generator + # they are augmenting. + + def initialize(generator) + @generator = generator + initialize_methods + end + + # Path to the component. This should be defined in the + # subclass as: + # + # def path + # @path ||= Pathname.new(__FILE__).parent + # end + # + def path + raise "Must be implemented by subclass!" + end + + # Subcomponents use this to setup template provisions. + # + # def initialize_methods + # provide :svninfo + # end + # + # See the #provide method. + + def initialize_methods + end + + # This is the method that is called by the generator, + # allowing the component in turn to generate the + # files it needs. By default this copies the components + # <tt>static</tt> directory. + + def generate + generate_static + end + + # Copy static files to output. All the common static content is + # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> + # directory more or less follows an <i>Abbreviated Monash</i> convention: + # + # assets/ + # css/ <- stylesheets + # json/ <- json data table (*maybe top level is better?) + # img/ <- images + # inc/ <- server-side includes + # js/ <- javascripts + # + # Components can utilize this method by providing a +path+. + + def generate_static + from = Dir[(path_static + '**').to_s] + dest = path_output.to_s + show_from = path_static.to_s.sub(path.parent.to_s+'/', '') + debug_msg "Copying #{show_from}/** to #{path_output_relative}:" + fileutils.cp_r from, dest, :preserve => true + end + + # + + def method_missing(s, *a, &b) + generator.__send__(s,*a,&b) + end + + # + + def path_static + path + 'static' + end + + # Provide a method interface(s) to the generator. This extends + # the generator's context with component methods. Since + # ERB templates are rendering in the generator scope, this + # is useful when a component needs to provide method access + # to templates. + + def provision(method, &block) + if block + generator.provision(method, &block) + else + generator.provision(method) do |*a, &b| + __send__(method, *a, &b) + end + end + end + + # Output progress information if rdoc debugging is enabled + + def debug_msg(msg) + return unless $DEBUG_RDOC + case msg[-1,1] + when '.' then tab = "= " + when ':' then tab = "== " + else tab = "* " + end + $stderr.puts(tab + msg) + end + + end + +end + diff --git a/lib/webri/components/github/component.rb b/lib/webri/components/github.rb similarity index 96% rename from lib/webri/components/github/component.rb rename to lib/webri/components/github.rb index fbbbdef..d494868 100644 --- a/lib/webri/components/github/component.rb +++ b/lib/webri/components/github.rb @@ -1,105 +1,105 @@ -require 'webri/abstract/component' +require 'webri/components/abstract' module WebRI # - class GitHub < Abstract::Component + class GitHub < Component # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :github_url end # #def generate # path = PATH_TEMPLATE + 'template/assets' # dest = path_output + 'assets' # debug_msg "Copying #{path}/** to #{dest}/**" # fileutils.cp_r path.to_s, dest.to_s, :preserve => true #end # def github_url(path) unless github_url_cache.has_key? path github_url_cache[path] = false file = RDoc::TopLevel.find_file_named(path) if file base_url = repository_url(path) if base_url sha1 = commit_sha1(path) if sha1 relative_url = path_relative_to_repository(path) github_url_cache[path] = "#{base_url}#{sha1}#{relative_url}" end end end end github_url_cache[path] end # def github_url_cache @github_url_cache ||= {} end # #def path_base # generator.path_base #end protected def commit_sha1(path) name = File.basename(path) s = in_dir(File.join(path_base, File.dirname(path))) do `git log -1 --pretty=format:"commit %H" #{name}` end m = s.match(/commit\s+(\S+)/) m ? m[1] : false end def repository_url(path) s = in_dir(File.join(path_base, File.dirname(path))) do `git config --get remote.origin.url` end m = s.match(%r{github.com[/:](.*)\.git$}) m ? "http://github.com/#{m[1]}/blob/" : false end def path_relative_to_repository(path) absolute_path = File.join(path_base, path) root = path_to_git_dir(File.dirname(absolute_path)) absolute_path[root.size..absolute_path.size] end def path_to_git_dir(path) while !path.empty? && path != '.' if (File.exists? File.join(path, '.git')) return path end path = File.dirname(path) end '' end def in_dir(dir) pwd = Dir.pwd Dir.chdir dir return yield rescue Exception => e return '' ensure Dir.chdir pwd end end end diff --git a/lib/webri/components/jsonfile/component.rb b/lib/webri/components/jsonfile.rb similarity index 98% rename from lib/webri/components/jsonfile/component.rb rename to lib/webri/components/jsonfile.rb index 5e47d6e..0d3c97a 100644 --- a/lib/webri/components/jsonfile/component.rb +++ b/lib/webri/components/jsonfile.rb @@ -1,180 +1,181 @@ -module WebRI +require 'webri/components/abstract' + - require 'webri/abstract/component' +module WebRI # TODO: This component is not finished. The actual json produced # needs to be fleshed out more, making sure we have all the data # we want in there, and theat it is layedout in the optimal structure. # # TODO: RDoc has some json related stuff going on. I found # RDoc::TopLevel.json_creatable?, so maybe there's a much better # wat to do this component. - class JSONFile < Abstract::Component + class JSONFile < Component # Save as json. def generate puts RDoc::TopLevel.json_creatable? puts RDoc::TopLevel.to_json save_data(class_tree, 'classes.json') save_data(file_tree , 'files.json') save_data(methods , 'methods.json') end # Save class tree def save_data(data, file) debug_msg "writing data to %s" % file File.open(file, "w", 0644) do |f| f.write(data.to_json) end unless $dryrun end # -- CLASS/MODULES ---------------------------------------------------- def classes generator.all_classes_and_modules end # Build class/module namespace tree structure. def class_tree @class_tree ||= generate_class_tree end def generate_class_tree debug_msg "Generating class tree:" topclasses = classes.select {|klass| !(RDoc::ClassModule === klass.parent) } generate_class_tree_level(topclasses) end # Recursivly build class/module namespace tree structure def generate_class_tree_level(classes) tree = [] list = classes.select{|c| c.with_documentation? } list = list.sort list.each do |c| item = c.to_h item[:methods] = c.method_list.map{ |m| m.to_h } item[:classes] = generate_class_tree_level(c.classes_and_modules) tree << item end tree end # Recursivly build class tree structure #def generate_class_tree_level(classes) # tree = [] # list = classes.select{|c| c.with_documentation? } # list = list.sort # list.each do |c| # item = [ # c.name, # c.document_self_or_methods ? c.path : '', # c.module? ? '' : (c.superclass ? " < #{String === c.superclass ? c.superclass : c.superclass.full_name}" : ''), # generate_class_tree_level(c.classes_and_modules) # ] # tree << item # end # tree #end # -- FILES ------------------------------------------------------ def files generator.files end def file_tree @file_tree ||= generate_file_tree end # def generate_file_tree debug_msg "Generating file tree:" return {} if files.empty? ftree = {} files.each do |file| path = file.full_name generate_file_tree_level(path, file, ftree) end ftree end def generate_file_tree_level(path, file, tree) parent, *subpath = *path.split(File::SEPARATOR) subpath = subpath.join(File::SEPARATOR) tree[parent] ||= {} e = tree[parent] e[:name] = parent if subpath.empty? e.merge!(file.to_h) else e[:files] ||= {} generate_file_tree_level(subpath, file, e[:files]) end end =begin # def generate_file_tree debug_msg "Generating file tree:" if @files.length > 1 @files_tree = FilesTree.new @files.each do |file| @files_tree.add(file.relative_name, file.path) end generate_file_tree_level(@files_tree) else [] end end # def generate_file_tree_level(tree) tree.children.keys.sort.map do |name| child = tree.children[name] if String === child [name, child, '', []] else ['', '', name, generate_file_tree_level(child)] end end end class FilesTree attr_reader :children def add(path, url) path = path.split(File::SEPARATOR) unless Array === path @children ||= {} if path.length == 1 @children[path.first] = url else @children[path.first] ||= FilesTree.new @children[path.first].add(path[1, path.length], url) end end end =end # -- METHODS ---------------------------------------------------- # All methods. def all_methods @methods ||= ( list = [] classes.map do |mod| mod.method_list.each do |method| list << method end end list ) end end end diff --git a/lib/webri/components/metadata/component.rb b/lib/webri/components/metadata.rb similarity index 95% rename from lib/webri/components/metadata/component.rb rename to lib/webri/components/metadata.rb index 282ca45..f43bec9 100644 --- a/lib/webri/components/metadata/component.rb +++ b/lib/webri/components/metadata.rb @@ -1,63 +1,64 @@ +require 'webri/components/abstract' require 'ostruct' module WebRI # - class Metadata < Abstract::Component + class Metadata < Component # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :metadata end # def metadata @metadata ||= get_metadata end # def get_metadata data = OpenStruct.new begin require 'pom/metadata' pom = POM::Metadata.load(path_base) raise LoadError unless pom.name data.title = pom.title data.homepage = pom.homepage data.development = pom.development data.mailinglist = pom.mailinglist data.forum = pom.forum data.wiki = pom.wiki data.blog = pom.blog data.copyright = pom.copyright rescue LoadError if file = Dir[path_base + '*.gemspec'].first gem = YAML.load(file) data.title = gem.title date.homepage = gem.homepage data.mailinglist = gem.email date.development = nil # TODO: how to improve? data.forum = nil data.wiki = nil data.blog = nil data.copyright = nil else # TODO: we may be able to develop some other hueristics here, but for now, nope. end end return data end def scm Dir[File.join(path_base.to_s,"{.svn,.git}")].first end end end diff --git a/lib/webri/components/quicksearch/component.rb b/lib/webri/components/quicksearch.rb similarity index 98% rename from lib/webri/components/quicksearch/component.rb rename to lib/webri/components/quicksearch.rb index 100a88c..bcc476a 100644 --- a/lib/webri/components/quicksearch/component.rb +++ b/lib/webri/components/quicksearch.rb @@ -1,234 +1,234 @@ -require 'webri/abstract/component' +require 'webri/components/abstract' require 'iconv' module WebRI # - class QuickSearch < Abstract::Component + class QuickSearch < Component # SEARCH_TREE_FILE = 'search_tree.js' # SEARCH_INDEX_FILE = 'search_index.js' # Used in js to reduce index sizes TYPE_CLASS = 1 TYPE_METHOD = 2 TYPE_FILE = 3 # def path @path ||= Pathname.new(File.dirname(__FILE__)) end # Generate class tree and serach index. def generate generate_static generate_search_tree generate_search_index end # Create class tree structure and write it as json def generate_search_tree debug_msg "Generating Class Tree:" topclasses = classes.select {|klass| !(RDoc::ClassModule === klass.parent) } tree = generate_file_tree + generate_search_tree_level(topclasses) debug_msg "writing class tree to %s" % SEARCH_TREE_FILE File.open(SEARCH_TREE_FILE, "w", 0644) do |f| f.write('var tree = '); f.write(tree.to_json) end unless $dryrun end # Recursivly build class tree structure def generate_search_tree_level(classes) tree = [] classes.select{|c| c.with_documentation? }.sort.each do |klass| item = [ klass.name, klass.document_self_or_methods ? klass.path : '', klass.module? ? '' : (klass.superclass ? " < #{String === klass.superclass ? klass.superclass : klass.superclass.full_name}" : ''), generate_search_tree_level(klass.classes_and_modules) ] tree << item end tree end # Create search index for all classes, methods and files # Write as json. def generate_search_index debug_msg "Generating Search Index:" index = { :searchIndex => [], :longSearchIndex => [], :info => [] } add_class_search_index(index) add_method_search_index(index) add_file_search_index(index) debug_msg "writing search index to %s" % SEARCH_INDEX_FILE data = { :index => index } File.open(SEARCH_INDEX_FILE, "w", 0644) do |f| f.write('var search_data = '); f.write(data.to_json) end unless $dryrun end # Add files to search +index+ array. def add_file_search_index(index) debug_msg "generating file search index" files.select { |file| file.document_self }.sort.each do |file| index[:searchIndex].push( search_string(file.name) ) index[:longSearchIndex].push( search_string(file.path) ) index[:info].push([ file.name, file.path, file.path, '', snippet(file.comment), TYPE_FILE ]) end end # Add classes to search +index+ array. def add_class_search_index(index) debug_msg "generating class search index" classes.select { |klass| klass.document_self_or_methods }.sort.each do |klass| modulename = klass.module? ? '' : (klass.superclass ? (String === klass.superclass ? klass.superclass : klass.superclass.full_name) : '') index[:searchIndex].push( search_string(klass.name) ) index[:longSearchIndex].push( search_string(klass.parent.full_name) ) index[:info].push([ klass.name, klass.parent.full_name, klass.path, modulename ? " < #{modulename}" : '', snippet(klass.comment), TYPE_CLASS ]) end end # Add methods to search +index+ array. def add_method_search_index(index) debug_msg "generating method search index" list = classes.map { |klass| klass.method_list }.flatten.sort{ |a, b| a.name == b.name ? a.parent.full_name <=> b.parent.full_name : a.name <=> b.name }.select { |method| method.document_self } unless options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end list.each do |method| index[:searchIndex].push( search_string(method.name) + '()' ) index[:longSearchIndex].push( search_string(method.parent.full_name) ) index[:info].push([ method.name, method.parent.full_name, method.path, method.params, snippet(method.comment), TYPE_METHOD ]) end end # Build search index key. def search_string(string) string ||= '' string.downcase.gsub(/\s/,'') end # def generate_file_tree if files.length > 1 @files_tree = FilesTree.new files.each do |file| @files_tree.add(file.relative_name, file.path) end [['', '', 'files', generate_file_tree_level(@files_tree)]] else [] end end # def generate_file_tree_level(tree) tree.children.keys.sort.map do |name| child = tree.children[name] if String === child [name, child, '', []] else ['', '', name, generate_file_tree_level(child)] end end end # class FilesTree attr_reader :children def add(path, url) path = path.split(File::SEPARATOR) unless Array === path @children ||= {} if path.length == 1 @children[path.first] = url else @children[path.first] ||= FilesTree.new @children[path.first].add(path[1, path.length], url) end end end # Strip comments on a space after 100 chars def snippet(str) str ||= '' if str =~ /^(?>\s*)[^\#]/ content = str else content = str.gsub(/^\s*(#+)\s*/, '') end content = content.sub(/^(.{100,}?)\s.*/m, "\\1").gsub(/\r?\n/m, ' ') begin content.to_json rescue # might fail on non-unicode string begin # remove all non-unicode chars content = Iconv.conv('latin1//ignore', "UTF8", content) content.to_json rescue content = '' # something hugely wrong happend end end content end end end diff --git a/lib/webri/components/subversion/component.rb b/lib/webri/components/subversion.rb similarity index 94% rename from lib/webri/components/subversion/component.rb rename to lib/webri/components/subversion.rb index 6e794bb..7d58eb1 100644 --- a/lib/webri/components/subversion/component.rb +++ b/lib/webri/components/subversion.rb @@ -1,66 +1,65 @@ -require 'webri/abstract/component' +require 'webri/components/abstract' module WebRI # - class Subversion < Abstract::Component - + class Subversion < Component # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :svninfo end # def svninfo(klass) @svninfo ||= {} @svninfo[klass] ||= get_svninfo(klass) end # Try to extract Subversion information out of the first constant whose value looks like # a subversion Id tag. If no matching constant is found, and empty hash is returned. def get_svninfo(klass) constants = klass.constants or return {} constants.find {|c| c.value =~ SVNID_PATTERN } or return {} filename, rev, date, time, committer = $~.captures commitdate = Time.parse( date + ' ' + time ) return { :filename => filename, :rev => Integer( rev ), :commitdate => commitdate, :commitdelta => time_delta_string( Time.now.to_i - commitdate.to_i ), :committer => committer, } end # Subversion rev #SVNRev = %$Rev: 52 $ # Subversion ID #SVNId = %$Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $ # SVNID_PATTERN = / \$Id:\s (\S+)\s # filename (\d+)\s # rev (\d{4}-\d{2}-\d{2})\s # Date (YYYY-MM-DD) (\d{2}:\d{2}:\d{2}Z)\s # Time (HH:MM:SSZ) (\w+)\s # committer \$$ /x end end diff --git a/lib/webri/extensions/fileutils.rb b/lib/webri/extensions/fileutils.rb new file mode 100644 index 0000000..18ade75 --- /dev/null +++ b/lib/webri/extensions/fileutils.rb @@ -0,0 +1,9 @@ +require 'fileutils' + +# +# TODO: options = { :verbose => $DEBUG_RDOC, :noop => $dryrun } + +def fileutils + $dryrun ? FileUtils::DryRun : FileUtils +end + diff --git a/lib/webri/abstract/rdoc.rb b/lib/webri/extensions/rdoc.rb similarity index 100% rename from lib/webri/abstract/rdoc.rb rename to lib/webri/extensions/rdoc.rb diff --git a/lib/webri/abstract/generator.rb b/lib/webri/generators/abstract.rb similarity index 96% rename from lib/webri/abstract/generator.rb rename to lib/webri/generators/abstract.rb index 23a2e53..9efc7f0 100644 --- a/lib/webri/abstract/generator.rb +++ b/lib/webri/generators/abstract.rb @@ -1,646 +1,657 @@ #begin # # requiroing rubygems is needed here b/c ruby comes with # # rdoc but it's not the latest version. # require 'rubygems' # #gem 'rdoc', '>= 2.4' unless ENV['RDOC_TEST'] or defined?($rdoc_rakefile) # gem "rdoc", ">= 2.4.2" #rescue #end if Gem.available? "json" gem "json", ">= 1.1.3" else gem "json_pure", ">= 1.1.3" end require 'json' require 'pp' require 'pathname' -require 'fileutils' +#require 'fileutils' require 'yaml' require 'rdoc/rdoc' require 'rdoc/generator' require 'rdoc/generator/markup' -require 'webri/abstract/rdoc' +require 'webri/extensions/rdoc' +require 'webri/extensions/fileutils' -require 'webri/abstract/commons' -require 'webri/abstract/timedelta' -require 'webri/abstract/erbtemplate' +require 'webri/generators/abstract/timedelta' +require 'webri/generators/abstract/erbtemplate' # -module WebRI::Abstract +module WebRI - # Generator base class. + # = Abstract Generator Base Class # class Generator #include ERB::Util - include Commons include TimeDelta # # C O N S T A N T S # PATH = Pathname.new(File.dirname(__FILE__)) # Common template directory. PATH_STATIC = PATH + 'static' # Common template directory. PATH_TEMPLATE = PATH + 'template' # Directory where generated classes live relative to the root DIR_CLASS = 'classes' # Directory where generated files live relative to the root DIR_FILE = 'files' # Directory where static assets are located in the template DIR_ASSETS = 'assets' # # C L A S S M E T H O D S # #::RDoc::RDoc.add_generator(self) def self.inherited(base) ::RDoc::RDoc.add_generator(base) end # def self.include(*mods) comps, mods = *mods.partition{ |m| m < Component } components.concat(comps) super(*mods) end # def self.components @components ||= [] end # Standard generator factory method. def self.for(options) new(options) end # # I N S T A N C E M E T H O D S # # User options from the command line. attr :options # TODO: Get from metadata -- use POM if available. def title options.title end # FIXME: Pull copyright from project. def copyright "(c) 2009".sub("(c)", "&copy;") end # List of all classes and modules. #def all_classes_and_modules # @all_classes_and_modules ||= RDoc::TopLevel.all_classes_and_modules #end # In the world of the RDoc Generators #classes is the same as # #all_classes_and_modules. Well, except that its sorted too. # For classes sans modules, see #types. def classes @classes ||= RDoc::TopLevel.all_classes_and_modules.sort end # Only toplevel classes and modules. def classes_toplevel @classes_toplevel ||= classes.select {|klass| !(RDoc::ClassModule === klass.parent) } end # Documented classes and modules sorted by salience first, then by name. def classes_salient @classes_salient ||= sort_salient(classes) end # def classes_hash @classes_hash ||= RDoc::TopLevel.modules_hash.merge(RDoc::TopLevel.classes_hash) end # def modules @modules ||= RDoc::TopLevel.modules.sort end # def modules_toplevel @modules_toplevel ||= modules.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def modules_salient @modules_salient ||= sort_salient(modules) end # def modules_hash @modules_hash ||= RDoc::TopLevel.modules_hash end # def types @types ||= RDoc::TopLevel.classes.sort end # def types_toplevel @types_toplevel ||= types.select {|klass| !(RDoc::ClassModule === klass.parent) } end # def types_salient @types_salient ||= sort_salient(types) end # def types_hash @types_hash ||= RDoc::TopLevel.classes_hash end # def files @files ||= RDoc::TopLevel.files end # List of toplevel files. RDoc supplies this via the #generate method. def files_toplevel @files_toplevel end # def files_hash @files ||= RDoc::TopLevel.files_hash end # List of all methods in all classes and modules. def methods_all @methods_all ||= classes.map{ |m| m.method_list }.flatten.sort end # def find_class_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) || RDoc::TopLevel.find_module_named(*a,&b) end # def find_module_named(*a,&b) RDoc::TopLevel.find_module_named(*a,&b) end # def find_type_named(*a,&b) RDoc::TopLevel.find_class_named(*a,&b) end # def find_file_named(*a,&b) RDoc::TopLevel.find_file_named(*a,&b) end # # TODO: What's this then? def json_creatable? RDoc::TopLevel.json_creatable? end # RDoc needs this to function. ? def class_dir ; DIR_CLASS ; end # RDoc needs this to function. ? def file_dir ; DIR_FILE ; end # Build the initial indices and output objects # based on an array of top level objects containing # the extracted information. def generate(toplevel_files) @files_toplevel = toplevel_files.sort generate_setup generate_commons generate_static generate_template generate_components rescue StandardError => err debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] raise end # Components may need to define a method on # the rendering context. def provision(method, &block) #if block #@provisions[method] = block (class << self; self; end).class_eval do define_method(method) do |*a, &b| block.call(*a, &b) end end #else # @provisions[method] = lambda do |*a, &b| # __send__(method, *a, &b) # end #end end protected # def sort_salient(classes) nscounts = classes.inject({}) do |counthash, klass| top_level = klass.full_name.gsub( /::.*/, '' ) counthash[top_level] ||= 0 counthash[top_level] += 1 counthash end # Sort based on how often the top level namespace occurs, and then on the # name of the module -- this works for projects that put their stuff into # a namespace, of course, but doesn't hurt if they don't. classes.sort_by do |klass| top_level = klass.full_name.gsub( /::.*/, '' ) [nscounts[top_level] * -1, klass.full_name] end.select do |klass| klass.document_self end end ## ## Initialization ## def initialize(options) @options = options @options.diagram = false # why? @path_base = Pathname.pwd.expand_path @path_output = Pathname.new(@options.op_dir).expand_path(@path_base) @provisions = {} initialize_template initialize_methods initialize_components end # def initialize_template @template = @options.template #|| DEFAULT_TEMPLATE raise RDoc::Error, "could not find template #{template.inspect}" unless path_template.directory? end # Overide this method to set up any rendering provisions. def initialize_methods end # def initialize_components @components = [] self.class.components.each do |comp| @components << comp.new(self) end end # Component instances. attr :components # Component provisions. attr :provisions # The template type selected to be generated. attr :template # Current pathname. attr :path_base # The output path. attr :path_output # Path to the static files. This should be defined in the # subclass as: # # def path # @path ||= Pathname.new(__FILE__).parent # end # def path raise "Must be implemented by subclass!" end # Path to static files. This is <tt>path + 'static'</tt>. def path_static path + 'static' end # Path to static files. This is <tt>path + 'template'</tt>. def path_template path + 'template' end # def path_output_relative(path=nil) if path path.to_s.sub(path_base.to_s+'/', '') else @path_output_relative ||= path_output.to_s.sub(path_base.to_s+'/', '') end end # Prepare generator. def generate_setup end # This method files copies the common static files of the abstract # generator, which are overlayed with the files from the subclass. # This way there is always a standard base to draw upon, and anything # the subclass doesn't like it can override, which provides a sort-of, # albeit simplistic, file inheritence system. def generate_commons from = Dir[(PATH_STATIC + '**').to_s] dest = path_output.to_s show_from = PATH_STATIC.to_s.sub(PATH.parent.to_s+'/','') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Copy static files to output. All the common static content is # stored in the <tt>assets/</tt> directory. WebRI's <tt>assets/</tt> # directory more or less follows an <i>Abbreviated Monash</i> convention: # # assets/ # css/ <- stylesheets # json/ <- json data table (*maybe top level is better?) # img/ <- images # inc/ <- server-side includes # js/ <- javascripts # # Components can utilize this method by providing a +path+. def generate_static from = Dir[(path_static + '**').to_s] dest = path_output.to_s show_from = path_static.to_s.sub(path.parent.to_s+'/', '') debug_msg "Copying #{show_from}/** to #{path_output_relative}/:" fileutils.cp_r from, dest, :preserve => true end # Rendered and save templates. def generate_template generate_files generate_classes generate_index end # Let the components generate what they need. Iterates through # each componenet and calls #generate. def generate_components components.each do |component| component.generate end end # Create the directories the generated docs will live in if # they don't already exist. #def gen_sub_directories # @path_output.mkpath #end # Generate a documentation file for each file def generate_files debug_msg "Generating file documentation in #{path_output_relative}:" templatefile = self.path_template + 'file.rhtml' files_toplevel.each do |file| outfile = self.path_output + file.path debug_msg "working on %s (%s)" % [ file.full_name, path_output_relative(outfile) ] rel_prefix = self.path_output.relative_path_from( outfile.dirname ) #context = binding() debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :file=>file, :rel_prefix=>rel_prefix) end end # Generate a documentation file for each class def generate_classes debug_msg "Generating class documentation in #{path_output_relative}:" templatefile = self.path_template + 'class.rhtml' classes.each do |klass| debug_msg "working on %s (%s)" % [ klass.full_name, klass.path ] outfile = self.path_output + klass.path rel_prefix = self.path_output.relative_path_from(outfile.dirname) debug_msg "rendering #{path_output_relative(outfile)}" self.render_template( templatefile, outfile, :klass=>klass, :rel_prefix=>rel_prefix ) end end # Create index.html def generate_index debug_msg "Generating index file in #{path_output_relative}:" templatefile = self.path_template + 'index.rhtml' outfile = self.path_output + 'index.html' index_path = index_file.path debug_msg "rendering #{path_output_relative(outfile)}" self.render_template(templatefile, outfile, :index_path=>index_path) end # TODO: Make public? def index_file if self.options.main_page && file = self.files.find { |f| f.full_name == self.options.main_page } file else self.files.first end end =begin # Generate an index page def generate_index_file debug_msg "Generating index file in #@path_output" templatefile = @path_template + 'index.rhtml' template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s context = binding() output = nil begin output = template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end outfile = path_base + @options.op_dir + 'index.html' unless $dryrun debug_msg "Outputting to %s" % [outfile.expand_path] outfile.open( 'w', 0644 ) do |fh| fh.print( output ) end else debug_msg "Would have output to %s" % [outfile.expand_path] end end =end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and write it out to +outfile+. # Both +templatefile+ and +outfile+ should be Pathname-like objects. def render_template(templatefile, outfile, local_assigns) output = erb_template.render(templatefile, local_assigns) #output = eval_template(templatefile, context) # TODO: delete this dirty hack when documentation for example for GeneratorMethods will not be cutted off by <script> tag begin if output.respond_to? :force_encoding encoding = output.encoding output = output.force_encoding('ASCII-8BIT').gsub('<script>', '&lt;script;&gt;').force_encoding(encoding) else output = output.gsub('<script>', '&lt;script&gt;') end rescue Exception => e end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |file| file.print( output ) end else debug_msg "would have written %d bytes to %s" % [ output.length, outfile ] end end # Load and render the erb template in the given +templatefile+ within the # specified +context+ (a Binding object) and return output # Both +templatefile+ and +outfile+ should be Pathname-like objects. def eval_template(templatefile, context) template_src = templatefile.read template = ERB.new(template_src, nil, '<>') template.filename = templatefile.to_s begin template.result(context) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval("_erbout[-50,50]", context) ], err.backtrace end end # def erb_template @erb_template ||= ERBTemplate.new(self, provisions) end =begin def render_template( templatefile, context, outfile ) template_src = templatefile.read template = ERB.new( template_src, nil, '<>' ) template.filename = templatefile.to_s output = begin template.result( context ) rescue NoMethodError => err raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ templatefile.to_s, err.message, eval( "_erbout[-50,50]", context ) ], err.backtrace end unless $dryrun outfile.dirname.mkpath outfile.open( 'w', 0644 ) do |ofh| ofh.print( output ) end else debug_msg " would have written %d bytes to %s" % [ output.length, outfile ] end end =end + # Output progress information if rdoc debugging is enabled + + def debug_msg(msg) + return unless $DEBUG_RDOC + case msg[-1,1] + when '.' then tab = "= " + when ':' then tab = "== " + else tab = "* " + end + $stderr.puts(tab + msg) + end + end end diff --git a/lib/webri/abstract/erbtemplate.rb b/lib/webri/generators/abstract/erbtemplate.rb similarity index 100% rename from lib/webri/abstract/erbtemplate.rb rename to lib/webri/generators/abstract/erbtemplate.rb diff --git a/lib/webri/abstract/static/assets/img/alias.png b/lib/webri/generators/abstract/static/assets/img/alias.png similarity index 100% rename from lib/webri/abstract/static/assets/img/alias.png rename to lib/webri/generators/abstract/static/assets/img/alias.png diff --git a/lib/webri/abstract/static/assets/img/attribute.png b/lib/webri/generators/abstract/static/assets/img/attribute.png similarity index 100% rename from lib/webri/abstract/static/assets/img/attribute.png rename to lib/webri/generators/abstract/static/assets/img/attribute.png diff --git a/lib/webri/abstract/static/assets/img/bug.png b/lib/webri/generators/abstract/static/assets/img/bug.png similarity index 100% rename from lib/webri/abstract/static/assets/img/bug.png rename to lib/webri/generators/abstract/static/assets/img/bug.png diff --git a/lib/webri/abstract/static/assets/img/bullet_black.png b/lib/webri/generators/abstract/static/assets/img/bullet_black.png similarity index 100% rename from lib/webri/abstract/static/assets/img/bullet_black.png rename to lib/webri/generators/abstract/static/assets/img/bullet_black.png diff --git a/lib/webri/abstract/static/assets/img/bullet_toggle_minus.png b/lib/webri/generators/abstract/static/assets/img/bullet_toggle_minus.png similarity index 100% rename from lib/webri/abstract/static/assets/img/bullet_toggle_minus.png rename to lib/webri/generators/abstract/static/assets/img/bullet_toggle_minus.png diff --git a/lib/webri/abstract/static/assets/img/bullet_toggle_plus.png b/lib/webri/generators/abstract/static/assets/img/bullet_toggle_plus.png similarity index 100% rename from lib/webri/abstract/static/assets/img/bullet_toggle_plus.png rename to lib/webri/generators/abstract/static/assets/img/bullet_toggle_plus.png diff --git a/lib/webri/abstract/static/assets/img/check.png b/lib/webri/generators/abstract/static/assets/img/check.png similarity index 100% rename from lib/webri/abstract/static/assets/img/check.png rename to lib/webri/generators/abstract/static/assets/img/check.png diff --git a/lib/webri/abstract/static/assets/img/class.png b/lib/webri/generators/abstract/static/assets/img/class.png similarity index 100% rename from lib/webri/abstract/static/assets/img/class.png rename to lib/webri/generators/abstract/static/assets/img/class.png diff --git a/lib/webri/abstract/static/assets/img/date.png b/lib/webri/generators/abstract/static/assets/img/date.png similarity index 100% rename from lib/webri/abstract/static/assets/img/date.png rename to lib/webri/generators/abstract/static/assets/img/date.png diff --git a/lib/webri/abstract/static/assets/img/favicon.ico b/lib/webri/generators/abstract/static/assets/img/favicon.ico similarity index 100% rename from lib/webri/abstract/static/assets/img/favicon.ico rename to lib/webri/generators/abstract/static/assets/img/favicon.ico diff --git a/lib/webri/abstract/static/assets/img/file.png b/lib/webri/generators/abstract/static/assets/img/file.png similarity index 100% rename from lib/webri/abstract/static/assets/img/file.png rename to lib/webri/generators/abstract/static/assets/img/file.png diff --git a/lib/webri/abstract/static/assets/img/find.png b/lib/webri/generators/abstract/static/assets/img/find.png similarity index 100% rename from lib/webri/abstract/static/assets/img/find.png rename to lib/webri/generators/abstract/static/assets/img/find.png diff --git a/lib/webri/abstract/static/assets/img/loadingAnimation.gif b/lib/webri/generators/abstract/static/assets/img/loadingAnimation.gif similarity index 100% rename from lib/webri/abstract/static/assets/img/loadingAnimation.gif rename to lib/webri/generators/abstract/static/assets/img/loadingAnimation.gif diff --git a/lib/webri/abstract/static/assets/img/macFFBgHack.png b/lib/webri/generators/abstract/static/assets/img/macFFBgHack.png similarity index 100% rename from lib/webri/abstract/static/assets/img/macFFBgHack.png rename to lib/webri/generators/abstract/static/assets/img/macFFBgHack.png diff --git a/lib/webri/abstract/static/assets/img/method.png b/lib/webri/generators/abstract/static/assets/img/method.png similarity index 100% rename from lib/webri/abstract/static/assets/img/method.png rename to lib/webri/generators/abstract/static/assets/img/method.png diff --git a/lib/webri/abstract/static/assets/img/module.png b/lib/webri/generators/abstract/static/assets/img/module.png similarity index 100% rename from lib/webri/abstract/static/assets/img/module.png rename to lib/webri/generators/abstract/static/assets/img/module.png diff --git a/lib/webri/abstract/static/assets/img/page_green.png b/lib/webri/generators/abstract/static/assets/img/page_green.png similarity index 100% rename from lib/webri/abstract/static/assets/img/page_green.png rename to lib/webri/generators/abstract/static/assets/img/page_green.png diff --git a/lib/webri/abstract/static/assets/img/page_white_width.png b/lib/webri/generators/abstract/static/assets/img/page_white_width.png similarity index 100% rename from lib/webri/abstract/static/assets/img/page_white_width.png rename to lib/webri/generators/abstract/static/assets/img/page_white_width.png diff --git a/lib/webri/abstract/static/assets/img/plugin.png b/lib/webri/generators/abstract/static/assets/img/plugin.png similarity index 100% rename from lib/webri/abstract/static/assets/img/plugin.png rename to lib/webri/generators/abstract/static/assets/img/plugin.png diff --git a/lib/webri/abstract/static/assets/img/project.png b/lib/webri/generators/abstract/static/assets/img/project.png similarity index 100% rename from lib/webri/abstract/static/assets/img/project.png rename to lib/webri/generators/abstract/static/assets/img/project.png diff --git a/lib/webri/abstract/static/assets/img/ruby.png b/lib/webri/generators/abstract/static/assets/img/ruby.png similarity index 100% rename from lib/webri/abstract/static/assets/img/ruby.png rename to lib/webri/generators/abstract/static/assets/img/ruby.png diff --git a/lib/webri/abstract/static/assets/img/wrench.png b/lib/webri/generators/abstract/static/assets/img/wrench.png similarity index 100% rename from lib/webri/abstract/static/assets/img/wrench.png rename to lib/webri/generators/abstract/static/assets/img/wrench.png diff --git a/lib/webri/abstract/static/assets/img/wrench_orange.png b/lib/webri/generators/abstract/static/assets/img/wrench_orange.png similarity index 100% rename from lib/webri/abstract/static/assets/img/wrench_orange.png rename to lib/webri/generators/abstract/static/assets/img/wrench_orange.png diff --git a/lib/webri/abstract/static/assets/img/zoom.png b/lib/webri/generators/abstract/static/assets/img/zoom.png similarity index 100% rename from lib/webri/abstract/static/assets/img/zoom.png rename to lib/webri/generators/abstract/static/assets/img/zoom.png diff --git a/lib/webri/abstract/static/assets/js/highlight.js b/lib/webri/generators/abstract/static/assets/js/highlight.js similarity index 100% rename from lib/webri/abstract/static/assets/js/highlight.js rename to lib/webri/generators/abstract/static/assets/js/highlight.js diff --git a/lib/webri/abstract/static/assets/js/jquery.js b/lib/webri/generators/abstract/static/assets/js/jquery.js similarity index 100% rename from lib/webri/abstract/static/assets/js/jquery.js rename to lib/webri/generators/abstract/static/assets/js/jquery.js diff --git a/lib/webri/abstract/static/assets/js/thickbox.js b/lib/webri/generators/abstract/static/assets/js/thickbox.js similarity index 100% rename from lib/webri/abstract/static/assets/js/thickbox.js rename to lib/webri/generators/abstract/static/assets/js/thickbox.js diff --git a/lib/webri/abstract/timedelta.rb b/lib/webri/generators/abstract/timedelta.rb similarity index 100% rename from lib/webri/abstract/timedelta.rb rename to lib/webri/generators/abstract/timedelta.rb diff --git a/lib/webri/generators/foxsocks/generator.rb b/lib/webri/generators/foxsocks.rb similarity index 86% rename from lib/webri/generators/foxsocks/generator.rb rename to lib/webri/generators/foxsocks.rb index 9c81556..1dbd614 100644 --- a/lib/webri/generators/foxsocks/generator.rb +++ b/lib/webri/generators/foxsocks.rb @@ -1,55 +1,55 @@ -require 'webri/abstract/generator' -require 'webri/quicksearch/component' -require 'webri/github/component' +require 'webri/generators/abstract' +require 'webri/components/quicksearch' +require 'webri/components/github' module WebRI # - class Foxsocks < Abstract::Generator + class Foxsocks < Generator include QuickSearch include GitHub # def path @path ||= Pathname.new(__FILE__).parent end #def generate_template # super #end # TODO: Does this belong here or in the quicksearch component? def each_letter_group(methods, &block) group = {:name => '', :methods => []} methods.sort{ |a, b| a.name <=> b.name }.each do |method| gname = group_name method.name if gname != group[:name] yield group unless group[:methods].size == 0 group = { :name => gname, :methods => [] } end group[:methods].push(method) end yield group unless group[:methods].size == 0 end protected # def group_name(name) if match = name.match(/^([a-z])/i) match[1].upcase else '#' end end end end diff --git a/lib/webri/generators/oldfish.rb b/lib/webri/generators/oldfish.rb new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lib/webri/generators/oldfish.rb @@ -0,0 +1 @@ + diff --git a/lib/webri/generators/redfish/generator.rb b/lib/webri/generators/redfish.rb similarity index 62% rename from lib/webri/generators/redfish/generator.rb rename to lib/webri/generators/redfish.rb index 4ef93e2..84d30a7 100644 --- a/lib/webri/generators/redfish/generator.rb +++ b/lib/webri/generators/redfish.rb @@ -1,24 +1,24 @@ -require 'webri/abstract/generator' -require 'webri/subversion/component' +require 'webri/generators/abstract' +require 'webri/components/subversion' module WebRI # - class Redfish < Abstract::Generator + class Redfish < Generator include Subversion # def path @path ||= Pathname.new(__FILE__).parent end # #def generate_template # super #end end end diff --git a/lib/webri/generators/rubylong/generator.rb b/lib/webri/generators/rubylong.rb similarity index 86% rename from lib/webri/generators/rubylong/generator.rb rename to lib/webri/generators/rubylong.rb index 2813048..ca3afd0 100644 --- a/lib/webri/generators/rubylong/generator.rb +++ b/lib/webri/generators/rubylong.rb @@ -1,73 +1,73 @@ -require 'webri/abstract/generator' -#require 'webri/subversion/component' -require 'webri/github/component' -require 'webri/metadata/component' +require 'webri/generators/abstract' +#require 'webri/components/subversion' +require 'webri/components/github' +require 'webri/components/metadata' module WebRI # - class Rubylong < Abstract::Generator + class Rubylong < Generator #include Subversion include GitHub include Metadata # def path @path ||= Pathname.new(__FILE__).parent end # def site_homepage metadata.homepage end # def site_community metadata.mailinglist || metadata.wiki end # def site_repository metadata.development end # def site_news metadata.blog end # def index_title @index_title ||= parse_index_header[0] end # def index_description @index_description ||= parse_index_header[1] end # TODO: Generalize for all generators (?) def parse_index_header if options.main_page && main_page = files_toplevel.find { |f| f.full_name == options.main_page } desc = main_page.description if md = /^\s*\<h1\>(.*?)\<\/h1\>/.match(desc) title = md[1] desc = md.post_match else title = options.main_page end else title = options.title desc = "This is the API documentation for '#{options.title}'." end return title, desc end end end diff --git a/lib/webri/generators/twofish/generator.rb b/lib/webri/generators/twofish.rb similarity index 96% rename from lib/webri/generators/twofish/generator.rb rename to lib/webri/generators/twofish.rb index 29272b6..adcada5 100644 --- a/lib/webri/generators/twofish/generator.rb +++ b/lib/webri/generators/twofish.rb @@ -1,116 +1,116 @@ -require 'webri/abstract/generator' -require 'webri/subversion/component' +require 'webri/generators/abstract' +require 'webri/components/subversion' module WebRI # - class Twofish < Abstract::Generator + class Twofish < Generator include Subversion # def path @path ||= Pathname.new(__FILE__).parent end # def initialize_methods provision :html_tree end # #def generate_template # super #end #<ul> # <li class="trigger"> # <img src="assets/img/class.png" onClick="showBranch(this);"/> # # <span class="link" path="__path__" onClick="lookup_static(this);">__entry.name__</span> # # <div class="branch"> # <ul> # <li class="meta_leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # <ul> # <li class="leaf"> # <span class="link" path="__path__" onClick="lookup_static(this);">__method__</span> # </li> # </ul> # </li> #</ul> # def html_tree #%[<iframe src="tree.html"></iframe>] @html_tree ||= ( %[<div class="root">] + generate_html_tree(classes_toplevel) + %[</div>] #heirarchy) #heirarchy.to_html ) end # generate html tree # def generate_html_tree(classes) markup = ["<ul>"] classes = classes.sort{ |a,b| a.full_name <=> b.full_name } classes.each do |entry| path = entry.path #WebRI.entry_to_path(entry.full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <a class="link" href="#{path}" target="main">#{entry.name}</a> ] markup << %[<div class="branch">] markup << %[<ul>] cmethods, imethods = *entry.method_list.partition{ |m| m.singleton } cmethods = cmethods.sort{ |a,b| a.name <=> b.name } cmethods.each do |method| path = method.path #entry.full_name + ".#{method.name}" #WebRI.entry_to_path(entry.full_name + ".#{method}") markup << %[ <li class="meta_leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end imethods = imethods.sort{ |a,b| a.name <=> b.name } imethods.each do |method| path = method.path #WebRI.entry_to_path(entry.full_name + "##{method}") markup << %[ <li class="leaf"> <a class="link" href="#{path}" target="main">#{method.name}</a> </li> ] end #entry.classes.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << generate_html_tree(entry.classes_and_modules) if entry.classes #end markup << %[</ul>] #if entry.root? # markup << %[</div>] #else markup << %[</div>] markup << %[</li>] #end end markup << "</ul>" return markup.join("\n") end end end#module WebRI
razerbeans/webri
9e09685234415ca66555e1e7ab008d8e66a3c150
new syckle plugin based on rdocs
diff --git a/plug/syckle/services/webri.rb b/plug/syckle/services/webri.rb index bdae00e..f90a695 100644 --- a/plug/syckle/services/webri.rb +++ b/plug/syckle/services/webri.rb @@ -1,108 +1,263 @@ module Syckle::Plugins - # = WebRI Documentation Plugin + # WebRI documentation plugin generates WebRI-based RDocs for + # your project. # - # The webri documentation plugin provides services for - # generating webri documentation. + # By default it generates the documentaiton at doc/webri, + # unless an 'webri' directory exists in the project's root + # directory, in which case the documentation will be + # stored there (unless an alternative is specified). # - # By default it generates the documentaiton at doc/webri. + # This plugin provides the following cycle-phases: # - # This plugin provides three services for both the +main+ and +site+ pipelines. + # main:document - generate rdocs + # main:reset - mark rdocs out-of-date + # main:clean - remove rdocs # - # * +webri+ - Create webri docs - # * +reset+ - Reset webri docs - # * +clean+ - Remove webri docs + # site:document - generate rdocs + # site:reset - mark rdocs out-of-date + # site:clean - remove rdocs + # + # WebRI service will be available automatically if the project + # has a +doc/webri+ or +webri+ directory. # class WebRI < Service #Plugin + ## + # Generate rdocs in main cycle. + # :method: main_document cycle :main, :document - cycle :site, :document + + cycle :main, :reset cycle :main, :clean - cycle :site, :clean - cycle :main, :reset + cycle :site, :document cycle :site, :reset + cycle :site, :clean + # TODO: IMPROVE #available do |project| # !project.metadata.loadpath.empty? #end - # Default location to store ri documentation files. - DEFAULT_OUTPUT = "doc/webri" + # RDoc can run automatically if the project has + # a +doc/rdoc+ directory. + autorun do |project| + project.root.glob('doc/webri,webri').first + end - # - DEFAULT_RIDOC = "doc/ri" + # Default location to store rdoc documentation files. + DEFAULT_OUTPUT = "doc/webri" - # + # Locations to check for existance in deciding where to store rdoc documentation. + DEFAULT_OUTPUT_MATCH = "{doc/webri,webri}" + + # Default main file. + DEFAULT_MAIN = "README{,.*}" + + # Default rdoc template to use. + DEFAULT_TEMPLATE = "redfish" + + # Deafult extra options to add to rdoc call. + DEFAULT_EXTRA = '' + + private + + # Setup default attribute values. def initialize_defaults - @title = metadata.title - @ridoc = DEFAULT_RIDOC - @output = DEFAULT_OUTPUT + @title = metadata.title + @files = metadata.loadpath + ['[A-Z]*', 'bin'] # DEFAULT_FILES + @output = Dir[DEFAULT_OUTPUT_MATCH].first || DEFAULT_OUTPUT + @extra = DEFAULT_EXTRA + @main = Dir[DEFAULT_MAIN].first + @template = ENV['RDOC_TEMPLATE'] || DEFAULT_TEMPLATE end + public + # Title of documents. Defaults to general metadata title field. attr_accessor :title - # Where to save rdoc files (doc/webri). + # Where to save rdoc files (doc/rdoc). attr_accessor :output - # Location of ri docs. Defaults to doc/ri. - # These files must be preset for this plugin to work. - attr_accessor :ridoc + # Template to use (defaults to ENV['RDOC_TEMPLATE'] or 'darkfish') + attr_accessor :template + + # Main file. This can be a file pattern. (README{,.*}) + attr_accessor :main + + # Which files to document. + attr_accessor :files + + # Alias for +files+. + alias_accessor :include, :files + + # Paths to specifically exclude. + attr_accessor :exclude - # In case one is inclined to #ridoc plural. - alias_accessor :ridocs + # File patterns to ignore. + #attr_accessor :ignore - # Generate ri documentation. This utilizes - # rdoc to produce the appropriate files. + # Ad file html snippet to add to html rdocs. + #attr_accessor :adfile + + # Additional options passed to the rdoc command. + attr_accessor :extra + + # Generate Rdoc documentation. Settings are the + # same as the rdoc command's option, with two + # exceptions: +inline+ for +inline-source+ and + # +output+ for +op+. # - def document - output = self.output + def document(options=nil) + options ||= {} - #cmdopts = {} - #cmdopts['o'] = output + title = options['title'] || self.title + output = options['output'] || self.output + main = options['main'] || self.main + template = options['template'] || self.template + files = options['files'] || self.files + exclude = options['exclude'] || self.exclude + #adfile = options['adfile'] || self.adfile + extra = options['extra'] || self.extra - #input = files #.collect do |i| - # dir?(i) ? File.join(i,'**','*') : i - #end + # NOTE: Due to a bug in RDOC this needs to be done so that + # alternate templates can be used. + begin + gem('rdoc') + #gem(templib || template) + rescue LoadError + end - if outofdate?(output, ridoc) or force? - rm_r(output) if exist?(output) and safe?(output) # remove old webri docs + require 'rdoc/rdoc' - status "Generating #{output} ..." + # you can specify more than one possibility, first match wins + adfile = [adfile].flatten.compact.find do |f| + File.exist?(f) + end - #vector = [ridoc, cmdopts] - #if verbose? - sh "webri -o #{output} #{ridoc}" - #else - # silently do - # sh "webri #{vector.to_console}" - # end - #end + main = Dir.glob(main, File::FNM_CASEFOLD).first + + include_files = files.to_list.uniq + exclude_files = exclude.to_list.uniq + + if mfile = project.manifest_file + exclude_files << mfile.basename.to_s # TODO: I think base name should retun a string? + end + + filelist = amass(include_files, exclude_files) + filelist = filelist.select{ |fname| File.file?(fname) } + + if outofdate?(output, *filelist) or force? + status "Generating #{output}" + + #target_main = Dir.glob(target['main'].to_s, File::FNM_CASEFOLD).first + #target_main = File.expand_path(target_main) if target_main + #target_output = File.expand_path(File.join(output, subdir)) + #target_output = File.join(output, subdir) + + argv = [] + argv.concat(extra.split(/\s+/)) + argv.concat ['--op', output] + argv.concat ['--main', main] if main + argv.concat ['--template', template] if template + argv.concat ['--title', title] if title + + exclude_files.each do |file| + argv.concat ['--exclude', file] + end + + argv = argv + filelist #include_files + + rdoc_target(output, include_files, argv) + #rdoc_insert_ads(output, adfile) + + touch(output) else - report "webri docs are current (#{output.sub(Dir.pwd,'')})" + status "RDocs are current (#{output})." end end - # Set the output directory's mtime to furthest time in past. - # This "marks" the documentation as out-of-date. + # Reset output directory, marking it as out-of-date. def reset if File.directory?(output) - File.utime(0,0,self.output) - report "reset #{output}" + File.utime(0,0,output) + report "reset #{output}" #unless dryrun? end end - # Remove ri products. + # Remove rdocs products. def clean if File.directory?(output) rm_r(output) - status "Removed #{output}" #unless dryrun? + status "removed #{output}" #unless dryrun? + end + end + + private + + # Generate rdocs for input targets. + # + # TODO: Use RDoc programmatically rather than via shell. + # + def rdoc_target(output, input, argv=[]) + #if outofdate?(output, *input) or force? + rm_r(output) if exist?(output) and safe?(output) # remove old rdocs + + #rdocopt['op'] = output + + #if template == 'hanna' + # cmd = "hanna #{extra} " + [input, rdocopt].to_console + #else + # cmd = "rdoc #{extra} " + [input, rdocopt].to_console + #end + + #argv = ("#{extra}" + [input, rdocopt].to_console).split(/\s+/) + + if verbose? or dryrun? + puts "webri " + argv.join(" ") + #sh(cmd) #shell(cmd) + else + puts "webri " + argv.join(" ") if trace? + rdoc = ::RDoc::RDoc.new + rdoc.document(argv) + #silently do + # sh(cmd) #shell(cmd) + #end + end + #else + # puts "RDocs are current -- #{output}" + #end + end + +=begin (let webri handle this if desired) + # Insert an ad into rdocs, if exists. + # + # Note that this code is needs work, as is it + # was designed to work with an old version of RDoc. + # + def rdoc_insert_ads(site, adfile) + return if dryrun? + return unless adfile && File.file?(adfile) + adtext = File.read(adfile) + #puts + dirs = Dir.glob(File.join(site,'*/')) + dirs.each do |dir| + files = Dir.glob(File.join(dir, '**/*.html')) + files.each do |file| + html = File.read(file) + bodi = html.index('<body>') + next unless bodi + html[bodi + 7] = "\n" + adtext + File.write(file, html) unless dryrun? + end end end +=end end end
razerbeans/webri
c9895c0f518a44a216cd2453764fdcf6917689f9
moved all server files to riserver/ directory
diff --git a/lib/webri/riserver/generator.rb b/lib/webri/riserver/generator.rb index cf628cb..6fd434c 100644 --- a/lib/webri/riserver/generator.rb +++ b/lib/webri/riserver/generator.rb @@ -1,165 +1,165 @@ -require 'webri/server' +require 'webri/ri/server/server' module WebRI # This is the static website generator. # class Generator < Server # Reference to CGI Service #attr :cgi # Reference to RI Service #attr :service # Directory in which to store generated html files attr :output # def initialize(service, options={}) super(service, options) #@cgi = {} #CGI.new('html4') #@service = service @directory_depth = 0 end # #def tree # #%[<iframe src="tree.html"></iframe>] # @tree ||= heirarchy.to_html_static #end =begin # def lookup(req) keyw = File.basename(req.path_info) if keyw keyw.sub!('-','#') html = service.info(keyw) #puts html #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}" else html = "<h1>ERROR</h1>" end return html end =end #def template_source # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) #end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # Generate webpages. def generate(output=".") @output = File.expand_path(output) # traverse the the hierarchy generate_support_files #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end end # Recrusive HTML generation on a hierarchy entry. def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') write(file, service.info(keyword)) cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = WebRI.entry_to_path(mname) mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") write(mfile, service.info(mname)) end imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |name| mname = "#{entry.full_name}##{name}" mfile = WebRI.entry_to_path(mname) mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") write(mfile, service.info(mname)) end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # Generate files. def generate_support_files FileUtils.mkdir_p(output) write(File.join(output, 'index.html'), index) #write(File.join(output, 'header.html'), page_header) #write(File.join(output, 'tree.html'), page_tree) #write(File.join(output, 'main.html'), page_main) # copy assets dir = File.join(directory, 'assets') FileUtils.cp_r(dir, output) end # Write file. def write(file, text) puts file FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') { |f| f << text.to_s } end # def current_content @current_content end end #class Generator end #module WebRI diff --git a/lib/webri/riserver/generator1.rb b/lib/webri/riserver/generator1.rb index 53fe500..523aff5 100644 --- a/lib/webri/riserver/generator1.rb +++ b/lib/webri/riserver/generator1.rb @@ -1,211 +1,211 @@ -require 'webri/server' +require 'webri/riserver/server' module WebRI # This is the static website generator which creates # a single page. # class GeneratorOne < Server # Reference to CGI Service #attr :cgi # Reference to RI Service #attr :service # Dir in which to store generated html attr :output # attr :html # def initialize(service, options={}) super(service, options) @html = "" #@cgi = {} #CGI.new('html4') #@service = service @directory_depth = 0 end # #def tree # #%[<iframe src="tree.html"></iframe>] # @tree ||= heirarchy.to_html_static #end =begin # def lookup(req) keyw = File.basename(req.path_info) if keyw keyw.sub!('-','#') html = service.info(keyw) #puts html #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}" else html = "<h1>ERROR</h1>" end return html end =end #def template_source # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) #end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # generate webpages def generate(output=".") @output = File.expand_path(output) @assets = {} # traverse the the hierarchy #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end generate_support_files end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name #file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') html << %[<h1>#{entry.full_name}</h1>] html << %[\n<div id="#{file}" class="slot module">\n] html << service.info(keyword) html << %[\n</div>\n] #html << %[<h1>Class Methods</h1>] cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot cmethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end #html << %[<h1>Instance Methods</h1>] imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |name| mname = "#{entry.full_name}##{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot imethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts file FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) index = render(template('index1')) #base = base.strip.chomp('</html>').strip.chomp('</body>').strip.chomp('</div>') #base = base + html #base = base + "</div>\n</body>\n</html>" write(File.join(output, 'webri.html'), index) #write(File.join(output, 'header.html'), page_header) #write(File.join(output, 'tree.html'), page_tree) #write(File.join(output, 'main.html'), page_main) # copy assets #dir = File.join(directory, 'assets') #FileUtils.cp_r(dir, output) end # def current_content @current_content end # def asset(name) @assets[name] ||= File.read(File.join(directory, 'assets', name)) end # def css asset('css/style1.css') end # def jquery '' # asset('js/jquery.js') end # def rijquery '' #asset('js/ri.jquery.js') end end #class Generator end #module WebRI diff --git a/lib/webri/riserver/server.rb b/lib/webri/riserver/server.rb index 39a809d..77dcfca 100644 --- a/lib/webri/riserver/server.rb +++ b/lib/webri/riserver/server.rb @@ -1,352 +1,352 @@ require 'erb' require 'yaml' require 'cgi' -require 'webri/opesc' -require 'webri/heirarchy' +require 'webri/riserver/opesc' +require 'webri/riserver/heirarchy' module WebRI # Server class and base class for Generator. # class Server # Reference to CGI Service #attr :cgi # Reference to RI Service attr :service # Directory in which to store generated html files #attr :output # Title of docs to add to webpage header. attr :title # def initialize(service, options={}) #@cgi = {} #CGI.new('html4') @service = service @templates = {} @title = options[:title] end # Tile of documentation as given by commandline option # or a the namespace of the root entry of the heirarchy. def title @title ||= heirarchy.full_name end # def directory @directory ||= File.dirname(__FILE__) end # def heirarchy @heirarchy ||=( ns = Heirarchy.new(nil) service.names.each do |m| if m.index('#') type = :instance space, method = m.split('#') spaces = space.split('::').collect{|s| s.to_sym } method = method.to_sym elsif m.index('::') type = :class spaces = m.split('::').collect{|s| s.to_sym } if spaces.last.to_s =~ /^[a-z]/ method = spaces.pop else next # what to do about class/module ? end else next # what to do abot class/module ? end memo = ns spaces.each do |space| memo[space] ||= Heirarchy.new(space, memo) memo = memo[space] end if type == :class memo.class_methods << method else memo.instance_methods << method end end ns ) end # def tree #%[<iframe src="tree.html"></iframe>] @tree ||= generate_tree(heirarchy) #heirarchy.to_html end # generate html tree # def generate_tree(entry) markup = [] if entry.root? markup << %[<div class="root">] else path = WebRI.entry_to_path(entry.full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <span class="link" onClick="lookup_static(this, '#{path}');">#{entry.name}</span> ] markup << %[<div class="branch">] end markup << %[<ul>] cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |method| path = WebRI.entry_to_path(entry.full_name + ".#{method}") markup << %[ <li class="meta_leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |method| path = WebRI.entry_to_path(entry.full_name + "##{method}") markup << %[ <li class="leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end entry.subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << generate_tree(subspace) #subspace.to_html end markup << %[</ul>] if entry.root? markup << %[</div>] else markup << %[</div>] markup << %[</li>] end return markup.join("\n") end # def lookup(path) entry = WebRI.path_to_entry(path) if entry html = service.info(entry) html = autolink(html, entry) #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}<br/><br/>" else html = "<h1>ERROR</h1>" end return html end # Search for certain patterns within the HTML and subs in hyperlinks. # # Eg. # # <h2>Instance methods:</h2> # current_content, directory, generate, generate_recurse, generate_tree # def autolink(html, entry) link = entry.gsub('::','/') re = Regexp.new(Regexp.escape(entry), Regexp::MULTILINE) if md = re.match(html) title = %[<a class="link title" href="javascript: lookup_static(this, '#{link}.html');">#{md[0]}</a>] html[md.begin(0)...md.end(0)] = title end # class methods re = Regexp.new(Regexp.escape("<h2>Class methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/c-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end # instance methods re = Regexp.new(Regexp.escape("<h2>Instance methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/i-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end return html end # def template(name) @templates[name] ||= File.read(File.join(directory, 'templates', name + '.html')) end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # def render(source) template = ERB.new(source) template.result(binding) end # #def page_header # render(template('header')) #end # #def page_tree # render(template('tree')) #end # def index render(template('index')) end # #def page_main # render(template('main')) #end =begin # generate webpages def generate(output=".") @output = File.expand_path(output) # traverse the the hierarchy generate_support_files #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name + '.html' file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') write(file, service.info(keyword)) #File.open(file, 'w') { |f| f << service.info(keyword) } #to_html } entry.class_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}--#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.instance_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}-#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts mfile File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) # generate index file file = File.join(output, 'index.html') File.open(file, 'w') { |f| f << to_html } # copy css file dir = File.join(directory,'public','css') FileUtils.cp_r(dir, output) # copy images dir = File.join(directory,'public','img') FileUtils.cp_r(dir, output) # copy scripts dir = File.join(directory,'public','js') FileUtils.cp_r(dir, output) end =end # def current_content @current_content end # def esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end # def self.esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end end #class Engine end #module WebRI
razerbeans/webri
44b208d4f524156354f0506730b1e760ac10d654
default rdoc template is redfish
diff --git a/.config/syckle/rdoc/template b/.config/syckle/rdoc/template new file mode 100644 index 0000000..3e4bc0f --- /dev/null +++ b/.config/syckle/rdoc/template @@ -0,0 +1 @@ +redfish \ No newline at end of file
razerbeans/webri
2110b0a6e12e7ee1b9d7d6657e35bc1ac292f7ce
added meta/repository
diff --git a/meta/repository b/meta/repository new file mode 100644 index 0000000..81e35f9 --- /dev/null +++ b/meta/repository @@ -0,0 +1 @@ +git://github.com/proutils/webri.git
razerbeans/webri
9b92f3393bb9230684ee9957f016073a9c989cf9
added doc/webri.html to .gitignore
diff --git a/.gitignore b/.gitignore index 377f3ca..5f3a1f9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ MANIFEST .cache log pack doc/rdoc doc/ri doc/webri +doc/webri.html
razerbeans/webri
8fad2d31ba3efb8834209d0fd63fed694e772d03
fixed namespace for syckle plugin
diff --git a/plug/syckle/services/webri.rb b/plug/syckle/services/webri.rb index 3eb2141..bdae00e 100644 --- a/plug/syckle/services/webri.rb +++ b/plug/syckle/services/webri.rb @@ -1,108 +1,108 @@ -module Syckles +module Syckle::Plugins # = WebRI Documentation Plugin # # The webri documentation plugin provides services for # generating webri documentation. # # By default it generates the documentaiton at doc/webri. # # This plugin provides three services for both the +main+ and +site+ pipelines. # # * +webri+ - Create webri docs # * +reset+ - Reset webri docs # * +clean+ - Remove webri docs # class WebRI < Service #Plugin cycle :main, :document cycle :site, :document cycle :main, :clean cycle :site, :clean cycle :main, :reset cycle :site, :reset #available do |project| # !project.metadata.loadpath.empty? #end # Default location to store ri documentation files. DEFAULT_OUTPUT = "doc/webri" # DEFAULT_RIDOC = "doc/ri" # def initialize_defaults @title = metadata.title @ridoc = DEFAULT_RIDOC @output = DEFAULT_OUTPUT end # Title of documents. Defaults to general metadata title field. attr_accessor :title # Where to save rdoc files (doc/webri). attr_accessor :output # Location of ri docs. Defaults to doc/ri. # These files must be preset for this plugin to work. attr_accessor :ridoc # In case one is inclined to #ridoc plural. alias_accessor :ridocs # Generate ri documentation. This utilizes # rdoc to produce the appropriate files. # def document output = self.output #cmdopts = {} #cmdopts['o'] = output #input = files #.collect do |i| # dir?(i) ? File.join(i,'**','*') : i #end if outofdate?(output, ridoc) or force? rm_r(output) if exist?(output) and safe?(output) # remove old webri docs status "Generating #{output} ..." #vector = [ridoc, cmdopts] #if verbose? sh "webri -o #{output} #{ridoc}" #else # silently do # sh "webri #{vector.to_console}" # end #end else report "webri docs are current (#{output.sub(Dir.pwd,'')})" end end # Set the output directory's mtime to furthest time in past. # This "marks" the documentation as out-of-date. def reset if File.directory?(output) File.utime(0,0,self.output) report "reset #{output}" end end # Remove ri products. def clean if File.directory?(output) rm_r(output) status "Removed #{output}" #unless dryrun? end end end end
razerbeans/webri
aa7e02a06960d8e8bac1c702e3d39d6161114178
doc updates
diff --git a/COPYING b/COPYING deleted file mode 100644 index ca8c036..0000000 --- a/COPYING +++ /dev/null @@ -1,349 +0,0 @@ - - WebRI - - Copyright (c) 2008 TigerOps - - - THE RUBY LICENSE - (http://www.ruby-lang.org/en/LICENSE.txt) - - You may redistribute this software and/or modify it under either the terms of - the GPL (see below), or the conditions below: - - 1. You may make and give away verbatim copies of the source form of the - software without restriction, provided that you duplicate all of the - original copyright notices and associated disclaimers. - - 2. You may modify your copy of the software in any way, provided that - you do at least ONE of the following: - - a) place your modifications in the Public Domain or otherwise - make them Freely Available, such as by posting said - modifications to Usenet or an equivalent medium, or by allowing - the author to include your modifications in the software. - - b) use the modified software only within your corporation or - organization. - - c) rename any non-standard executables so the names do not conflict - with standard executables, which must also be provided. - - d) make other distribution arrangements with the author. - - 3. You may distribute the software in object code or executable - form, provided that you do at least ONE of the following: - - a) distribute the executables and library files of the software, - together with instructions (in the manual page or equivalent) - on where to get the original distribution. - - b) accompany the distribution with the machine-readable source of - the software. - - c) give non-standard executables non-standard names, with - instructions on where to get the original software distribution. - - d) make other distribution arrangements with the author. - - 4. You may modify and include the part of the software into any other - software (possibly commercial). But some files in the distribution - are not written by the author, so that they are not under these terms. - - For the list of those files and their copying conditions, see the - file LEGAL. - - 5. The scripts and library files supplied as input to or produced as - output from the software do not automatically fall under the - copyright of the software, but belong to whomever generated them, - and may be sold commercially, and may be aggregated with this - software. - - 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR - IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE. - - ---------------------------------------------------------------------------- - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your - freedom to share and change it. By contrast, the GNU General Public - License is intended to guarantee your freedom to share and change free - software--to make sure the software is free for all its users. This - General Public License applies to most of the Free Software - Foundation's software and to any other program whose authors commit to - using it. (Some other Free Software Foundation software is covered by - the GNU Library General Public License instead.) You can apply it to - your programs, too. - - When we speak of free software, we are referring to freedom, not - price. Our General Public Licenses are designed to make sure that you - have the freedom to distribute copies of free software (and charge for - this service if you wish), that you receive source code or can get it - if you want it, that you can change the software or use pieces of it - in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid - anyone to deny you these rights or to ask you to surrender the rights. - These restrictions translate to certain responsibilities for you if you - distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether - gratis or for a fee, you must give the recipients all the rights that - you have. You must make sure that they, too, receive or can get the - source code. And you must show them these terms so they know their - rights. - - We protect your rights with two steps: (1) copyright the software, and - (2) offer you this license which gives you legal permission to copy, - distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain - that everyone understands that there is no warranty for this free - software. If the software is modified by someone else and passed on, we - want its recipients to know that what they have is not the original, so - that any problems introduced by others will not reflect on the original - authors' reputations. - - Finally, any free program is threatened constantly by software - patents. We wish to avoid the danger that redistributors of a free - program will individually obtain patent licenses, in effect making the - program proprietary. To prevent this, we have made it clear that any - patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and - modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains - a notice placed by the copyright holder saying it may be distributed - under the terms of this General Public License. The "Program", below, - refers to any such program or work, and a "work based on the Program" - means either the Program or any derivative work under copyright law: - that is to say, a work containing the Program or a portion of it, - either verbatim or with modifications and/or translated into another - language. (Hereinafter, translation is included without limitation in - the term "modification".) Each licensee is addressed as "you". - - Activities other than copying, distribution and modification are not - covered by this License; they are outside its scope. The act of - running the Program is not restricted, and the output from the Program - is covered only if its contents constitute a work based on the - Program (independent of having been made by running the Program). - Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's - source code as you receive it, in any medium, provided that you - conspicuously and appropriately publish on each copy an appropriate - copyright notice and disclaimer of warranty; keep intact all the - notices that refer to this License and to the absence of any warranty; - and give any other recipients of the Program a copy of this License - along with the Program. - - You may charge a fee for the physical act of transferring a copy, and - you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion - of it, thus forming a work based on the Program, and copy and - distribute such modifications or work under the terms of Section 1 - above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - - These requirements apply to the modified work as a whole. If - identifiable sections of that work are not derived from the Program, - and can be reasonably considered independent and separate works in - themselves, then this License, and its terms, do not apply to those - sections when you distribute them as separate works. But when you - distribute the same sections as part of a whole which is a work based - on the Program, the distribution of the whole must be on the terms of - this License, whose permissions for other licensees extend to the - entire whole, and thus to each and every part regardless of who wrote it. - - Thus, it is not the intent of this section to claim rights or contest - your rights to work written entirely by you; rather, the intent is to - exercise the right to control the distribution of derivative or - collective works based on the Program. - - In addition, mere aggregation of another work not based on the Program - with the Program (or with a work based on the Program) on a volume of - a storage or distribution medium does not bring the other work under - the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, - under Section 2) in object code or executable form under the terms of - Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - - The source code for a work means the preferred form of the work for - making modifications to it. For an executable work, complete source - code means all the source code for all modules it contains, plus any - associated interface definition files, plus the scripts used to - control compilation and installation of the executable. However, as a - special exception, the source code distributed need not include - anything that is normally distributed (in either source or binary - form) with the major components (compiler, kernel, and so on) of the - operating system on which the executable runs, unless that component - itself accompanies the executable. - - If distribution of executable or object code is made by offering - access to copy from a designated place, then offering equivalent - access to copy the source code from the same place counts as - distribution of the source code, even though third parties are not - compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program - except as expressly provided under this License. Any attempt - otherwise to copy, modify, sublicense or distribute the Program is - void, and will automatically terminate your rights under this License. - However, parties who have received copies, or rights, from you under - this License will not have their licenses terminated so long as such - parties remain in full compliance. - - 5. You are not required to accept this License, since you have not - signed it. However, nothing else grants you permission to modify or - distribute the Program or its derivative works. These actions are - prohibited by law if you do not accept this License. Therefore, by - modifying or distributing the Program (or any work based on the - Program), you indicate your acceptance of this License to do so, and - all its terms and conditions for copying, distributing or modifying - the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the - Program), the recipient automatically receives a license from the - original licensor to copy, distribute or modify the Program subject to - these terms and conditions. You may not impose any further - restrictions on the recipients' exercise of the rights granted herein. - You are not responsible for enforcing compliance by third parties to - this License. - - 7. If, as a consequence of a court judgment or allegation of patent - infringement or for any other reason (not limited to patent issues), - conditions are imposed on you (whether by court order, agreement or - otherwise) that contradict the conditions of this License, they do not - excuse you from the conditions of this License. If you cannot - distribute so as to satisfy simultaneously your obligations under this - License and any other pertinent obligations, then as a consequence you - may not distribute the Program at all. For example, if a patent - license would not permit royalty-free redistribution of the Program by - all those who receive copies directly or indirectly through you, then - the only way you could satisfy both it and this License would be to - refrain entirely from distribution of the Program. - - If any portion of this section is held invalid or unenforceable under - any particular circumstance, the balance of the section is intended to - apply and the section as a whole is intended to apply in other - circumstances. - - It is not the purpose of this section to induce you to infringe any - patents or other property right claims or to contest validity of any - such claims; this section has the sole purpose of protecting the - integrity of the free software distribution system, which is - implemented by public license practices. Many people have made - generous contributions to the wide range of software distributed - through that system in reliance on consistent application of that - system; it is up to the author/donor to decide if he or she is willing - to distribute software through any other system and a licensee cannot - impose that choice. - - This section is intended to make thoroughly clear what is believed to - be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in - certain countries either by patents or by copyrighted interfaces, the - original copyright holder who places the Program under this License - may add an explicit geographical distribution limitation excluding - those countries, so that distribution is permitted only in or among - countries not thus excluded. In such case, this License incorporates - the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions - of the General Public License from time to time. Such new versions will - be similar in spirit to the present version, but may differ in detail to - address new problems or concerns. - - Each version is given a distinguishing version number. If the Program - specifies a version number of this License which applies to it and "any - later version", you have the option of following the terms and conditions - either of that version or of any later version published by the Free - Software Foundation. If the Program does not specify a version number of - this License, you may choose any version ever published by the Free Software - Foundation. - - 10. If you wish to incorporate parts of the Program into other free - programs whose distribution conditions are different, write to the author - to ask for permission. For software which is copyrighted by the Free - Software Foundation, write to the Free Software Foundation; we sometimes - make exceptions for this. Our decision will be guided by the two goals - of preserving the free status of all derivatives of our free software and - of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY - FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN - OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES - PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED - OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS - TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE - PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, - REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING - WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR - REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, - INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING - OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED - TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY - YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER - PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6cbe198 --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +The MIT License + +Copyright (c) 2009 Thomas Sawyer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + diff --git a/README b/README index fcfda02..51b19b1 100644 --- a/README +++ b/README @@ -1,78 +1,98 @@ -= Web RI += Webri - http://webri.rubyforge.org +* http://proutils.github.com/webri +* http://github.com/proutils/webri +* http://googlegroups/group/proutils -Webrick-based RI browser -== Usage +== DESCRIPTION + +Webri is a web-based ri browser. It can provided ri documentation dynamically, +by running a webrick server, or it can generate static pages. + +== USAGE === Generate RI Docs WebRI can be used to browse the entire installed object system --eveything documented in one of the central RI locations. WebRI can also be used (and this is probably more useful) to browse per-project RI documentation. Simply generate the RI docs by navigating to the projects root directory and running: - rdoc --ri --op "doc/ri" lib + $ rdoc --ri --op "doc/ri" lib Sometimes a package will include a convenience script for generating these. Try running 'rake -T', or look for a 'script/' or 'task/' executable that does the job. Usually the generated documentation is placed in either ri/ or doc/ri/. I will use doc/ri/ in the following example, sicen that is my preference. Adjust your directory as needed. === Using Webri to View Them With ri docs generated, you can view them with: $ webri doc/ri You will see a Webrick server start up, informing you of the port being used. [2008-03-28 12:11:16] INFO WEBrick 1.3.1 [2008-03-28 12:11:16] INFO ruby 1.8.6 (2007-06-07) [x86_64-linux] [2008-03-28 12:11:21] INFO WEBrick::HTTPServer#start: pid=8870 port=8888 In this example we see the port is the default 8888. Simply open your browser and navigate to: http://localhost:8888/ On the left side of the screen you will see a navigation tree, and the right side contans an infromation panel. NOTE: Becuase RI itself isn't very fast, if you use WebRI against the entire set of installed Ruby libraries it can take a few seconds to load up. (Sure wish FastRI turned out for the better.) === Generating Static Output You can generate a static set of pages for offline viewing by specifying and +output+ option. - webri -o doc/webri doc/ri + $ webri -o doc/webri doc/ri This will create a number of files in the doc/webri directory. Open +doc/webri/index.html+ to view them. [ed-- Not yet ready for use] There is also a one page generation mode, where the entire set of specified ridocs will be placed in a single file. -== How to Install +== INSTALLATION Installation using RubyGems: - gem install webri + $ sudo gem install webri + + +== ROADMAP + +Currently Webri churns through a libraries entries one at a time, calling ri on the backend +again and again. This makes Webri fairly slow. Now that RDoc templates are becoming much easier +create, Webri may well be transformed into an RDoc template. It's just a matter of figuring +out how to use a different formatter other than Darkfish. Once that happens, Webri the program +will migrate into a web-browser extension (Firefox in particular). -== Copying +== COPYING -WebRI, Copyright (c) 2008, 2009 Thomas Sawyer +WebRI Copyright (c) 2009 Thomas Sawyer, MIT License -Unless otherwise permited by the author, this sowftware -is distributed under the terms of the GPL version 3. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/task/notes.syckle b/task/notes.syckle index 8fbd9b0..335eb97 100644 --- a/task/notes.syckle +++ b/task/notes.syckle @@ -1,4 +1,4 @@ --- -notes: - service: Notes - +dnote: + service: DNote + active: true
razerbeans/webri
4eeb5d02530207e86003503832e68b68e0040665
use redfish rdoc template
diff --git a/.config/syckle/automatic b/.config/syckle/automatic new file mode 100644 index 0000000..27ba77d --- /dev/null +++ b/.config/syckle/automatic @@ -0,0 +1 @@ +true diff --git a/.config/syckle/defaults/rdoc/template b/.config/syckle/defaults/rdoc/template new file mode 100644 index 0000000..93fef85 --- /dev/null +++ b/.config/syckle/defaults/rdoc/template @@ -0,0 +1 @@ +redfish diff --git a/TODO b/TODO index cf2136e..e8d2872 100644 --- a/TODO +++ b/TODO @@ -1,8 +1,9 @@ = WebRI TODO * All three modes now works, they just need a bit of TLC to look good and work optiamally. * Would like to add a Rack server, that could be used instead of the Webrick server. +* Incoporate firefox keyword mode (see MGeorgi Blog) diff --git a/meta/project b/meta/project new file mode 100644 index 0000000..a8ab384 --- /dev/null +++ b/meta/project @@ -0,0 +1 @@ +proutils diff --git a/task/box.syckle b/task/box.syckle index 9349efe..aa898e8 100644 --- a/task/box.syckle +++ b/task/box.syckle @@ -1,7 +1,7 @@ --- box: service : Box - types : [gem, tar] - manifest : true + types : [gem, gz] + master : true include : [bin, lib, meta, test, "[A-Z]*" ] diff --git a/task/rdoc.syckle b/task/rdoc.syckle index 9f2e13b..6e03443 100644 --- a/task/rdoc.syckle +++ b/task/rdoc.syckle @@ -1,6 +1,6 @@ --- rdoc: service : RDoc - template : ~ - inline : true + template : redfish exclude : [ lib/webri/public ] +