id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
26,300
backend_pdf.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_pdf.py
# -*- coding: iso-8859-1 -*- """ A PDF matplotlib backend (not yet complete) Author: Jouni K Seppänen <jks@iki.fi> """ from __future__ import division import os import re import sys import time import warnings import zlib import numpy as npy from cStringIO import StringIO from datetime import datetime from math import ceil, cos, floor, pi, sin try: set except NameError: from sets import Set as set import matplotlib from matplotlib import __version__, rcParams, get_data_path from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.cbook import Bunch, is_string_like, reverse_dict, \ get_realpath_and_stat, is_writable_file_like, maxdict from matplotlib.mlab import quad2cubic from matplotlib.figure import Figure from matplotlib.font_manager import findfont, is_opentype_cff_font from matplotlib.afm import AFM import matplotlib.type1font as type1font import matplotlib.dviread as dviread from matplotlib.ft2font import FT2Font, FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, \ LOAD_NO_HINTING, KERNING_UNFITTED from matplotlib.mathtext import MathTextParser from matplotlib.transforms import Affine2D, Bbox, BboxBase from matplotlib.path import Path from matplotlib import ttconv # Overview # # The low-level knowledge about pdf syntax lies mainly in the pdfRepr # function and the classes Reference, Name, Operator, and Stream. The # PdfFile class knows about the overall structure of pdf documents. # It provides a "write" method for writing arbitrary strings in the # file, and an "output" method that passes objects through the pdfRepr # function before writing them in the file. The output method is # called by the RendererPdf class, which contains the various draw_foo # methods. RendererPdf contains a GraphicsContextPdf instance, and # each draw_foo calls self.check_gc before outputting commands. This # method checks whether the pdf graphics state needs to be modified # and outputs the necessary commands. GraphicsContextPdf represents # the graphics state, and its "delta" method returns the commands that # modify the state. # Add "pdf.use14corefonts: True" in your configuration file to use only # the 14 PDF core fonts. These fonts do not need to be embedded; every # PDF viewing application is required to have them. This results in very # light PDF files you can use directly in LaTeX or ConTeXt documents # generated with pdfTeX, without any conversion. # These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique, # Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique, # Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic, # Times-BoldItalic, Symbol, ZapfDingbats. # # Some tricky points: # # 1. The clip path can only be widened by popping from the state # stack. Thus the state must be pushed onto the stack before narrowing # the clip path. This is taken care of by GraphicsContextPdf. # # 2. Sometimes it is necessary to refer to something (e.g. font, # image, or extended graphics state, which contains the alpha value) # in the page stream by a name that needs to be defined outside the # stream. PdfFile provides the methods fontName, imageObject, and # alphaState for this purpose. The implementations of these methods # should perhaps be generalized. # TODOs: # # * the alpha channel of images # * image compression could be improved (PDF supports png-like compression) # * encoding of fonts, including mathtext fonts and unicode support # * Type 1 font support (i.e., "pdf.use_afm") # * TTF support has lots of small TODOs, e.g. how do you know if a font # is serif/sans-serif, or symbolic/non-symbolic? # * draw_markers, draw_line_collection, etc. # * use_tex def fill(strings, linelen=75): """Make one string from sequence of strings, with whitespace in between. The whitespace is chosen to form lines of at most linelen characters, if possible.""" currpos = 0 lasti = 0 result = [] for i, s in enumerate(strings): length = len(s) if currpos + length < linelen: currpos += length + 1 else: result.append(' '.join(strings[lasti:i])) lasti = i currpos = length result.append(' '.join(strings[lasti:])) return '\n'.join(result) _string_escape_regex = re.compile(r'([\\()])') def pdfRepr(obj): """Map Python objects to PDF syntax.""" # Some objects defined later have their own pdfRepr method. if hasattr(obj, 'pdfRepr'): return obj.pdfRepr() # Floats. PDF does not have exponential notation (1.0e-10) so we # need to use %f with some precision. Perhaps the precision # should adapt to the magnitude of the number? elif isinstance(obj, float): if not npy.isfinite(obj): raise ValueError, "Can only output finite numbers in PDF" r = "%.10f" % obj return r.rstrip('0').rstrip('.') # Integers are written as such. elif isinstance(obj, (int, long)): return "%d" % obj # Strings are written in parentheses, with backslashes and parens # escaped. Actually balanced parens are allowed, but it is # simpler to escape them all. TODO: cut long strings into lines; # I believe there is some maximum line length in PDF. elif is_string_like(obj): return '(' + _string_escape_regex.sub(r'\\\1', obj) + ')' # Dictionaries. The keys must be PDF names, so if we find strings # there, we make Name objects from them. The values may be # anything, so the caller must ensure that PDF names are # represented as Name objects. elif isinstance(obj, dict): r = ["<<"] r.extend(["%s %s" % (Name(key).pdfRepr(), pdfRepr(val)) for key, val in obj.items()]) r.append(">>") return fill(r) # Lists. elif isinstance(obj, (list, tuple)): r = ["["] r.extend([pdfRepr(val) for val in obj]) r.append("]") return fill(r) # Booleans. elif isinstance(obj, bool): return ['false', 'true'][obj] # The null keyword. elif obj is None: return 'null' # A date. elif isinstance(obj, datetime): r = obj.strftime('D:%Y%m%d%H%M%S') if time.daylight: z = time.altzone else: z = time.timezone if z == 0: r += 'Z' elif z < 0: r += "+%02d'%02d'" % ((-z)//3600, (-z)%3600) else: r += "-%02d'%02d'" % (z//3600, z%3600) return pdfRepr(r) # A bounding box elif isinstance(obj, BboxBase): return fill([pdfRepr(val) for val in obj.bounds]) else: raise TypeError, \ "Don't know a PDF representation for %s objects." \ % type(obj) class Reference: """PDF reference object. Use PdfFile.reserveObject() to create References. """ def __init__(self, id): self.id = id def __repr__(self): return "<Reference %d>" % self.id def pdfRepr(self): return "%d 0 R" % self.id def write(self, contents, file): write = file.write write("%d 0 obj\n" % self.id) write(pdfRepr(contents)) write("\nendobj\n") class Name: """PDF name object.""" _regex = re.compile(r'[^!-~]') def __init__(self, name): if isinstance(name, Name): self.name = name.name else: self.name = self._regex.sub(Name.hexify, name) def __repr__(self): return "<Name %s>" % self.name def hexify(match): return '#%02x' % ord(match.group()) hexify = staticmethod(hexify) def pdfRepr(self): return '/' + self.name class Operator: """PDF operator object.""" def __init__(self, op): self.op = op def __repr__(self): return '<Operator %s>' % self.op def pdfRepr(self): return self.op # PDF operators (not an exhaustive list) _pdfops = dict(close_fill_stroke='b', fill_stroke='B', fill='f', closepath='h', close_stroke='s', stroke='S', endpath='n', begin_text='BT', end_text='ET', curveto='c', rectangle='re', lineto='l', moveto='m', concat_matrix='cm', use_xobject='Do', setgray_stroke='G', setgray_nonstroke='g', setrgb_stroke='RG', setrgb_nonstroke='rg', setcolorspace_stroke='CS', setcolorspace_nonstroke='cs', setcolor_stroke='SCN', setcolor_nonstroke='scn', setdash='d', setlinejoin='j', setlinecap='J', setgstate='gs', gsave='q', grestore='Q', textpos='Td', selectfont='Tf', textmatrix='Tm', show='Tj', showkern='TJ', setlinewidth='w', clip='W') Op = Bunch(**dict([(name, Operator(value)) for name, value in _pdfops.items()])) class Stream: """PDF stream object. This has no pdfRepr method. Instead, call begin(), then output the contents of the stream by calling write(), and finally call end(). """ def __init__(self, id, len, file, extra=None): """id: object id of stream; len: an unused Reference object for the length of the stream, or None (to use a memory buffer); file: a PdfFile; extra: a dictionary of extra key-value pairs to include in the stream header """ self.id = id # object id self.len = len # id of length object self.pdfFile = file self.file = file.fh # file to which the stream is written self.compressobj = None # compression object if extra is None: self.extra = dict() else: self.extra = extra self.pdfFile.recordXref(self.id) if rcParams['pdf.compression']: self.compressobj = zlib.compressobj(rcParams['pdf.compression']) if self.len is None: self.file = StringIO() else: self._writeHeader() self.pos = self.file.tell() def _writeHeader(self): write = self.file.write write("%d 0 obj\n" % self.id) dict = self.extra dict['Length'] = self.len if rcParams['pdf.compression']: dict['Filter'] = Name('FlateDecode') write(pdfRepr(dict)) write("\nstream\n") def end(self): """Finalize stream.""" self._flush() if self.len is None: contents = self.file.getvalue() self.len = len(contents) self.file = self.pdfFile.fh self._writeHeader() self.file.write(contents) self.file.write("\nendstream\nendobj\n") else: length = self.file.tell() - self.pos self.file.write("\nendstream\nendobj\n") self.pdfFile.writeObject(self.len, length) def write(self, data): """Write some data on the stream.""" if self.compressobj is None: self.file.write(data) else: compressed = self.compressobj.compress(data) self.file.write(compressed) def _flush(self): """Flush the compression object.""" if self.compressobj is not None: compressed = self.compressobj.flush() self.file.write(compressed) self.compressobj = None class PdfFile: """PDF file with one page.""" def __init__(self, width, height, dpi, filename): self.width, self.height = width, height self.dpi = dpi if rcParams['path.simplify']: self.simplify = (width * dpi, height * dpi) else: self.simplify = None self.nextObject = 1 # next free object id self.xrefTable = [ [0, 65535, 'the zero object'] ] self.passed_in_file_object = False if is_string_like(filename): fh = file(filename, 'wb') elif is_writable_file_like(filename): fh = filename self.passed_in_file_object = True else: raise ValueError("filename must be a path or a file-like object") self.fh = fh self.currentstream = None # stream object to write to, if any fh.write("%PDF-1.4\n") # 1.4 is the first version to have alpha # Output some eight-bit chars as a comment so various utilities # recognize the file as binary by looking at the first few # lines (see note in section 3.4.1 of the PDF reference). fh.write("%\254\334 \253\272\n") self.rootObject = self.reserveObject('root') self.infoObject = self.reserveObject('info') pagesObject = self.reserveObject('pages') thePageObject = self.reserveObject('page 0') contentObject = self.reserveObject('contents of page 0') self.fontObject = self.reserveObject('fonts') self.alphaStateObject = self.reserveObject('extended graphics states') self.hatchObject = self.reserveObject('tiling patterns') self.XObjectObject = self.reserveObject('external objects') resourceObject = self.reserveObject('resources') root = { 'Type': Name('Catalog'), 'Pages': pagesObject } self.writeObject(self.rootObject, root) info = { 'Creator': 'matplotlib ' + __version__ \ + ', http://matplotlib.sf.net', 'Producer': 'matplotlib pdf backend', 'CreationDate': datetime.today() } # Possible TODO: Title, Author, Subject, Keywords self.writeObject(self.infoObject, info) pages = { 'Type': Name('Pages'), 'Kids': [ thePageObject ], 'Count': 1 } self.writeObject(pagesObject, pages) thePage = { 'Type': Name('Page'), 'Parent': pagesObject, 'Resources': resourceObject, 'MediaBox': [ 0, 0, dpi*width, dpi*height ], 'Contents': contentObject } self.writeObject(thePageObject, thePage) # self.fontNames maps filenames to internal font names self.fontNames = {} self.nextFont = 1 # next free internal font name self.fontInfo = {} # information on fonts: metrics, encoding self.alphaStates = {} # maps alpha values to graphics state objects self.nextAlphaState = 1 self.hatchPatterns = {} self.nextHatch = 1 self.images = {} self.nextImage = 1 self.markers = {} self.multi_byte_charprocs = {} # The PDF spec recommends to include every procset procsets = [ Name(x) for x in "PDF Text ImageB ImageC ImageI".split() ] # Write resource dictionary. # Possibly TODO: more general ExtGState (graphics state dictionaries) # ColorSpace Pattern Shading Properties resources = { 'Font': self.fontObject, 'XObject': self.XObjectObject, 'ExtGState': self.alphaStateObject, 'Pattern': self.hatchObject, 'ProcSet': procsets } self.writeObject(resourceObject, resources) # Start the content stream of the page self.beginStream(contentObject.id, self.reserveObject('length of content stream')) def close(self): # End the content stream and write out the various deferred # objects self.endStream() self.writeFonts() self.writeObject(self.alphaStateObject, dict([(val[0], val[1]) for val in self.alphaStates.values()])) self.writeHatches() xobjects = dict(self.images.values()) for tup in self.markers.values(): xobjects[tup[0]] = tup[1] for name, value in self.multi_byte_charprocs.items(): xobjects[name] = value self.writeObject(self.XObjectObject, xobjects) self.writeImages() self.writeMarkers() self.writeXref() self.writeTrailer() if self.passed_in_file_object: self.fh.flush() else: self.fh.close() def write(self, data): if self.currentstream is None: self.fh.write(data) else: self.currentstream.write(data) def output(self, *data): self.write(fill(map(pdfRepr, data))) self.write('\n') def beginStream(self, id, len, extra=None): assert self.currentstream is None self.currentstream = Stream(id, len, self, extra) def endStream(self): self.currentstream.end() self.currentstream = None def fontName(self, fontprop): """ Select a font based on fontprop and return a name suitable for Op.selectfont. If fontprop is a string, it will be interpreted as the filename of the font. """ if is_string_like(fontprop): filename = fontprop elif rcParams['pdf.use14corefonts']: filename = findfont(fontprop, fontext='afm') else: filename = findfont(fontprop) Fx = self.fontNames.get(filename) if Fx is None: Fx = Name('F%d' % self.nextFont) self.fontNames[filename] = Fx self.nextFont += 1 return Fx def writeFonts(self): fonts = {} for filename, Fx in self.fontNames.items(): if filename.endswith('.afm'): fontdictObject = self._write_afm_font(filename) elif filename.endswith('.pfb') or filename.endswith('.pfa'): # a Type 1 font; limited support for now fontdictObject = self.embedType1(filename, self.fontInfo[Fx]) else: realpath, stat_key = get_realpath_and_stat(filename) chars = self.used_characters.get(stat_key) if chars is not None and len(chars[1]): fontdictObject = self.embedTTF(realpath, chars[1]) fonts[Fx] = fontdictObject #print >>sys.stderr, filename self.writeObject(self.fontObject, fonts) def _write_afm_font(self, filename): fh = file(filename) font = AFM(fh) fh.close() fontname = font.get_fontname() fontdict = { 'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(fontname), 'Encoding': Name('WinAnsiEncoding') } fontdictObject = self.reserveObject('font dictionary') self.writeObject(fontdictObject, fontdict) return fontdictObject def embedType1(self, filename, fontinfo): # TODO: font effects such as SlantFont fh = open(filename, 'rb') matplotlib.verbose.report( 'Embedding Type 1 font ' + filename, 'debug') try: fontdata = fh.read() finally: fh.close() font = FT2Font(filename) widthsObject, fontdescObject, fontdictObject, fontfileObject = \ [ self.reserveObject(n) for n in ('font widths', 'font descriptor', 'font dictionary', 'font file') ] firstchar = 0 lastchar = len(fontinfo.widths) - 1 fontdict = { 'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font.postscript_name), 'FirstChar': 0, 'LastChar': lastchar, 'Widths': widthsObject, 'FontDescriptor': fontdescObject, } if fontinfo.encodingfile is not None: enc = dviread.Encoding(fontinfo.encodingfile) differencesArray = [ Name(ch) for ch in enc ] differencesArray = [ 0 ] + differencesArray fontdict.update({ 'Encoding': { 'Type': Name('Encoding'), 'Differences': differencesArray }, }) _, _, fullname, familyname, weight, italic_angle, fixed_pitch, \ ul_position, ul_thickness = font.get_ps_font_info() flags = 0 if fixed_pitch: flags |= 1 << 0 # fixed width if 0: flags |= 1 << 1 # TODO: serif if 1: flags |= 1 << 2 # TODO: symbolic (most TeX fonts are) else: flags |= 1 << 5 # non-symbolic if italic_angle: flags |= 1 << 6 # italic if 0: flags |= 1 << 16 # TODO: all caps if 0: flags |= 1 << 17 # TODO: small caps if 0: flags |= 1 << 18 # TODO: force bold descriptor = { 'Type': Name('FontDescriptor'), 'FontName': Name(font.postscript_name), 'Flags': flags, 'FontBBox': font.bbox, 'ItalicAngle': italic_angle, 'Ascent': font.ascender, 'Descent': font.descender, 'CapHeight': 1000, # TODO: find this out 'XHeight': 500, # TODO: this one too 'FontFile': fontfileObject, 'FontFamily': familyname, 'StemV': 50, # TODO # (see also revision 3874; but not all TeX distros have AFM files!) #'FontWeight': a number where 400 = Regular, 700 = Bold } self.writeObject(fontdictObject, fontdict) self.writeObject(widthsObject, fontinfo.widths) self.writeObject(fontdescObject, descriptor) t1font = type1font.Type1Font(filename) self.beginStream(fontfileObject.id, None, { 'Length1': len(t1font.parts[0]), 'Length2': len(t1font.parts[1]), 'Length3': 0 }) self.currentstream.write(t1font.parts[0]) self.currentstream.write(t1font.parts[1]) self.endStream() return fontdictObject def _get_xobject_symbol_name(self, filename, symbol_name): return "%s-%s" % ( os.path.splitext(os.path.basename(filename))[0], symbol_name) _identityToUnicodeCMap = """/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> <ffff> endcodespacerange %d beginbfrange %s endbfrange endcmap CMapName currentdict /CMap defineresource pop end end""" def embedTTF(self, filename, characters): """Embed the TTF font from the named file into the document.""" font = FT2Font(str(filename)) fonttype = rcParams['pdf.fonttype'] def cvt(length, upe=font.units_per_EM, nearest=True): "Convert font coordinates to PDF glyph coordinates" value = length / upe * 1000 if nearest: return round(value) # Perhaps best to round away from zero for bounding # boxes and the like if value < 0: return floor(value) else: return ceil(value) def embedTTFType3(font, characters, descriptor): """The Type 3-specific part of embedding a Truetype font""" widthsObject = self.reserveObject('font widths') fontdescObject = self.reserveObject('font descriptor') fontdictObject = self.reserveObject('font dictionary') charprocsObject = self.reserveObject('character procs') differencesArray = [] firstchar, lastchar = 0, 255 bbox = [cvt(x, nearest=False) for x in font.bbox] fontdict = { 'Type' : Name('Font'), 'BaseFont' : ps_name, 'FirstChar' : firstchar, 'LastChar' : lastchar, 'FontDescriptor' : fontdescObject, 'Subtype' : Name('Type3'), 'Name' : descriptor['FontName'], 'FontBBox' : bbox, 'FontMatrix' : [ .001, 0, 0, .001, 0, 0 ], 'CharProcs' : charprocsObject, 'Encoding' : { 'Type' : Name('Encoding'), 'Differences' : differencesArray}, 'Widths' : widthsObject } # Make the "Widths" array from encodings import cp1252 # The "decoding_map" was changed to a "decoding_table" as of Python 2.5. if hasattr(cp1252, 'decoding_map'): def decode_char(charcode): return cp1252.decoding_map[charcode] or 0 else: def decode_char(charcode): return ord(cp1252.decoding_table[charcode]) def get_char_width(charcode): unicode = decode_char(charcode) width = font.load_char(unicode, flags=LOAD_NO_SCALE|LOAD_NO_HINTING).horiAdvance return cvt(width) widths = [ get_char_width(charcode) for charcode in range(firstchar, lastchar+1) ] descriptor['MaxWidth'] = max(widths) # Make the "Differences" array, sort the ccodes < 255 from # the multi-byte ccodes, and build the whole set of glyph ids # that we need from this font. cmap = font.get_charmap() glyph_ids = [] differences = [] multi_byte_chars = set() for c in characters: ccode = c gind = cmap.get(ccode) or 0 glyph_ids.append(gind) glyph_name = font.get_glyph_name(gind) if ccode <= 255: differences.append((ccode, glyph_name)) else: multi_byte_chars.add(glyph_name) differences.sort() last_c = -2 for c, name in differences: if c != last_c + 1: differencesArray.append(c) differencesArray.append(Name(name)) last_c = c # Make the charprocs array (using ttconv to generate the # actual outlines) rawcharprocs = ttconv.get_pdf_charprocs(filename, glyph_ids) charprocs = {} charprocsRef = {} for charname, stream in rawcharprocs.items(): charprocDict = { 'Length': len(stream) } # The 2-byte characters are used as XObjects, so they # need extra info in their dictionary if charname in multi_byte_chars: charprocDict['Type'] = Name('XObject') charprocDict['Subtype'] = Name('Form') charprocDict['BBox'] = bbox # Each glyph includes bounding box information, # but xpdf and ghostscript can't handle it in a # Form XObject (they segfault!!!), so we remove it # from the stream here. It's not needed anyway, # since the Form XObject includes it in its BBox # value. stream = stream[stream.find("d1") + 2:] charprocObject = self.reserveObject('charProc') self.beginStream(charprocObject.id, None, charprocDict) self.currentstream.write(stream) self.endStream() # Send the glyphs with ccode > 255 to the XObject dictionary, # and the others to the font itself if charname in multi_byte_chars: name = self._get_xobject_symbol_name(filename, charname) self.multi_byte_charprocs[name] = charprocObject else: charprocs[charname] = charprocObject # Write everything out self.writeObject(fontdictObject, fontdict) self.writeObject(fontdescObject, descriptor) self.writeObject(widthsObject, widths) self.writeObject(charprocsObject, charprocs) return fontdictObject def embedTTFType42(font, characters, descriptor): """The Type 42-specific part of embedding a Truetype font""" fontdescObject = self.reserveObject('font descriptor') cidFontDictObject = self.reserveObject('CID font dictionary') type0FontDictObject = self.reserveObject('Type 0 font dictionary') cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') fontfileObject = self.reserveObject('font file stream') wObject = self.reserveObject('Type 0 widths') toUnicodeMapObject = self.reserveObject('ToUnicode map') cidFontDict = { 'Type' : Name('Font'), 'Subtype' : Name('CIDFontType2'), 'BaseFont' : ps_name, 'CIDSystemInfo' : { 'Registry' : 'Adobe', 'Ordering' : 'Identity', 'Supplement' : 0 }, 'FontDescriptor' : fontdescObject, 'W' : wObject, 'CIDToGIDMap' : cidToGidMapObject } type0FontDict = { 'Type' : Name('Font'), 'Subtype' : Name('Type0'), 'BaseFont' : ps_name, 'Encoding' : Name('Identity-H'), 'DescendantFonts' : [cidFontDictObject], 'ToUnicode' : toUnicodeMapObject } # Make fontfile stream descriptor['FontFile2'] = fontfileObject length1Object = self.reserveObject('decoded length of a font') self.beginStream( fontfileObject.id, self.reserveObject('length of font stream'), {'Length1': length1Object}) fontfile = open(filename, 'rb') length1 = 0 while True: data = fontfile.read(4096) if not data: break length1 += len(data) self.currentstream.write(data) fontfile.close() self.endStream() self.writeObject(length1Object, length1) # Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap # at the same time cid_to_gid_map = [u'\u0000'] * 65536 cmap = font.get_charmap() unicode_mapping = [] widths = [] max_ccode = 0 for c in characters: ccode = c gind = cmap.get(ccode) or 0 glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) widths.append((ccode, glyph.horiAdvance / 6)) if ccode < 65536: cid_to_gid_map[ccode] = unichr(gind) max_ccode = max(ccode, max_ccode) widths.sort() cid_to_gid_map = cid_to_gid_map[:max_ccode + 1] last_ccode = -2 w = [] max_width = 0 unicode_groups = [] for ccode, width in widths: if ccode != last_ccode + 1: w.append(ccode) w.append([width]) unicode_groups.append([ccode, ccode]) else: w[-1].append(width) unicode_groups[-1][1] = ccode max_width = max(max_width, width) last_ccode = ccode unicode_bfrange = [] for start, end in unicode_groups: unicode_bfrange.append( "<%04x> <%04x> [%s]" % (start, end, " ".join(["<%04x>" % x for x in range(start, end+1)]))) unicode_cmap = (self._identityToUnicodeCMap % (len(unicode_groups), "\n".join(unicode_bfrange))) # CIDToGIDMap stream cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be") self.beginStream(cidToGidMapObject.id, None, {'Length': len(cid_to_gid_map)}) self.currentstream.write(cid_to_gid_map) self.endStream() # ToUnicode CMap self.beginStream(toUnicodeMapObject.id, None, {'Length': unicode_cmap}) self.currentstream.write(unicode_cmap) self.endStream() descriptor['MaxWidth'] = max_width # Write everything out self.writeObject(cidFontDictObject, cidFontDict) self.writeObject(type0FontDictObject, type0FontDict) self.writeObject(fontdescObject, descriptor) self.writeObject(wObject, w) return type0FontDictObject # Beginning of main embedTTF function... # You are lost in a maze of TrueType tables, all different... ps_name = Name(font.get_sfnt()[(1,0,0,6)]) pclt = font.get_sfnt_table('pclt') \ or { 'capHeight': 0, 'xHeight': 0 } post = font.get_sfnt_table('post') \ or { 'italicAngle': (0,0) } ff = font.face_flags sf = font.style_flags flags = 0 symbolic = False #ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10') if ff & FIXED_WIDTH: flags |= 1 << 0 if 0: flags |= 1 << 1 # TODO: serif if symbolic: flags |= 1 << 2 else: flags |= 1 << 5 if sf & ITALIC: flags |= 1 << 6 if 0: flags |= 1 << 16 # TODO: all caps if 0: flags |= 1 << 17 # TODO: small caps if 0: flags |= 1 << 18 # TODO: force bold descriptor = { 'Type' : Name('FontDescriptor'), 'FontName' : ps_name, 'Flags' : flags, 'FontBBox' : [ cvt(x, nearest=False) for x in font.bbox ], 'Ascent' : cvt(font.ascender, nearest=False), 'Descent' : cvt(font.descender, nearest=False), 'CapHeight' : cvt(pclt['capHeight'], nearest=False), 'XHeight' : cvt(pclt['xHeight']), 'ItalicAngle' : post['italicAngle'][1], # ??? 'StemV' : 0 # ??? } # The font subsetting to a Type 3 font does not work for # OpenType (.otf) that embed a Postscript CFF font, so avoid that -- # save as a (non-subsetted) Type 42 font instead. if is_opentype_cff_font(filename): fonttype = 42 warnings.warn(("'%s' can not be subsetted into a Type 3 font. " + "The entire font will be embedded in the output.") % os.path.basename(filename)) if fonttype == 3: return embedTTFType3(font, characters, descriptor) elif fonttype == 42: return embedTTFType42(font, characters, descriptor) def alphaState(self, alpha): """Return name of an ExtGState that sets alpha to the given value""" state = self.alphaStates.get(alpha, None) if state is not None: return state[0] name = Name('A%d' % self.nextAlphaState) self.nextAlphaState += 1 self.alphaStates[alpha] = \ (name, { 'Type': Name('ExtGState'), 'CA': alpha, 'ca': alpha }) return name def hatchPattern(self, lst): pattern = self.hatchPatterns.get(lst, None) if pattern is not None: return pattern[0] name = Name('H%d' % self.nextHatch) self.nextHatch += 1 self.hatchPatterns[lst] = name return name def writeHatches(self): hatchDict = dict() sidelen = 144.0 density = 24.0 for lst, name in self.hatchPatterns.items(): ob = self.reserveObject('hatch pattern') hatchDict[name] = ob res = { 'Procsets': [ Name(x) for x in "PDF Text ImageB ImageC ImageI".split() ] } self.beginStream( ob.id, None, { 'Type': Name('Pattern'), 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, 'BBox': [0, 0, sidelen, sidelen], 'XStep': sidelen, 'YStep': sidelen, 'Resources': res }) # lst is a tuple of stroke color, fill color, # number of - lines, number of / lines, # number of | lines, number of \ lines rgb = lst[0] self.output(rgb[0], rgb[1], rgb[2], Op.setrgb_stroke) if lst[1] is not None: rgb = lst[1] self.output(rgb[0], rgb[1], rgb[2], Op.setrgb_nonstroke, 0, 0, sidelen, sidelen, Op.rectangle, Op.fill) if lst[2]: # - for j in npy.arange(0.0, sidelen, density/lst[2]): self.output(0, j, Op.moveto, sidelen, j, Op.lineto) if lst[3]: # / for j in npy.arange(0.0, sidelen, density/lst[3]): self.output(0, j, Op.moveto, sidelen-j, sidelen, Op.lineto, sidelen-j, 0, Op.moveto, sidelen, j, Op.lineto) if lst[4]: # | for j in npy.arange(0.0, sidelen, density/lst[4]): self.output(j, 0, Op.moveto, j, sidelen, Op.lineto) if lst[5]: # \ for j in npy.arange(sidelen, 0.0, -density/lst[5]): self.output(sidelen, j, Op.moveto, j, sidelen, Op.lineto, j, 0, Op.moveto, 0, j, Op.lineto) self.output(Op.stroke) self.endStream() self.writeObject(self.hatchObject, hatchDict) def imageObject(self, image): """Return name of an image XObject representing the given image.""" pair = self.images.get(image, None) if pair is not None: return pair[0] name = Name('I%d' % self.nextImage) ob = self.reserveObject('image %d' % self.nextImage) self.nextImage += 1 self.images[image] = (name, ob) return name ## These two from backend_ps.py ## TODO: alpha (SMask, p. 518 of pdf spec) def _rgb(self, im): h,w,s = im.as_rgba_str() rgba = npy.fromstring(s, npy.uint8) rgba.shape = (h, w, 4) rgb = rgba[:,:,:3] a = rgba[:,:,3:] return h, w, rgb.tostring(), a.tostring() def _gray(self, im, rc=0.3, gc=0.59, bc=0.11): rgbat = im.as_rgba_str() rgba = npy.fromstring(rgbat[2], npy.uint8) rgba.shape = (rgbat[0], rgbat[1], 4) rgba_f = rgba.astype(npy.float32) r = rgba_f[:,:,0] g = rgba_f[:,:,1] b = rgba_f[:,:,2] gray = (r*rc + g*gc + b*bc).astype(npy.uint8) return rgbat[0], rgbat[1], gray.tostring() def writeImages(self): for img, pair in self.images.items(): img.flipud_out() if img.is_grayscale: height, width, data = self._gray(img) self.beginStream( pair[1].id, self.reserveObject('length of image stream'), {'Type': Name('XObject'), 'Subtype': Name('Image'), 'Width': width, 'Height': height, 'ColorSpace': Name('DeviceGray'), 'BitsPerComponent': 8 }) self.currentstream.write(data) # TODO: predictors (i.e., output png) self.endStream() else: height, width, data, adata = self._rgb(img) smaskObject = self.reserveObject("smask") stream = self.beginStream( smaskObject.id, self.reserveObject('length of smask stream'), {'Type': Name('XObject'), 'Subtype': Name('Image'), 'Width': width, 'Height': height, 'ColorSpace': Name('DeviceGray'), 'BitsPerComponent': 8 }) self.currentstream.write(adata) # TODO: predictors (i.e., output png) self.endStream() self.beginStream( pair[1].id, self.reserveObject('length of image stream'), {'Type': Name('XObject'), 'Subtype': Name('Image'), 'Width': width, 'Height': height, 'ColorSpace': Name('DeviceRGB'), 'BitsPerComponent': 8, 'SMask': smaskObject}) self.currentstream.write(data) # TODO: predictors (i.e., output png) self.endStream() img.flipud_out() def markerObject(self, path, trans, fillp, lw): """Return name of a marker XObject representing the given path.""" key = (path, trans, fillp is not None, lw) result = self.markers.get(key) if result is None: name = Name('M%d' % len(self.markers)) ob = self.reserveObject('marker %d' % len(self.markers)) self.markers[key] = (name, ob, path, trans, fillp, lw) else: name = result[0] return name def writeMarkers(self): for tup in self.markers.values(): name, object, path, trans, fillp, lw = tup bbox = path.get_extents(trans) bbox = bbox.padded(lw * 0.5) self.beginStream( object.id, None, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': list(bbox.extents) }) self.writePath(path, trans) if fillp: self.output(Op.fill_stroke) else: self.output(Op.stroke) self.endStream() #@staticmethod def pathOperations(path, transform, simplify=None): tpath = transform.transform_path(path) cmds = [] last_points = None for points, code in tpath.iter_segments(simplify): if code == Path.MOVETO: cmds.extend(points) cmds.append(Op.moveto) elif code == Path.LINETO: cmds.extend(points) cmds.append(Op.lineto) elif code == Path.CURVE3: points = quad2cubic(*(list(last_points[-2:]) + list(points))) cmds.extend(points[2:]) cmds.append(Op.curveto) elif code == Path.CURVE4: cmds.extend(points) cmds.append(Op.curveto) elif code == Path.CLOSEPOLY: cmds.append(Op.closepath) last_points = points return cmds pathOperations = staticmethod(pathOperations) def writePath(self, path, transform): cmds = self.pathOperations( path, transform, self.simplify) self.output(*cmds) def reserveObject(self, name=''): """Reserve an ID for an indirect object. The name is used for debugging in case we forget to print out the object with writeObject. """ id = self.nextObject self.nextObject += 1 self.xrefTable.append([None, 0, name]) return Reference(id) def recordXref(self, id): self.xrefTable[id][0] = self.fh.tell() def writeObject(self, object, contents): self.recordXref(object.id) object.write(contents, self) def writeXref(self): """Write out the xref table.""" self.startxref = self.fh.tell() self.write("xref\n0 %d\n" % self.nextObject) i = 0 borken = False for offset, generation, name in self.xrefTable: if offset is None: print >>sys.stderr, \ 'No offset for object %d (%s)' % (i, name) borken = True else: self.write("%010d %05d n \n" % (offset, generation)) i += 1 if borken: raise AssertionError, 'Indirect object does not exist' def writeTrailer(self): """Write out the PDF trailer.""" self.write("trailer\n") self.write(pdfRepr( {'Size': self.nextObject, 'Root': self.rootObject, 'Info': self.infoObject })) # Could add 'ID' self.write("\nstartxref\n%d\n%%%%EOF\n" % self.startxref) class RendererPdf(RendererBase): truetype_font_cache = maxdict(50) afm_font_cache = maxdict(50) def __init__(self, file, dpi, image_dpi): RendererBase.__init__(self) self.file = file self.gc = self.new_gc() self.file.used_characters = self.used_characters = {} self.mathtext_parser = MathTextParser("Pdf") self.dpi = dpi self.image_dpi = image_dpi self.tex_font_map = None def finalize(self): self.file.output(*self.gc.finalize()) def check_gc(self, gc, fillcolor=None): orig_fill = gc._fillcolor gc._fillcolor = fillcolor delta = self.gc.delta(gc) if delta: self.file.output(*delta) # Restore gc to avoid unwanted side effects gc._fillcolor = orig_fill def tex_font_mapping(self, texfont): if self.tex_font_map is None: self.tex_font_map = \ dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) return self.tex_font_map[texfont] def track_characters(self, font, s): """Keeps track of which characters are required from each font.""" if isinstance(font, (str, unicode)): fname = font else: fname = font.fname realpath, stat_key = get_realpath_and_stat(fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s]) def merge_used_characters(self, other): for stat_key, (realpath, charset) in other.items(): used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update(charset) def get_image_magnification(self): return self.image_dpi/72.0 def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # MGDTODO: Support clippath here gc = self.new_gc() if bbox is not None: gc.set_clip_rectangle(bbox) self.check_gc(gc) h, w = im.get_size_out() h, w = 72.0*h/self.image_dpi, 72.0*w/self.image_dpi imob = self.file.imageObject(im) self.file.output(Op.gsave, w, 0, 0, h, x, y, Op.concat_matrix, imob, Op.use_xobject, Op.grestore) def draw_path(self, gc, path, transform, rgbFace=None): self.check_gc(gc, rgbFace) stream = self.file.writePath(path, transform) self.file.output(self.gc.paint()) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): self.check_gc(gc, rgbFace) fillp = rgbFace is not None output = self.file.output marker = self.file.markerObject( marker_path, marker_trans, fillp, self.gc._linewidth) tpath = trans.transform_path(path) output(Op.gsave) lastx, lasty = 0, 0 for vertices, code in tpath.iter_segments(): if len(vertices): x, y = vertices[-2:] dx, dy = x - lastx, y - lasty output(1, 0, 0, 1, dx, dy, Op.concat_matrix, marker, Op.use_xobject) lastx, lasty = x, y output(Op.grestore) def _setup_textpos(self, x, y, descent, angle, oldx=0, oldy=0, olddescent=0, oldangle=0): if angle == oldangle == 0: self.file.output(x - oldx, (y + descent) - (oldy + olddescent), Op.textpos) else: angle = angle / 180.0 * pi self.file.output( cos(angle), sin(angle), -sin(angle), cos(angle), x, y, Op.textmatrix) self.file.output(0, descent, Op.textpos) def draw_mathtext(self, gc, x, y, s, prop, angle): # TODO: fix positioning and encoding width, height, descent, glyphs, rects, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) self.merge_used_characters(used_characters) # When using Type 3 fonts, we can't use character codes higher # than 255, so we use the "Do" command to render those # instead. global_fonttype = rcParams['pdf.fonttype'] # Set up a global transformation matrix for the whole math expression a = angle / 180.0 * pi self.file.output(Op.gsave) self.file.output(cos(a), sin(a), -sin(a), cos(a), x, y, Op.concat_matrix) self.check_gc(gc, gc._rgb) self.file.output(Op.begin_text) prev_font = None, None oldx, oldy = 0, 0 for ox, oy, fontname, fontsize, num, symbol_name in glyphs: if is_opentype_cff_font(fontname): fonttype = 42 else: fonttype = global_fonttype if fonttype == 42 or num <= 255: self._setup_textpos(ox, oy, 0, 0, oldx, oldy) oldx, oldy = ox, oy if (fontname, fontsize) != prev_font: fontsize *= self.dpi/72.0 self.file.output(self.file.fontName(fontname), fontsize, Op.selectfont) prev_font = fontname, fontsize self.file.output(self.encode_string(unichr(num), fonttype), Op.show) self.file.output(Op.end_text) # If using Type 3 fonts, render all of the multi-byte characters # as XObjects using the 'Do' command. if global_fonttype == 3: for ox, oy, fontname, fontsize, num, symbol_name in glyphs: fontsize *= self.dpi/72.0 if is_opentype_cff_font(fontname): fonttype = 42 else: fonttype = global_fonttype if fonttype == 3 and num > 255: self.file.fontName(fontname) self.file.output(Op.gsave, 0.001 * fontsize, 0, 0, 0.001 * fontsize, ox, oy, Op.concat_matrix) name = self.file._get_xobject_symbol_name( fontname, symbol_name) self.file.output(Name(name), Op.use_xobject) self.file.output(Op.grestore) # Draw any horizontal lines in the math layout for ox, oy, width, height in rects: self.file.output(Op.gsave, ox, oy, width, height, Op.rectangle, Op.fill, Op.grestore) # Pop off the global transformation self.file.output(Op.grestore) def draw_tex(self, gc, x, y, s, prop, angle): texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() dvifile = texmanager.make_dvi(s, fontsize) dvi = dviread.Dvi(dvifile, self.dpi) page = iter(dvi).next() dvi.close() # Gather font information and do some setup for combining # characters into strings. oldfont, seq = None, [] for x1, y1, dvifont, glyph, width in page.text: if dvifont != oldfont: psfont = self.tex_font_mapping(dvifont.texname) pdfname = self.file.fontName(psfont.filename) if self.file.fontInfo.get(pdfname, None) is None: self.file.fontInfo[pdfname] = Bunch( encodingfile=psfont.encoding, widths=dvifont.widths, dvifont=dvifont) seq += [['font', pdfname, dvifont.size]] oldfont = dvifont seq += [['text', x1, y1, [chr(glyph)], x1+width]] # Find consecutive text strings with constant x coordinate and # combine into a sequence of strings and kerns, or just one # string (if any kerns would be less than 0.1 points). i, curx = 0, 0 while i < len(seq)-1: elt, next = seq[i:i+2] if elt[0] == next[0] == 'text' and elt[2] == next[2]: offset = elt[4] - next[1] if abs(offset) < 0.1: elt[3][-1] += next[3][0] elt[4] += next[4]-next[1] else: elt[3] += [offset*1000.0/dvifont.size, next[3][0]] elt[4] = next[4] del seq[i+1] continue i += 1 # Create a transform to map the dvi contents to the canvas. mytrans = Affine2D().rotate_deg(angle).translate(x, y) # Output the text. self.check_gc(gc, gc._rgb) self.file.output(Op.begin_text) curx, cury, oldx, oldy = 0, 0, 0, 0 for elt in seq: if elt[0] == 'font': self.file.output(elt[1], elt[2], Op.selectfont) elif elt[0] == 'text': curx, cury = mytrans.transform((elt[1], elt[2])) self._setup_textpos(curx, cury, 0, angle, oldx, oldy) oldx, oldy = curx, cury if len(elt[3]) == 1: self.file.output(elt[3][0], Op.show) else: self.file.output(elt[3], Op.showkern) else: assert False self.file.output(Op.end_text) # Then output the boxes (e.g. variable-length lines of square # roots). boxgc = self.new_gc() boxgc.copy_properties(gc) boxgc.set_linewidth(0) pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] for x1, y1, h, w in page.boxes: path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h], [0,0]], pathops) self.draw_path(boxgc, path, mytrans, gc._rgb) def encode_string(self, s, fonttype): if fonttype == 3: return s.encode('cp1252', 'replace') return s.encode('utf-16be', 'replace') def draw_text(self, gc, x, y, s, prop, angle, ismath=False): # TODO: combine consecutive texts into one BT/ET delimited section # This function is rather complex, since there is no way to # access characters of a Type 3 font with codes > 255. (Type # 3 fonts can not have a CIDMap). Therefore, we break the # string into chunks, where each chunk contains exclusively # 1-byte or exclusively 2-byte characters, and output each # chunk a separate command. 1-byte characters use the regular # text show command (Tj), whereas 2-byte characters use the # use XObject command (Do). If using Type 42 fonts, all of # this complication is avoided, but of course, those fonts can # not be subsetted. self.check_gc(gc, gc._rgb) if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) fontsize = prop.get_size_in_points() * self.dpi/72.0 if rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) l, b, w, h = font.get_str_bbox(s) descent = -b * fontsize / 1000 fonttype = 42 else: font = self._get_font_ttf(prop) self.track_characters(font, s) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) descent = font.get_descent() / 64.0 fonttype = rcParams['pdf.fonttype'] # We can't subset all OpenType fonts, so switch to Type 42 # in that case. if is_opentype_cff_font(font.fname): fonttype = 42 def check_simple_method(s): """Determine if we should use the simple or woven method to output this text, and chunks the string into 1-byte and 2-byte sections if necessary.""" use_simple_method = True chunks = [] if not rcParams['pdf.use14corefonts']: if fonttype == 3 and not isinstance(s, str) and len(s) != 0: # Break the string into chunks where each chunk is either # a string of chars <= 255, or a single character > 255. s = unicode(s) for c in s: if ord(c) <= 255: char_type = 1 else: char_type = 2 if len(chunks) and chunks[-1][0] == char_type: chunks[-1][1].append(c) else: chunks.append((char_type, [c])) use_simple_method = (len(chunks) == 1 and chunks[-1][0] == 1) return use_simple_method, chunks def draw_text_simple(): """Outputs text using the simple method.""" self.file.output(Op.begin_text, self.file.fontName(prop), fontsize, Op.selectfont) self._setup_textpos(x, y, descent, angle) self.file.output(self.encode_string(s, fonttype), Op.show, Op.end_text) def draw_text_woven(chunks): """Outputs text using the woven method, alternating between chunks of 1-byte characters and 2-byte characters. Only used for Type 3 fonts.""" chunks = [(a, ''.join(b)) for a, b in chunks] cmap = font.get_charmap() # Do the rotation and global translation as a single matrix # concatenation up front self.file.output(Op.gsave) a = angle / 180.0 * pi self.file.output(cos(a), sin(a), -sin(a), cos(a), x, y, Op.concat_matrix) # Output all the 1-byte characters in a BT/ET group, then # output all the 2-byte characters. for mode in (1, 2): newx = oldx = 0 olddescent = 0 # Output a 1-byte character chunk if mode == 1: self.file.output(Op.begin_text, self.file.fontName(prop), fontsize, Op.selectfont) for chunk_type, chunk in chunks: if mode == 1 and chunk_type == 1: self._setup_textpos(newx, 0, descent, 0, oldx, 0, olddescent, 0) self.file.output(self.encode_string(chunk, fonttype), Op.show) oldx = newx olddescent = descent lastgind = None for c in chunk: ccode = ord(c) gind = cmap.get(ccode) if gind is not None: if mode == 2 and chunk_type == 2: glyph_name = font.get_glyph_name(gind) self.file.output(Op.gsave) self.file.output(0.001 * fontsize, 0, 0, 0.001 * fontsize, newx, 0, Op.concat_matrix) name = self.file._get_xobject_symbol_name( font.fname, glyph_name) self.file.output(Name(name), Op.use_xobject) self.file.output(Op.grestore) # Move the pointer based on the character width # and kerning glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if lastgind is not None: kern = font.get_kerning( lastgind, gind, KERNING_UNFITTED) else: kern = 0 lastgind = gind newx += kern/64.0 + glyph.linearHoriAdvance/65536.0 if mode == 1: self.file.output(Op.end_text) self.file.output(Op.grestore) use_simple_method, chunks = check_simple_method(s) if use_simple_method: return draw_text_simple() else: return draw_text_woven(chunks) def get_text_width_height_descent(self, s, prop, ismath): if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() dvifile = texmanager.make_dvi(s, fontsize) dvi = dviread.Dvi(dvifile, self.dpi) page = iter(dvi).next() dvi.close() # A total height (including the descent) needs to be returned. return page.width, page.height+page.descent, page.descent if ismath: w, h, d, glyphs, rects, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) elif rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) l, b, w, h, d = font.get_str_bbox_and_descent(s) scale = prop.get_size_in_points() w *= scale h *= scale d *= scale else: font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() scale = (1.0 / 64.0) w *= scale h *= scale d = font.get_descent() d *= scale return w, h, d def _get_font_afm(self, prop): key = hash(prop) font = self.afm_font_cache.get(key) if font is None: filename = findfont(prop, fontext='afm') font = self.afm_font_cache.get(filename) if font is None: fh = file(filename) font = AFM(fh) self.afm_font_cache[filename] = font fh.close() self.afm_font_cache[key] = font return font def _get_font_ttf(self, prop): key = hash(prop) font = self.truetype_font_cache.get(key) if font is None: filename = findfont(prop) font = self.truetype_font_cache.get(filename) if font is None: font = FT2Font(str(filename)) self.truetype_font_cache[filename] = font self.truetype_font_cache[key] = font font.clear() font.set_size(prop.get_size_in_points(), self.dpi) return font def flipy(self): return False def get_canvas_width_height(self): return self.file.width / self.dpi, self.file.height / self.dpi def new_gc(self): return GraphicsContextPdf(self.file) class GraphicsContextPdf(GraphicsContextBase): def __init__(self, file): GraphicsContextBase.__init__(self) self._fillcolor = (0.0, 0.0, 0.0) self.file = file self.parent = None def __repr__(self): d = dict(self.__dict__) del d['file'] del d['parent'] return `d` def _strokep(self): return (self._linewidth > 0 and self._alpha > 0 and (len(self._rgb) <= 3 or self._rgb[3] != 0.0)) def _fillp(self): return ((self._fillcolor is not None or self._hatch) and (len(self._fillcolor) <= 3 or self._fillcolor[3] != 0.0)) def close_and_paint(self): if self._strokep(): if self._fillp(): return Op.close_fill_stroke else: return Op.close_stroke else: if self._fillp(): return Op.fill else: return Op.endpath def paint(self): if self._strokep(): if self._fillp(): return Op.fill_stroke else: return Op.stroke else: if self._fillp(): return Op.fill else: return Op.endpath capstyles = { 'butt': 0, 'round': 1, 'projecting': 2 } joinstyles = { 'miter': 0, 'round': 1, 'bevel': 2 } def capstyle_cmd(self, style): return [self.capstyles[style], Op.setlinecap] def joinstyle_cmd(self, style): return [self.joinstyles[style], Op.setlinejoin] def linewidth_cmd(self, width): return [width, Op.setlinewidth] def dash_cmd(self, dashes): offset, dash = dashes if dash is None: dash = [] offset = 0 return [list(dash), offset, Op.setdash] def alpha_cmd(self, alpha): name = self.file.alphaState(alpha) return [name, Op.setgstate] def hatch_cmd(self, hatch): if not hatch: if self._fillcolor is not None: return self.fillcolor_cmd(self._fillcolor) else: return [Name('DeviceRGB'), Op.setcolorspace_nonstroke] else: hatch = hatch.lower() lst = ( self._rgb, self._fillcolor, hatch.count('-') + hatch.count('+'), hatch.count('/') + hatch.count('x'), hatch.count('|') + hatch.count('+'), hatch.count('\\') + hatch.count('x') ) name = self.file.hatchPattern(lst) return [Name('Pattern'), Op.setcolorspace_nonstroke, name, Op.setcolor_nonstroke] def rgb_cmd(self, rgb): if rcParams['pdf.inheritcolor']: return [] if rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_stroke] else: return list(rgb[:3]) + [Op.setrgb_stroke] def fillcolor_cmd(self, rgb): if rgb is None or rcParams['pdf.inheritcolor']: return [] elif rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_nonstroke] else: return list(rgb[:3]) + [Op.setrgb_nonstroke] def push(self): parent = GraphicsContextPdf(self.file) parent.copy_properties(self) parent.parent = self.parent self.parent = parent return [Op.gsave] def pop(self): assert self.parent is not None self.copy_properties(self.parent) self.parent = self.parent.parent return [Op.grestore] def clip_cmd(self, cliprect, clippath): """Set clip rectangle. Calls self.pop() and self.push().""" cmds = [] # Pop graphics state until we hit the right one or the stack is empty while (self._cliprect, self._clippath) != (cliprect, clippath) \ and self.parent is not None: cmds.extend(self.pop()) # Unless we hit the right one, set the clip polygon if (self._cliprect, self._clippath) != (cliprect, clippath): cmds.extend(self.push()) if self._cliprect != cliprect: cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) if self._clippath != clippath: cmds.extend( PdfFile.pathOperations( *clippath.get_transformed_path_and_affine()) + [Op.clip, Op.endpath]) return cmds commands = ( (('_cliprect', '_clippath'), clip_cmd), # must come first since may pop (('_alpha',), alpha_cmd), (('_capstyle',), capstyle_cmd), (('_fillcolor',), fillcolor_cmd), (('_joinstyle',), joinstyle_cmd), (('_linewidth',), linewidth_cmd), (('_dashes',), dash_cmd), (('_rgb',), rgb_cmd), (('_hatch',), hatch_cmd), # must come after fillcolor and rgb ) # TODO: _linestyle def delta(self, other): """ Copy properties of other into self and return PDF commands needed to transform self into other. """ cmds = [] for params, cmd in self.commands: different = False for p in params: ours = getattr(self, p) theirs = getattr(other, p) try: different = bool(ours != theirs) except ValueError: ours = npy.asarray(ours) theirs = npy.asarray(theirs) different = ours.shape != theirs.shape or npy.any(ours != theirs) if different: break if different: theirs = [getattr(other, p) for p in params] cmds.extend(cmd(self, *theirs)) for p in params: setattr(self, p, getattr(other, p)) return cmds def copy_properties(self, other): """ Copy properties of other into self. """ GraphicsContextBase.copy_properties(self, other) self._fillcolor = other._fillcolor def finalize(self): """ Make sure every pushed graphics state is popped. """ cmds = [] while self.parent is not None: cmds.extend(self.pop()) return cmds ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # if a main-level app must be created, this is the usual place to # do it -- see backend_wx, backend_wxagg and backend_tkagg for # examples. Not all GUIs require explicit instantiation of a # main-level app (egg backend_gtk, backend_gtkagg) for pylab FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasPdf(thisFig) manager = FigureManagerPdf(canvas, num) return manager class FigureCanvasPdf(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def draw(self): pass filetypes = {'pdf': 'Portable Document Format'} def get_default_filetype(self): return 'pdf' def print_pdf(self, filename, **kwargs): ppi = 72 # Postscript points in an inch image_dpi = kwargs.get('dpi', 72) # dpi to use for images self.figure.set_dpi(ppi) width, height = self.figure.get_size_inches() file = PdfFile(width, height, ppi, filename) renderer = MixedModeRenderer( width, height, ppi, RendererPdf(file, ppi, image_dpi)) self.figure.draw(renderer) renderer.finalize() file.close() class FigureManagerPdf(FigureManagerBase): pass FigureManager = FigureManagerPdf
71,773
Python
.py
1,642
31.643727
96
0.547361
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,301
backend_macosx.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_macosx.py
from __future__ import division import os import numpy from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase, NavigationToolbar2 from matplotlib.cbook import maxdict from matplotlib.figure import Figure from matplotlib.path import Path from matplotlib.mathtext import MathTextParser from matplotlib.colors import colorConverter from matplotlib.widgets import SubplotTool import matplotlib from matplotlib.backends import _macosx def show(): """Show all the figures and enter the Cocoa mainloop. This function will not return until all windows are closed or the interpreter exits.""" # Having a Python-level function "show" wrapping the built-in # function "show" in the _macosx extension module allows us to # to add attributes to "show". This is something ipython does. _macosx.show() class RendererMac(RendererBase): """ The renderer handles drawing/rendering operations. Most of the renderer's methods forwards the command to the renderer's graphics context. The renderer does not wrap a C object and is written in pure Python. """ texd = maxdict(50) # a cache of tex image rasters def __init__(self, dpi, width, height): RendererBase.__init__(self) self.dpi = dpi self.width = width self.height = height self.gc = GraphicsContextMac() self.mathtext_parser = MathTextParser('MacOSX') def set_width_height (self, width, height): self.width, self.height = width, height def draw_path(self, gc, path, transform, rgbFace=None): if rgbFace is not None: rgbFace = tuple(rgbFace) if gc!=self.gc: n = self.gc.level() - gc.level() for i in range(n): self.gc.restore() self.gc = gc gc.draw_path(path, transform, rgbFace) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): if rgbFace is not None: rgbFace = tuple(rgbFace) if gc!=self.gc: n = self.gc.level() - gc.level() for i in range(n): self.gc.restore() self.gc = gc gc.draw_markers(marker_path, marker_trans, path, trans, rgbFace) def draw_path_collection(self, *args): gc = self.gc args = args[:13] gc.draw_path_collection(*args) def draw_quad_mesh(self, *args): gc = self.gc gc.draw_quad_mesh(*args) def new_gc(self): self.gc.reset() return self.gc def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): im.flipud_out() nrows, ncols, data = im.as_rgba_str() self.gc.draw_image(x, y, nrows, ncols, data, bbox, clippath, clippath_trans) im.flipud_out() def draw_tex(self, gc, x, y, s, prop, angle): if gc!=self.gc: n = self.gc.level() - gc.level() for i in range(n): self.gc.restore() self.gc = gc # todo, handle props, angle, origins size = prop.get_size_in_points() texmanager = self.get_texmanager() key = s, size, self.dpi, angle, texmanager.get_font_config() im = self.texd.get(key) # Not sure what this does; just copied from backend_agg.py if im is None: Z = texmanager.get_grey(s, size, self.dpi) Z = numpy.array(255.0 - Z * 255.0, numpy.uint8) gc.draw_mathtext(x, y, angle, Z) def _draw_mathtext(self, gc, x, y, s, prop, angle): if gc!=self.gc: n = self.gc.level() - gc.level() for i in range(n): self.gc.restore() self.gc = gc size = prop.get_size_in_points() ox, oy, width, height, descent, image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) gc.draw_mathtext(x, y, angle, 255 - image.as_array()) def draw_text(self, gc, x, y, s, prop, angle, ismath=False): if gc!=self.gc: n = self.gc.level() - gc.level() for i in range(n): self.gc.restore() self.gc = gc if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: family = prop.get_family() size = prop.get_size_in_points() weight = prop.get_weight() style = prop.get_style() gc.draw_text(x, y, unicode(s), family, size, weight, style, angle) def get_text_width_height_descent(self, s, prop, ismath): if ismath=='TeX': # TODO: handle props size = prop.get_size_in_points() texmanager = self.get_texmanager() Z = texmanager.get_grey(s, size, self.dpi) m,n = Z.shape # TODO: handle descent; This is based on backend_agg.py return n, m, 0 if ismath: ox, oy, width, height, descent, fonts, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent family = prop.get_family() size = prop.get_size_in_points() weight = prop.get_weight() style = prop.get_style() return self.gc.get_text_width_height_descent(unicode(s), family, size, weight, style) def flipy(self): return False def points_to_pixels(self, points): return points/72.0 * self.dpi def option_image_nocomposite(self): return True class GraphicsContextMac(_macosx.GraphicsContext, GraphicsContextBase): """ The GraphicsContext wraps a Quartz graphics context. All methods are implemented at the C-level in macosx.GraphicsContext. These methods set drawing properties such as the line style, fill color, etc. The actual drawing is done by the Renderer, which draws into the GraphicsContext. """ def __init__(self): GraphicsContextBase.__init__(self) _macosx.GraphicsContext.__init__(self) def set_foreground(self, fg, isRGB=False): if not isRGB: fg = colorConverter.to_rgb(fg) _macosx.GraphicsContext.set_foreground(self, fg) def set_clip_rectangle(self, box): GraphicsContextBase.set_clip_rectangle(self, box) if not box: return _macosx.GraphicsContext.set_clip_rectangle(self, box.bounds) def set_clip_path(self, path): GraphicsContextBase.set_clip_path(self, path) if not path: return path = path.get_fully_transformed_path() _macosx.GraphicsContext.set_clip_path(self, path) ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def draw_if_interactive(): """ For performance reasons, we don't want to redraw the figure after each draw command. Instead, we mark the figure as invalid, so that it will be redrawn as soon as the event loop resumes via PyOS_InputHook. This function should be called after each draw event, even if matplotlib is not running interactively. """ figManager = Gcf.get_active() if figManager is not None: figManager.canvas.invalidate() def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) canvas = FigureCanvasMac(figure) manager = FigureManagerMac(canvas, num) return manager class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance Events such as button presses, mouse movements, and key presses are handled in the C code and the base class methods button_press_event, button_release_event, motion_notify_event, key_press_event, and key_release_event are called from there. """ def __init__(self, figure): FigureCanvasBase.__init__(self, figure) width, height = self.get_width_height() self.renderer = RendererMac(figure.dpi, width, height) _macosx.FigureCanvas.__init__(self, width, height) def resize(self, width, height): self.renderer.set_width_height(width, height) dpi = self.figure.dpi width /= dpi height /= dpi self.figure.set_size_inches(width, height) def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', **kwargs): if dpi is None: dpi = matplotlib.rcParams['savefig.dpi'] filename = unicode(filename) root, ext = os.path.splitext(filename) ext = ext[1:].lower() if not ext: ext = "png" filename = root + "." + ext if ext=="jpg": ext = "jpeg" # save the figure settings origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() # set the new parameters self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) if ext in ('jpeg', 'png', 'tiff', 'gif', 'bmp'): width, height = self.figure.get_size_inches() width, height = width*dpi, height*dpi self.write_bitmap(filename, width, height) elif ext == 'pdf': self.write_pdf(filename) elif ext in ('ps', 'eps'): from backend_ps import FigureCanvasPS # Postscript backend changes figure.dpi, but doesn't change it back origDPI = self.figure.dpi fc = self.switch_backends(FigureCanvasPS) fc.print_figure(filename, dpi, facecolor, edgecolor, orientation, **kwargs) self.figure.dpi = origDPI self.figure.set_canvas(self) elif ext=='svg': from backend_svg import FigureCanvasSVG fc = self.switch_backends(FigureCanvasSVG) fc.print_figure(filename, dpi, facecolor, edgecolor, orientation, **kwargs) self.figure.set_canvas(self) else: raise ValueError("Figure format not available (extension %s)" % ext) # restore original figure settings self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): """ Wrap everything up into a window for the pylab interface """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) title = "Figure %d" % num _macosx.FigureManager.__init__(self, canvas, title) if matplotlib.rcParams['toolbar']=='classic': self.toolbar = NavigationToolbarMac(canvas) elif matplotlib.rcParams['toolbar']=='toolbar2': self.toolbar = NavigationToolbar2Mac(canvas) else: self.toolbar = None if self.toolbar is not None: self.toolbar.update() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) # This is ugly, but this is what tkagg and gtk are doing. # It is needed to get ginput() working. self.canvas.figure.show = lambda *args: self.show() def show(self): self.canvas.draw() def close(self): Gcf.destroy(self.num) class NavigationToolbarMac(_macosx.NavigationToolbar): def __init__(self, canvas): self.canvas = canvas basedir = os.path.join(matplotlib.rcParams['datapath'], "images") images = {} for imagename in ("stock_left", "stock_right", "stock_up", "stock_down", "stock_zoom-in", "stock_zoom-out", "stock_save_as"): filename = os.path.join(basedir, imagename+".ppm") images[imagename] = self._read_ppm_image(filename) _macosx.NavigationToolbar.__init__(self, images) self.message = None def _read_ppm_image(self, filename): data = "" imagefile = open(filename) for line in imagefile: if "#" in line: i = line.index("#") line = line[:i] + "\n" data += line imagefile.close() magic, width, height, maxcolor, imagedata = data.split(None, 4) width, height = int(width), int(height) assert magic=="P6" assert len(imagedata)==width*height*3 # 3 colors in RGB return (width, height, imagedata) def panx(self, direction): axes = self.canvas.figure.axes selected = self.get_active() for i in selected: axes[i].xaxis.pan(direction) self.canvas.invalidate() def pany(self, direction): axes = self.canvas.figure.axes selected = self.get_active() for i in selected: axes[i].yaxis.pan(direction) self.canvas.invalidate() def zoomx(self, direction): axes = self.canvas.figure.axes selected = self.get_active() for i in selected: axes[i].xaxis.zoom(direction) self.canvas.invalidate() def zoomy(self, direction): axes = self.canvas.figure.axes selected = self.get_active() for i in selected: axes[i].yaxis.zoom(direction) self.canvas.invalidate() def save_figure(self): filename = _macosx.choose_save_file('Save the figure') if filename is None: # Cancel return self.canvas.print_figure(filename) class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): def __init__(self, canvas): NavigationToolbar2.__init__(self, canvas) def _init_toolbar(self): basedir = os.path.join(matplotlib.rcParams['datapath'], "images") _macosx.NavigationToolbar2.__init__(self, basedir) def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.set_rubberband(x0, y0, x1, y1) def release(self, event): self.canvas.remove_rubberband() def set_cursor(self, cursor): _macosx.set_cursor(cursor) def save_figure(self): filename = _macosx.choose_save_file('Save the figure') if filename is None: # Cancel return self.canvas.print_figure(filename) def prepare_configure_subplots(self): toolfig = Figure(figsize=(6,3)) canvas = FigureCanvasMac(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) return canvas def set_message(self, message): _macosx.NavigationToolbar2.set_message(self, message.encode('utf-8')) ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## FigureManager = FigureManagerMac
15,397
Python
.py
360
33.963889
93
0.614381
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,302
backend_wx.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_wx.py
from __future__ import division """ backend_wx.py A wxPython backend for matplotlib, based (very heavily) on backend_template.py and backend_gtk.py Author: Jeremy O'Donoghue (jeremy@o-donoghue.com) Derived from original copyright work by John Hunter (jdhunter@ace.bsd.uchicago.edu) Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4 License: This work is licensed under a PSF compatible license. A copy should be included with this source code. """ """ KNOWN BUGS - - Mousewheel (on Windows) only works after menu button has been pressed at least once - Mousewheel on Linux (wxGTK linked against GTK 1.2) does not work at all - Vertical text renders horizontally if you use a non TrueType font on Windows. This is a known wxPython issue. Work-around is to ensure that you use a TrueType font. - Pcolor demo puts chart slightly outside bounding box (approx 1-2 pixels to the bottom left) - Outputting to bitmap more than 300dpi results in some text being incorrectly scaled. Seems to be a wxPython bug on Windows or font point sizes > 60, as font size is correctly calculated. - Performance poorer than for previous direct rendering version - TIFF output not supported on wxGTK. This is a wxGTK issue - Text is not anti-aliased on wxGTK. This is probably a platform configuration issue. - If a second call is made to show(), no figure is generated (#866965) Not implemented: - Printing Fixed this release: - Bug #866967: Interactive operation issues fixed [JDH] - Bug #866969: Dynamic update does not function with backend_wx [JOD] Examples which work on this release: --------------------------------------------------------------- | Windows 2000 | Linux | | wxPython 2.3.3 | wxPython 2.4.2.4 | --------------------------------------------------------------| - alignment_test.py | TBE | OK | - arctest.py | TBE | (3) | - axes_demo.py | OK | OK | - axes_props.py | OK | OK | - bar_stacked.py | TBE | OK | - barchart_demo.py | OK | OK | - color_demo.py | OK | OK | - csd_demo.py | OK | OK | - dynamic_demo.py | N/A | N/A | - dynamic_demo_wx.py | TBE | OK | - embedding_in_gtk.py | N/A | N/A | - embedding_in_wx.py | OK | OK | - errorbar_demo.py | OK | OK | - figtext.py | OK | OK | - histogram_demo.py | OK | OK | - interactive.py | N/A (2) | N/A (2) | - interactive2.py | N/A (2) | N/A (2) | - legend_demo.py | OK | OK | - legend_demo2.py | OK | OK | - line_styles.py | OK | OK | - log_demo.py | OK | OK | - logo.py | OK | OK | - mpl_with_glade.py | N/A (2) | N/A (2) | - mri_demo.py | OK | OK | - mri_demo_with_eeg.py | OK | OK | - multiple_figs_demo.py | OK | OK | - pcolor_demo.py | OK | OK | - psd_demo.py | OK | OK | - scatter_demo.py | OK | OK | - scatter_demo2.py | OK | OK | - simple_plot.py | OK | OK | - stock_demo.py | OK | OK | - subplot_demo.py | OK | OK | - system_monitor.py | N/A (2) | N/A (2) | - text_handles.py | OK | OK | - text_themes.py | OK | OK | - vline_demo.py | OK | OK | --------------------------------------------------------------- (2) - Script uses GTK-specific features - cannot not run, but wxPython equivalent should be written. (3) - Clipping seems to be broken. """ cvs_id = '$Id: backend_wx.py 6484 2008-12-03 18:38:03Z jdh2358 $' import sys, os, os.path, math, StringIO, weakref, warnings import numpy as npy # Debugging settings here... # Debug level set here. If the debug level is less than 5, information # messages (progressively more info for lower value) are printed. In addition, # traceback is performed, and pdb activated, for all uncaught exceptions in # this case _DEBUG = 5 if _DEBUG < 5: import traceback, pdb _DEBUG_lvls = {1 : 'Low ', 2 : 'Med ', 3 : 'High', 4 : 'Error' } try: import wx backend_version = wx.VERSION_STRING except: raise ImportError("Matplotlib backend_wx requires wxPython be installed") #!!! this is the call that is causing the exception swallowing !!! #wx.InitAllImageHandlers() def DEBUG_MSG(string, lvl=3, o=None): if lvl >= _DEBUG: cls = o.__class__ # Jeremy, often times the commented line won't print but the # one below does. I think WX is redefining stderr, damned # beast #print >>sys.stderr, "%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls) print "%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls) def debug_on_error(type, value, tb): """Code due to Thomas Heller - published in Python Cookbook (O'Reilley)""" traceback.print_exc(type, value, tb) print pdb.pm() # jdh uncomment class fake_stderr: """Wx does strange things with stderr, as it makes the assumption that there is probably no console. This redirects stderr to the console, since we know that there is one!""" def write(self, msg): print "Stderr: %s\n\r" % msg #if _DEBUG < 5: # sys.excepthook = debug_on_error # WxLogger =wx.LogStderr() # sys.stderr = fake_stderr # Event binding code changed after version 2.5 if wx.VERSION_STRING >= '2.5': def bind(actor,event,action,**kw): actor.Bind(event,action,**kw) else: def bind(actor,event,action,id=None): if id is not None: event(actor, id, action) else: event(actor,action) import matplotlib from matplotlib import verbose from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureCanvasBase, FigureManagerBase, NavigationToolbar2, \ cursors from matplotlib._pylab_helpers import Gcf from matplotlib.artist import Artist from matplotlib.cbook import exception_to_str, is_string_like, is_writable_file_like from matplotlib.figure import Figure from matplotlib.path import Path from matplotlib.text import _process_text_args, Text from matplotlib.transforms import Affine2D from matplotlib.widgets import SubplotTool from matplotlib import rcParams # the True dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 75 # Delay time for idle checks IDLE_DELAY = 5 def error_msg_wx(msg, parent=None): """ Signal an error condition -- in a GUI, popup a error dialog """ dialog =wx.MessageDialog(parent = parent, message = msg, caption = 'Matplotlib backend_wx error', style=wx.OK | wx.CENTRE) dialog.ShowModal() dialog.Destroy() return None def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg class RendererWx(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles. It acts as the 'renderer' instance used by many classes in the hierarchy. """ #In wxPython, drawing is performed on a wxDC instance, which will #generally be mapped to the client aread of the window displaying #the plot. Under wxPython, the wxDC instance has a wx.Pen which #describes the colour and weight of any lines drawn, and a wxBrush #which describes the fill colour of any closed polygon. fontweights = { 100 : wx.LIGHT, 200 : wx.LIGHT, 300 : wx.LIGHT, 400 : wx.NORMAL, 500 : wx.NORMAL, 600 : wx.NORMAL, 700 : wx.BOLD, 800 : wx.BOLD, 900 : wx.BOLD, 'ultralight' : wx.LIGHT, 'light' : wx.LIGHT, 'normal' : wx.NORMAL, 'medium' : wx.NORMAL, 'semibold' : wx.NORMAL, 'bold' : wx.BOLD, 'heavy' : wx.BOLD, 'ultrabold' : wx.BOLD, 'black' : wx.BOLD } fontangles = { 'italic' : wx.ITALIC, 'normal' : wx.NORMAL, 'oblique' : wx.SLANT } # wxPython allows for portable font styles, choosing them appropriately # for the target platform. Map some standard font names to the portable # styles # QUESTION: Is it be wise to agree standard fontnames across all backends? fontnames = { 'Sans' : wx.SWISS, 'Roman' : wx.ROMAN, 'Script' : wx.SCRIPT, 'Decorative' : wx.DECORATIVE, 'Modern' : wx.MODERN, 'Courier' : wx.MODERN, 'courier' : wx.MODERN } def __init__(self, bitmap, dpi): """ Initialise a wxWindows renderer instance. """ DEBUG_MSG("__init__()", 1, self) if wx.VERSION_STRING < "2.8": raise RuntimeError("matplotlib no longer supports wxPython < 2.8 for the Wx backend.\nYou may, however, use the WxAgg backend.") self.width = bitmap.GetWidth() self.height = bitmap.GetHeight() self.bitmap = bitmap self.fontd = {} self.dpi = dpi self.gc = None def flipy(self): return True def offset_text_height(self): return True def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop """ #return 1, 1 if ismath: s = self.strip_math(s) if self.gc is None: gc = self.new_gc() else: gc = self.gc gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) gfx_ctx.SetFont(font, wx.BLACK) w, h, descent, leading = gfx_ctx.GetFullTextExtent(s) return w, h, descent def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width, self.height def handle_clip_rectangle(self, gc): new_bounds = gc.get_clip_rectangle() if new_bounds is not None: new_bounds = new_bounds.bounds gfx_ctx = gc.gfx_ctx if gfx_ctx._lastcliprect != new_bounds: gfx_ctx._lastcliprect = new_bounds if new_bounds is None: gfx_ctx.ResetClip() else: gfx_ctx.Clip(new_bounds[0], self.height - new_bounds[1] - new_bounds[3], new_bounds[2], new_bounds[3]) #@staticmethod def convert_path(gfx_ctx, tpath): wxpath = gfx_ctx.CreatePath() for points, code in tpath.iter_segments(): if code == Path.MOVETO: wxpath.MoveToPoint(*points) elif code == Path.LINETO: wxpath.AddLineToPoint(*points) elif code == Path.CURVE3: wxpath.AddQuadCurveToPoint(*points) elif code == Path.CURVE4: wxpath.AddCurveToPoint(*points) elif code == Path.CLOSEPOLY: wxpath.CloseSubpath() return wxpath convert_path = staticmethod(convert_path) def draw_path(self, gc, path, transform, rgbFace=None): gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx transform = transform + Affine2D().scale(1.0, -1.0).translate(0.0, self.height) tpath = transform.transform_path(path) wxpath = self.convert_path(gfx_ctx, tpath) if rgbFace is not None: gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace))) gfx_ctx.DrawPath(wxpath) else: gfx_ctx.StrokePath(wxpath) gc.unselect() def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): if bbox != None: l,b,w,h = bbox.bounds else: l=0 b=0, w=self.width h=self.height rows, cols, image_str = im.as_rgba_str() image_array = npy.fromstring(image_str, npy.uint8) image_array.shape = rows, cols, 4 bitmap = wx.BitmapFromBufferRGBA(cols,rows,image_array) gc = self.get_gc() gc.select() gc.gfx_ctx.DrawBitmap(bitmap,int(l),int(b),int(w),int(h)) gc.unselect() def draw_text(self, gc, x, y, s, prop, angle, ismath): """ Render the matplotlib.text.Text instance None) """ if ismath: s = self.strip_math(s) DEBUG_MSG("draw_text()", 1, self) gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) color = gc.get_wxcolour(gc.get_rgb()) gfx_ctx.SetFont(font, color) w, h, d = self.get_text_width_height_descent(s, prop, ismath) x = int(x) y = int(y-h) if angle == 0.0: gfx_ctx.DrawText(s, x, y) else: rads = angle / 180.0 * math.pi xo = h * math.sin(rads) yo = h * math.cos(rads) gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads) gc.unselect() def new_gc(self): """ Return an instance of a GraphicsContextWx, and sets the current gc copy """ DEBUG_MSG('new_gc()', 2, self) self.gc = GraphicsContextWx(self.bitmap, self) self.gc.select() self.gc.unselect() return self.gc def get_gc(self): """ Fetch the locally cached gc. """ # This is a dirty hack to allow anything with access to a renderer to # access the current graphics context assert self.gc != None, "gc must be defined" return self.gc def get_wx_font(self, s, prop): """ Return a wx font. Cache instances in a font dictionary for efficiency """ DEBUG_MSG("get_wx_font()", 1, self) key = hash(prop) fontprop = prop fontname = fontprop.get_name() font = self.fontd.get(key) if font is not None: return font # Allow use of platform independent and dependent font names wxFontname = self.fontnames.get(fontname, wx.ROMAN) wxFacename = '' # Empty => wxPython chooses based on wx_fontname # Font colour is determined by the active wx.Pen # TODO: It may be wise to cache font information size = self.points_to_pixels(fontprop.get_size_in_points()) font =wx.Font(int(size+0.5), # Size wxFontname, # 'Generic' name self.fontangles[fontprop.get_style()], # Angle self.fontweights[fontprop.get_weight()], # Weight False, # Underline wxFacename) # Platform font name # cache the font and gc and return it self.fontd[key] = font return font def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ return points*(PIXELS_PER_INCH/72.0*self.dpi/72.0) class GraphicsContextWx(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... This class stores a reference to a wxMemoryDC, and a wxGraphicsContext that draws to it. Creating a wxGraphicsContext seems to be fairly heavy, so these objects are cached based on the bitmap object that is passed in. The base GraphicsContext stores colors as a RGB tuple on the unit interval, eg, (0.5, 0.0, 1.0). wxPython uses an int interval, but since wxPython colour management is rather simple, I have not chosen to implement a separate colour manager class. """ _capd = { 'butt': wx.CAP_BUTT, 'projecting': wx.CAP_PROJECTING, 'round': wx.CAP_ROUND } _joind = { 'bevel': wx.JOIN_BEVEL, 'miter': wx.JOIN_MITER, 'round': wx.JOIN_ROUND } _dashd_wx = { 'solid': wx.SOLID, 'dashed': wx.SHORT_DASH, 'dashdot': wx.DOT_DASH, 'dotted': wx.DOT } _cache = weakref.WeakKeyDictionary() def __init__(self, bitmap, renderer): GraphicsContextBase.__init__(self) #assert self.Ok(), "wxMemoryDC not OK to use" DEBUG_MSG("__init__()", 1, self) dc, gfx_ctx = self._cache.get(bitmap, (None, None)) if dc is None: dc = wx.MemoryDC() dc.SelectObject(bitmap) gfx_ctx = wx.GraphicsContext.Create(dc) gfx_ctx._lastcliprect = None self._cache[bitmap] = dc, gfx_ctx self.bitmap = bitmap self.dc = dc self.gfx_ctx = gfx_ctx self._pen = wx.Pen('BLACK', 1, wx.SOLID) gfx_ctx.SetPen(self._pen) self._style = wx.SOLID self.renderer = renderer def select(self): """ Select the current bitmap into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True def unselect(self): """ Select a Null bitmasp into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False def set_foreground(self, fg, isRGB=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate concept of pen and # brush - the brush fills any outline trace left by the pen. # Here we set both to the same colour - if a figure is not to be # filled, the renderer will set the brush to be transparent # Same goes for text foreground... DEBUG_MSG("set_foreground()", 1, self) self.select() GraphicsContextBase.set_foreground(self, fg, isRGB) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_graylevel(self, frac): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ DEBUG_MSG("set_graylevel()", 1, self) self.select() GraphicsContextBase.set_graylevel(self, frac) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linewidth(self, w): """ Set the line width. """ DEBUG_MSG("set_linewidth()", 1, self) self.select() if w>0 and w<1: w = 1 GraphicsContextBase.set_linewidth(self, w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw==0: lw = 1 self._pen.SetWidth(lw) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ DEBUG_MSG("set_capstyle()", 1, self) self.select() GraphicsContextBase.set_capstyle(self, cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ DEBUG_MSG("set_joinstyle()", 1, self) self.select() GraphicsContextBase.set_joinstyle(self, js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linestyle(self, ls): """ Set the line style to be one of """ DEBUG_MSG("set_linestyle()", 1, self) self.select() GraphicsContextBase.set_linestyle(self, ls) try: self._style = GraphicsContextWx._dashd_wx[ls] except KeyError: self._style = wx.LONG_DASH# Style not used elsewhere... # On MS Windows platform, only line width of 1 allowed for dash lines if wx.Platform == '__WXMSW__': self.set_linewidth(1) self._pen.SetStyle(self._style) self.gfx_ctx.SetPen(self._pen) self.unselect() def get_wxcolour(self, color): """return a wx.Colour from RGB format""" DEBUG_MSG("get_wx_color()", 1, self) if len(color) == 3: r, g, b = color r *= 255 g *= 255 b *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b)) else: r, g, b, a = color r *= 255 g *= 255 b *= 255 a *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a)) class FigureCanvasWx(FigureCanvasBase, wx.Panel): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wx.Sizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ keyvald = { wx.WXK_CONTROL : 'control', wx.WXK_SHIFT : 'shift', wx.WXK_ALT : 'alt', wx.WXK_LEFT : 'left', wx.WXK_UP : 'up', wx.WXK_RIGHT : 'right', wx.WXK_DOWN : 'down', wx.WXK_ESCAPE : 'escape', wx.WXK_F1 : 'f1', wx.WXK_F2 : 'f2', wx.WXK_F3 : 'f3', wx.WXK_F4 : 'f4', wx.WXK_F5 : 'f5', wx.WXK_F6 : 'f6', wx.WXK_F7 : 'f7', wx.WXK_F8 : 'f8', wx.WXK_F9 : 'f9', wx.WXK_F10 : 'f10', wx.WXK_F11 : 'f11', wx.WXK_F12 : 'f12', wx.WXK_SCROLL : 'scroll_lock', wx.WXK_PAUSE : 'break', wx.WXK_BACK : 'backspace', wx.WXK_RETURN : 'enter', wx.WXK_INSERT : 'insert', wx.WXK_DELETE : 'delete', wx.WXK_HOME : 'home', wx.WXK_END : 'end', wx.WXK_PRIOR : 'pageup', wx.WXK_NEXT : 'pagedown', wx.WXK_PAGEUP : 'pageup', wx.WXK_PAGEDOWN : 'pagedown', wx.WXK_NUMPAD0 : '0', wx.WXK_NUMPAD1 : '1', wx.WXK_NUMPAD2 : '2', wx.WXK_NUMPAD3 : '3', wx.WXK_NUMPAD4 : '4', wx.WXK_NUMPAD5 : '5', wx.WXK_NUMPAD6 : '6', wx.WXK_NUMPAD7 : '7', wx.WXK_NUMPAD8 : '8', wx.WXK_NUMPAD9 : '9', wx.WXK_NUMPAD_ADD : '+', wx.WXK_NUMPAD_SUBTRACT : '-', wx.WXK_NUMPAD_MULTIPLY : '*', wx.WXK_NUMPAD_DIVIDE : '/', wx.WXK_NUMPAD_DECIMAL : 'dec', wx.WXK_NUMPAD_ENTER : 'enter', wx.WXK_NUMPAD_UP : 'up', wx.WXK_NUMPAD_RIGHT : 'right', wx.WXK_NUMPAD_DOWN : 'down', wx.WXK_NUMPAD_LEFT : 'left', wx.WXK_NUMPAD_PRIOR : 'pageup', wx.WXK_NUMPAD_NEXT : 'pagedown', wx.WXK_NUMPAD_PAGEUP : 'pageup', wx.WXK_NUMPAD_PAGEDOWN : 'pagedown', wx.WXK_NUMPAD_HOME : 'home', wx.WXK_NUMPAD_END : 'end', wx.WXK_NUMPAD_INSERT : 'insert', wx.WXK_NUMPAD_DELETE : 'delete', } def __init__(self, parent, id, figure): """ Initialise a FigureWx instance. - Initialise the FigureCanvasBase and wxPanel parents. - Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event) """ FigureCanvasBase.__init__(self, figure) # Set preferred window size hint - helps the sizer (if one is # connected) l,b,w,h = figure.bbox.bounds w = int(math.ceil(w)) h = int(math.ceil(h)) wx.Panel.__init__(self, parent, id, size=wx.Size(w, h)) def do_nothing(*args, **kwargs): warnings.warn('could not find a setinitialsize function for backend_wx; please report your wxpython version=%s to the matplotlib developers list'%backend_version) pass # try to find the set size func across wx versions try: getattr(self, 'SetInitialSize') except AttributeError: self.SetInitialSize = getattr(self, 'SetBestFittingSize', do_nothing) if not hasattr(self,'IsShownOnScreen'): self.IsShownOnScreen = getattr(self, 'IsVisible', lambda *args: True) # Create the drawing bitmap self.bitmap =wx.EmptyBitmap(w, h) DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w,h), 2, self) # TODO: Add support for 'point' inspection and plot navigation. self._isDrawn = False bind(self, wx.EVT_SIZE, self._onSize) bind(self, wx.EVT_PAINT, self._onPaint) bind(self, wx.EVT_ERASE_BACKGROUND, self._onEraseBackground) bind(self, wx.EVT_KEY_DOWN, self._onKeyDown) bind(self, wx.EVT_KEY_UP, self._onKeyUp) bind(self, wx.EVT_RIGHT_DOWN, self._onRightButtonDown) bind(self, wx.EVT_RIGHT_DCLICK, self._onRightButtonDown) bind(self, wx.EVT_RIGHT_UP, self._onRightButtonUp) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel) bind(self, wx.EVT_LEFT_DOWN, self._onLeftButtonDown) bind(self, wx.EVT_LEFT_DCLICK, self._onLeftButtonDown) bind(self, wx.EVT_LEFT_UP, self._onLeftButtonUp) bind(self, wx.EVT_MOTION, self._onMotion) bind(self, wx.EVT_LEAVE_WINDOW, self._onLeave) bind(self, wx.EVT_ENTER_WINDOW, self._onEnter) bind(self, wx.EVT_IDLE, self._onIdle) self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.macros = {} # dict from wx id to seq of macros self.Printer_Init() def Destroy(self, *args, **kwargs): wx.Panel.Destroy(self, *args, **kwargs) def Copy_to_Clipboard(self, event=None): "copy bitmap of canvas to system clipboard" bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) wx.TheClipboard.Open() wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Close() def Printer_Init(self): """initialize printer settings using wx methods""" self.printerData = wx.PrintData() self.printerData.SetPaperId(wx.PAPER_LETTER) self.printerData.SetPrintMode(wx.PRINT_MODE_PRINTER) self.printerPageData= wx.PageSetupDialogData() self.printerPageData.SetMarginBottomRight((25,25)) self.printerPageData.SetMarginTopLeft((25,25)) self.printerPageData.SetPrintData(self.printerData) self.printer_width = 5.5 self.printer_margin= 0.5 def Printer_Setup(self, event=None): """set up figure for printing. The standard wx Printer Setup Dialog seems to die easily. Therefore, this setup simply asks for image width and margin for printing. """ dmsg = """Width of output figure in inches. The current aspect ration will be kept.""" dlg = wx.Dialog(self, -1, 'Page Setup for Printing' , (-1,-1)) df = dlg.GetFont() df.SetWeight(wx.NORMAL) df.SetPointSize(11) dlg.SetFont(df) x_wid = wx.TextCtrl(dlg,-1,value="%.2f" % self.printer_width, size=(70,-1)) x_mrg = wx.TextCtrl(dlg,-1,value="%.2f" % self.printer_margin,size=(70,-1)) sizerAll = wx.BoxSizer(wx.VERTICAL) sizerAll.Add(wx.StaticText(dlg,-1,dmsg), 0, wx.ALL | wx.EXPAND, 5) sizer = wx.FlexGridSizer(0,3) sizerAll.Add(sizer, 0, wx.ALL | wx.EXPAND, 5) sizer.Add(wx.StaticText(dlg,-1,'Figure Width'), 1, wx.ALIGN_LEFT|wx.ALL, 2) sizer.Add(x_wid, 1, wx.ALIGN_LEFT|wx.ALL, 2) sizer.Add(wx.StaticText(dlg,-1,'in'), 1, wx.ALIGN_LEFT|wx.ALL, 2) sizer.Add(wx.StaticText(dlg,-1,'Margin'), 1, wx.ALIGN_LEFT|wx.ALL, 2) sizer.Add(x_mrg, 1, wx.ALIGN_LEFT|wx.ALL, 2) sizer.Add(wx.StaticText(dlg,-1,'in'), 1, wx.ALIGN_LEFT|wx.ALL, 2) btn = wx.Button(dlg,wx.ID_OK, " OK ") btn.SetDefault() sizer.Add(btn, 1, wx.ALIGN_LEFT, 5) btn = wx.Button(dlg,wx.ID_CANCEL, " CANCEL ") sizer.Add(btn, 1, wx.ALIGN_LEFT, 5) dlg.SetSizer(sizerAll) dlg.SetAutoLayout(True) sizerAll.Fit(dlg) if dlg.ShowModal() == wx.ID_OK: try: self.printer_width = float(x_wid.GetValue()) self.printer_margin = float(x_mrg.GetValue()) except: pass if ((self.printer_width + self.printer_margin) > 7.5): self.printerData.SetOrientation(wx.LANDSCAPE) else: self.printerData.SetOrientation(wx.PORTRAIT) dlg.Destroy() return def Printer_Setup2(self, event=None): """set up figure for printing. Using the standard wx Printer Setup Dialog. """ if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() data.SetMarginTopLeft( (15, 15) ) data.SetMarginBottomRight( (15, 15) ) dlg = wx.PageSetupDialog(self, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() tl = data.GetMarginTopLeft() br = data.GetMarginBottomRight() self.printerData = wx.PrintData(data.GetPrintData()) dlg.Destroy() def Printer_Preview(self, event=None): """ generate Print Preview with wx Print mechanism""" po1 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin) po2 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin) self.preview = wx.PrintPreview(po1,po2,self.printerData) if not self.preview.Ok(): print "error with preview" self.preview.SetZoom(50) frameInst= self while not isinstance(frameInst, wx.Frame): frameInst= frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, "Preview") frame.Initialize() frame.SetPosition(self.GetPosition()) frame.SetSize((850,650)) frame.Centre(wx.BOTH) frame.Show(True) self.gui_repaint() def Printer_Print(self, event=None): """ Print figure using wx Print mechanism""" pdd = wx.PrintDialogData() # SetPrintData for 2.4 combatibility pdd.SetPrintData(self.printerData) pdd.SetToPage(1) printer = wx.Printer(pdd) printout = PrintoutWx(self, width=int(self.printer_width), margin=int(self.printer_margin)) print_ok = printer.Print(self, printout, True) if wx.VERSION_STRING >= '2.5': if not print_ok and not printer.GetLastError() == wx.PRINTER_CANCELLED: wx.MessageBox("""There was a problem printing. Perhaps your current printer is not set correctly?""", "Printing", wx.OK) else: if not print_ok: wx.MessageBox("""There was a problem printing. Perhaps your current printer is not set correctly?""", "Printing", wx.OK) printout.Destroy() self.gui_repaint() def draw_idle(self): """ Delay rendering until the GUI is idle. """ DEBUG_MSG("draw_idle()", 1, self) self._isDrawn = False # Force redraw # Create a timer for handling draw_idle requests # If there are events pending when the timer is # complete, reset the timer and continue. The # alternative approach, binding to wx.EVT_IDLE, # doesn't behave as nicely. if hasattr(self,'_idletimer'): self._idletimer.Restart(IDLE_DELAY) else: self._idletimer = wx.FutureCall(IDLE_DELAY,self._onDrawIdle) # FutureCall is a backwards-compatible alias; # CallLater became available in 2.7.1.1. def _onDrawIdle(self, *args, **kwargs): if wx.GetApp().Pending(): self._idletimer.Restart(IDLE_DELAY, *args, **kwargs) else: del self._idletimer # GUI event or explicit draw call may already # have caused the draw to take place if not self._isDrawn: self.draw(*args, **kwargs) def draw(self, drawDC=None): """ Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. """ DEBUG_MSG("draw()", 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.renderer) self._isDrawn = True self.gui_repaint(drawDC=drawDC) def flush_events(self): wx.Yield() def start_event_loop(self, timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. Call signature:: start_event_loop(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. Raises RuntimeError if event loop is already running. """ if hasattr(self, '_event_loop'): raise RuntimeError("Event loop already running") id = wx.NewId() timer = wx.Timer(self, id=id) if timeout > 0: timer.Start(timeout*1000, oneShot=True) bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id) # Event loop handler for start/stop event loop self._event_loop = wx.EventLoop() self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) """ if hasattr(self,'_event_loop'): if self._event_loop.IsRunning(): self._event_loop.Exit() del self._event_loop def _get_imagesave_wildcards(self): 'return the wildcard string for the filesave dialog' default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() wildcards = [] extensions = [] filter_index = 0 for i, (name, exts) in enumerate(sorted_filetypes): ext_list = ';'.join(['*.%s' % ext for ext in exts]) extensions.append(exts[0]) wildcard = '%s (%s)|%s' % (name, ext_list, ext_list) if default_filetype in exts: filter_index = i wildcards.append(wildcard) wildcards = '|'.join(wildcards) return wildcards, extensions, filter_index def gui_repaint(self, drawDC=None): """ Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image. """ DEBUG_MSG("gui_repaint()", 1, self) if self.IsShownOnScreen(): if drawDC is None: drawDC=wx.ClientDC(self) drawDC.BeginDrawing() drawDC.DrawBitmap(self.bitmap, 0, 0) drawDC.EndDrawing() #wx.GetApp().Yield() else: pass filetypes = FigureCanvasBase.filetypes.copy() filetypes['bmp'] = 'Windows bitmap' filetypes['jpeg'] = 'JPEG' filetypes['jpg'] = 'JPEG' filetypes['pcx'] = 'PCX' filetypes['png'] = 'Portable Network Graphics' filetypes['tif'] = 'Tagged Image Format File' filetypes['tiff'] = 'Tagged Image Format File' filetypes['xpm'] = 'X pixmap' def print_figure(self, filename, *args, **kwargs): # Use pure Agg renderer to draw FigureCanvasBase.print_figure(self, filename, *args, **kwargs) # Restore the current view; this is needed because the # artist contains methods rely on particular attributes # of the rendered figure for determining things like # bounding boxes. if self._isDrawn: self.draw() def print_bmp(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_BMP, *args, **kwargs) def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_JPEG, *args, **kwargs) print_jpg = print_jpeg def print_pcx(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PCX, *args, **kwargs) def print_png(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PNG, *args, **kwargs) def print_tiff(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_TIF, *args, **kwargs) print_tif = print_tiff def print_xpm(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_XPM, *args, **kwargs) def _print_image(self, filename, filetype, *args, **kwargs): origBitmap = self.bitmap l,b,width,height = self.figure.bbox.bounds width = int(math.ceil(width)) height = int(math.ceil(height)) self.bitmap = wx.EmptyBitmap(width, height) renderer = RendererWx(self.bitmap, self.figure.dpi) gc = renderer.new_gc() self.figure.draw(renderer) # Now that we have rendered into the bitmap, save it # to the appropriate file type and clean up if is_string_like(filename): if not self.bitmap.SaveFile(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError('Could not save figure to %s\n' % (filename)) elif is_writable_file_like(filename): if not self.bitmap.ConvertToImage().SaveStream(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError('Could not save figure to %s\n' % (filename)) # Restore everything to normal self.bitmap = origBitmap # Note: draw is required here since bits of state about the # last renderer are strewn about the artist draw methods. Do # not remove the draw without first verifying that these have # been cleaned up. The artist contains() methods will fail # otherwise. if self._isDrawn: self.draw() self.Refresh() def get_default_filetype(self): return 'png' def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ DEBUG_MSG("_onPaint()", 1, self) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) evt.Skip() def _onEraseBackground(self, evt): """ Called when window is redrawn; since we are blitting the entire image, we can leave this blank to suppress flicker. """ pass def _onSize(self, evt): """ Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. """ DEBUG_MSG("_onSize()", 2, self) # Create a new, correctly sized bitmap self._width, self._height = self.GetClientSize() self.bitmap =wx.EmptyBitmap(self._width, self._height) self._isDrawn = False if self._width <= 1 or self._height <= 1: return # Empty figure dpival = self.figure.dpi winch = self._width/dpival hinch = self._height/dpival self.figure.set_size_inches(winch, hinch) # Rendering will happen on the associated paint event # so no need to do anything here except to make sure # the whole background is repainted. self.Refresh(eraseBackground=False) def _get_key(self, evt): keyval = evt.m_keyCode if keyval in self.keyvald: key = self.keyvald[keyval] elif keyval <256: key = chr(keyval) else: key = None # why is wx upcasing this? if key is not None: key = key.lower() return key def _onIdle(self, evt): 'a GUI idle event' evt.Skip() FigureCanvasBase.idle_event(self, guiEvent=evt) def _onKeyDown(self, evt): """Capture key press.""" key = self._get_key(evt) evt.Skip() FigureCanvasBase.key_press_event(self, key, guiEvent=evt) def _onKeyUp(self, evt): """Release key.""" key = self._get_key(evt) #print 'release key', key evt.Skip() FigureCanvasBase.key_release_event(self, key, guiEvent=evt) def _onRightButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 3, guiEvent=evt) def _onRightButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 3, guiEvent=evt) def _onLeftButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt) def _onLeftButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() #print 'release button', 1 evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt) def _onMouseWheel(self, evt): """Translate mouse wheel events into matplotlib events""" # Determine mouse location x = evt.GetX() y = self.figure.bbox.height - evt.GetY() # Convert delta/rotation/rate into a floating point step size delta = evt.GetWheelDelta() rotation = evt.GetWheelRotation() rate = evt.GetLinesPerAction() #print "delta,rotation,rate",delta,rotation,rate step = rate*float(rotation)/delta # Done handling event evt.Skip() # Mac is giving two events for every wheel event # Need to skip every second one if wx.Platform == '__WXMAC__': if not hasattr(self,'_skipwheelevent'): self._skipwheelevent = True elif self._skipwheelevent: self._skipwheelevent = False return # Return without processing event else: self._skipwheelevent = True # Convert to mpl event FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt) def _onMotion(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt) def _onLeave(self, evt): """Mouse has left the window.""" evt.Skip() FigureCanvasBase.leave_notify_event(self, guiEvent = evt) def _onEnter(self, evt): """Mouse has entered the window.""" FigureCanvasBase.enter_notify_event(self, guiEvent = evt) ######################################################################## # # The following functions and classes are for pylab compatibility # mode (matplotlib.pylab) and implement figure managers, etc... # ######################################################################## def _create_wx_app(): """ Creates a wx.PySimpleApp instance if a wx.App has not been created. """ wxapp = wx.GetApp() if wxapp is None: wxapp = wx.PySimpleApp() wxapp.SetExitOnFrameDelete(True) # retain a reference to the app object so it does not get garbage # collected and cause segmentation faults _create_wx_app.theWxApp = wxapp def draw_if_interactive(): """ This should be overriden in a windowing environment if drawing should be done in interactive python mode """ DEBUG_MSG("draw_if_interactive()", 1, None) if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw() def show(): """ Current implementation assumes that matplotlib is executed in a PyCrust shell. It appears to be possible to execute wxPython applications from within a PyCrust without having to ensure that wxPython has been created in a secondary thread (e.g. SciPy gui_thread). Unfortunately, gui_thread seems to introduce a number of further dependencies on SciPy modules, which I do not wish to introduce into the backend at this point. If there is a need I will look into this in a later release. """ DEBUG_MSG("show()", 3, None) for figwin in Gcf.get_all_fig_managers(): figwin.frame.Show() if show._needmain and not matplotlib.is_interactive(): # start the wxPython gui event if there is not already one running wxapp = wx.GetApp() if wxapp is not None: # wxPython 2.4 has no wx.App.IsMainLoopRunning() method imlr = getattr(wxapp, 'IsMainLoopRunning', lambda: False) if not imlr(): wxapp.MainLoop() show._needmain = False show._needmain = True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # in order to expose the Figure constructor to the pylab # interface we need to create the figure here DEBUG_MSG("new_figure_manager()", 3, None) _create_wx_app() FigureClass = kwargs.pop('FigureClass', Figure) fig = FigureClass(*args, **kwargs) frame = FigureFrameWx(num, fig) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() return figmgr class FigureFrameWx(wx.Frame): def __init__(self, num, fig): # On non-Windows platform, explicitly set the position - fix # positioning bug on some Linux platforms if wx.Platform == '__WXMSW__': pos = wx.DefaultPosition else: pos =wx.Point(20,20) l,b,w,h = fig.bbox.bounds wx.Frame.__init__(self, parent=None, id=-1, pos=pos, title="Figure %d" % num) # Frame will be sized later by the Fit method DEBUG_MSG("__init__()", 1, self) self.num = num statbar = StatusBarWx(self) self.SetStatusBar(statbar) self.canvas = self.get_canvas(fig) self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height)) self.sizer =wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version self.toolbar = self._get_toolbar(statbar) if self.toolbar is not None: self.toolbar.Realize() if wx.Platform == '__WXMAC__': # Mac platform (OSX 10.3, MacPython) does not seem to cope with # having a toolbar in a sizer. This work-around gets the buttons # back, but at the expense of having the toolbar at the top self.SetToolBar(self.toolbar) else: # On Windows platform, default window size is incorrect, so set # toolbar width to figure width. tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. # As noted above, doesn't work for Mac. self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.figmgr = FigureManagerWx(self.canvas, num, self) bind(self, wx.EVT_CLOSE, self._onClose) def _get_toolbar(self, statbar): if matplotlib.rcParams['toolbar']=='classic': toolbar = NavigationToolbarWx(self.canvas, True) elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2Wx(self.canvas) toolbar.set_status_bar(statbar) else: toolbar = None return toolbar def get_canvas(self, fig): return FigureCanvasWx(self, -1, fig) def get_figure_manager(self): DEBUG_MSG("get_figure_manager()", 1, self) return self.figmgr def _onClose(self, evt): DEBUG_MSG("onClose()", 1, self) self.canvas.stop_event_loop() Gcf.destroy(self.num) #self.Destroy() def GetToolBar(self): """Override wxFrame::GetToolBar as we don't have managed toolbar""" return self.toolbar def Destroy(self, *args, **kwargs): wx.Frame.Destroy(self, *args, **kwargs) if self.toolbar is not None: self.toolbar.Destroy() wxapp = wx.GetApp() if wxapp: wxapp.Yield() return True class FigureManagerWx(FigureManagerBase): """ This class contains the FigureCanvas and GUI frame It is instantiated by GcfWx whenever a new figure is created. GcfWx is responsible for managing multiple instances of FigureManagerWx. NB: FigureManagerBase is found in _pylab_helpers public attrs canvas - a FigureCanvasWx(wx.Panel) instance window - a wxFrame instance - http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin_wxframe.html#wxframe """ def __init__(self, canvas, num, frame): DEBUG_MSG("__init__()", 1, self) FigureManagerBase.__init__(self, canvas, num) self.frame = frame self.window = frame self.tb = frame.GetToolBar() self.toolbar = self.tb # consistent with other backends def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.tb != None: self.tb.update() self.canvas.figure.add_axobserver(notify_axes_change) def showfig(*args): frame.Show() # attach a show method to the figure self.canvas.figure.show = showfig def destroy(self, *args): DEBUG_MSG("destroy()", 1, self) self.frame.Destroy() #if self.tb is not None: self.tb.Destroy() import wx #wx.GetApp().ProcessIdle() wx.WakeUpIdle() def set_window_title(self, title): self.window.SetTitle(title) def resize(self, width, height): 'Set the canvas size in pixels' self.canvas.SetInitialSize(wx.Size(width, height)) self.window.GetSizer().Fit(self.window) # Identifiers for toolbar controls - images_wx contains bitmaps for the images # used in the controls. wxWindows does not provide any stock images, so I've # 'stolen' those from GTK2, and transformed them into the appropriate format. #import images_wx _NTB_AXISMENU =wx.NewId() _NTB_AXISMENU_BUTTON =wx.NewId() _NTB_X_PAN_LEFT =wx.NewId() _NTB_X_PAN_RIGHT =wx.NewId() _NTB_X_ZOOMIN =wx.NewId() _NTB_X_ZOOMOUT =wx.NewId() _NTB_Y_PAN_UP =wx.NewId() _NTB_Y_PAN_DOWN =wx.NewId() _NTB_Y_ZOOMIN =wx.NewId() _NTB_Y_ZOOMOUT =wx.NewId() #_NTB_SUBPLOT =wx.NewId() _NTB_SAVE =wx.NewId() _NTB_CLOSE =wx.NewId() def _load_bitmap(filename): """ Load a bitmap file from the backends/images subdirectory in which the matplotlib library is installed. The filename parameter should not contain any path information as this is determined automatically. Returns a wx.Bitmap object """ basedir = os.path.join(rcParams['datapath'],'images') bmpFilename = os.path.normpath(os.path.join(basedir, filename)) if not os.path.exists(bmpFilename): raise IOError('Could not find bitmap file "%s"; dying'%bmpFilename) bmp = wx.Bitmap(bmpFilename) return bmp class MenuButtonWx(wx.Button): """ wxPython does not permit a menu to be incorporated directly into a toolbar. This class simulates the effect by associating a pop-up menu with a button in the toolbar, and managing this as though it were a menu. """ def __init__(self, parent): wx.Button.__init__(self, parent, _NTB_AXISMENU_BUTTON, "Axes: ", style=wx.BU_EXACTFIT) self._toolbar = parent self._menu =wx.Menu() self._axisId = [] # First two menu items never change... self._allId =wx.NewId() self._invertId =wx.NewId() self._menu.Append(self._allId, "All", "Select all axes", False) self._menu.Append(self._invertId, "Invert", "Invert axes selected", False) self._menu.AppendSeparator() bind(self, wx.EVT_BUTTON, self._onMenuButton, id=_NTB_AXISMENU_BUTTON) bind(self, wx.EVT_MENU, self._handleSelectAllAxes, id=self._allId) bind(self, wx.EVT_MENU, self._handleInvertAxesSelected, id=self._invertId) def Destroy(self): self._menu.Destroy() self.Destroy() def _onMenuButton(self, evt): """Handle menu button pressed.""" x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y+h-4) # When menu returned, indicate selection in button evt.Skip() def _handleSelectAllAxes(self, evt): """Called when the 'select all axes' menu item is selected.""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _handleInvertAxesSelected(self, evt): """Called when the invert all menu item is selected""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): self._menu.Check(self._axisId[i], False) else: self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _onMenuItemSelected(self, evt): """Called whenever one of the specific axis menu items is selected""" current = self._menu.IsChecked(evt.GetId()) if current: new = False else: new = True self._menu.Check(evt.GetId(), new) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def updateAxes(self, maxAxis): """Ensures that there are entries for max_axis axes in the menu (selected by default).""" if maxAxis > len(self._axisId): for i in range(len(self._axisId) + 1, maxAxis + 1, 1): menuId =wx.NewId() self._axisId.append(menuId) self._menu.Append(menuId, "Axis %d" % i, "Select axis %d" % i, True) self._menu.Check(menuId, True) bind(self, wx.EVT_MENU, self._onMenuItemSelected, id=menuId) self._toolbar.set_active(range(len(self._axisId))) def getActiveAxes(self): """Return a list of the selected axes.""" active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active def updateButtonText(self, lst): """Update the list of selected axes in the menu button""" axis_txt = '' for e in lst: axis_txt += '%d,' % (e+1) # remove trailing ',' and add to button string self.SetLabel("Axes: %s" % axis_txt[:-1]) cursord = { cursors.MOVE : wx.CURSOR_HAND, cursors.HAND : wx.CURSOR_HAND, cursors.POINTER : wx.CURSOR_ARROW, cursors.SELECT_REGION : wx.CURSOR_CROSS, } class SubplotToolWX(wx.Frame): def __init__(self, targetfig): wx.Frame.__init__(self, None, -1, "Configure subplots") toolfig = Figure((6,3)) canvas = FigureCanvasWx(self, -1, toolfig) # Create a figure manager to manage things figmgr = FigureManager(canvas, 1, self) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(canvas, 1, wx.LEFT|wx.TOP|wx.GROW) self.SetSizer(sizer) self.Fit() tool = SubplotTool(targetfig, toolfig) class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): def __init__(self, canvas): wx.ToolBar.__init__(self, canvas.GetParent(), -1) NavigationToolbar2.__init__(self, canvas) self.canvas = canvas self._idle = True self.statbar = None def get_canvas(self, frame, fig): return FigureCanvasWx(frame, -1, fig) def _init_toolbar(self): DEBUG_MSG("_init_toolbar", 1, self) self._parent = self.canvas.GetParent() _NTB2_HOME =wx.NewId() self._NTB2_BACK =wx.NewId() self._NTB2_FORWARD =wx.NewId() self._NTB2_PAN =wx.NewId() self._NTB2_ZOOM =wx.NewId() _NTB2_SAVE = wx.NewId() _NTB2_SUBPLOT =wx.NewId() self.SetToolBitmapSize(wx.Size(24,24)) self.AddSimpleTool(_NTB2_HOME, _load_bitmap('home.png'), 'Home', 'Reset original view') self.AddSimpleTool(self._NTB2_BACK, _load_bitmap('back.png'), 'Back', 'Back navigation view') self.AddSimpleTool(self._NTB2_FORWARD, _load_bitmap('forward.png'), 'Forward', 'Forward navigation view') # todo: get new bitmap self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'), shortHelp='Pan', longHelp='Pan with left, zoom with right') self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'), shortHelp='Zoom', longHelp='Zoom to rectangle') self.AddSeparator() self.AddSimpleTool(_NTB2_SUBPLOT, _load_bitmap('subplots.png'), 'Configure subplots', 'Configure subplot parameters') self.AddSimpleTool(_NTB2_SAVE, _load_bitmap('filesave.png'), 'Save', 'Save plot contents to file') bind(self, wx.EVT_TOOL, self.home, id=_NTB2_HOME) bind(self, wx.EVT_TOOL, self.forward, id=self._NTB2_FORWARD) bind(self, wx.EVT_TOOL, self.back, id=self._NTB2_BACK) bind(self, wx.EVT_TOOL, self.zoom, id=self._NTB2_ZOOM) bind(self, wx.EVT_TOOL, self.pan, id=self._NTB2_PAN) bind(self, wx.EVT_TOOL, self.configure_subplot, id=_NTB2_SUBPLOT) bind(self, wx.EVT_TOOL, self.save, id=_NTB2_SAVE) self.Realize() def zoom(self, *args): self.ToggleTool(self._NTB2_PAN, False) NavigationToolbar2.zoom(self, *args) def pan(self, *args): self.ToggleTool(self._NTB2_ZOOM, False) NavigationToolbar2.pan(self, *args) def configure_subplot(self, evt): frame = wx.Frame(None, -1, "Configure subplots") toolfig = Figure((6,3)) canvas = self.get_canvas(frame, toolfig) # Create a figure manager to manage things figmgr = FigureManager(canvas, 1, frame) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(canvas, 1, wx.LEFT|wx.TOP|wx.GROW) frame.SetSizer(sizer) frame.Fit() tool = SubplotTool(self.canvas.figure, toolfig) frame.Show() def save(self, evt): # Fetch the required filename and file type. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() default_file = "image." + self.canvas.get_default_filetype() dlg = wx.FileDialog(self._parent, "Save to file", "", default_file, filetypes, wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() == wx.ID_OK: dirname = dlg.GetDirectory() filename = dlg.GetFilename() DEBUG_MSG('Save file dir:%s name:%s' % (dirname, filename), 3, self) format = exts[dlg.GetFilterIndex()] basename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format!=ext: #looks like they forgot to set the image type drop #down, going with the extension. warnings.warn('extension %s did not match the selected image type %s; going with %s'%(ext, format, ext), stacklevel=0) format = ext try: self.canvas.print_figure( os.path.join(dirname, filename), format=format) except Exception, e: error_msg_wx(str(e)) def set_cursor(self, cursor): cursor =wx.StockCursor(cursord[cursor]) self.canvas.SetCursor( cursor ) def release(self, event): try: del self.lastrect except AttributeError: pass def dynamic_update(self): d = self._idle self._idle = False if d: self.canvas.draw() self._idle = True def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' canvas = self.canvas dc =wx.ClientDC(canvas) # Set logical function to XOR for rubberbanding dc.SetLogicalFunction(wx.XOR) # Set dc brush and pen # Here I set brush and pen to white and grey respectively # You can set it to your own choices # The brush setting is not really needed since we # dont do any filling of the dc. It is set just for # the sake of completion. wbrush =wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT) wpen =wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) dc.SetBrush(wbrush) dc.SetPen(wpen) dc.ResetBoundingBox() dc.BeginDrawing() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 if y1<y0: y0, y1 = y1, y0 if x1<y0: x0, x1 = x1, x0 w = x1 - x0 h = y1 - y0 rect = int(x0), int(y0), int(w), int(h) try: lastrect = self.lastrect except AttributeError: pass else: dc.DrawRectangle(*lastrect) #erase last self.lastrect = rect dc.DrawRectangle(*rect) dc.EndDrawing() def set_status_bar(self, statbar): self.statbar = statbar def set_message(self, s): if self.statbar is not None: self.statbar.set_function(s) def set_history_buttons(self): can_backward = (self._views._pos > 0) can_forward = (self._views._pos < len(self._views._elements) - 1) self.EnableTool(self._NTB2_BACK, can_backward) self.EnableTool(self._NTB2_FORWARD, can_forward) class NavigationToolbarWx(wx.ToolBar): def __init__(self, canvas, can_kill=False): """ figure is the Figure instance that the toolboar controls win, if not None, is the wxWindow the Figure is embedded in """ wx.ToolBar.__init__(self, canvas.GetParent(), -1) DEBUG_MSG("__init__()", 1, self) self.canvas = canvas self._lastControl = None self._mouseOnButton = None self._parent = canvas.GetParent() self._NTB_BUTTON_HANDLER = { _NTB_X_PAN_LEFT : self.panx, _NTB_X_PAN_RIGHT : self.panx, _NTB_X_ZOOMIN : self.zoomx, _NTB_X_ZOOMOUT : self.zoomy, _NTB_Y_PAN_UP : self.pany, _NTB_Y_PAN_DOWN : self.pany, _NTB_Y_ZOOMIN : self.zoomy, _NTB_Y_ZOOMOUT : self.zoomy } self._create_menu() self._create_controls(can_kill) self.Realize() def _create_menu(self): """ Creates the 'menu' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control """ DEBUG_MSG("_create_menu()", 1, self) self._menu = MenuButtonWx(self) self.AddControl(self._menu) self.AddSeparator() def _create_controls(self, can_kill): """ Creates the button controls, and links them to event handlers """ DEBUG_MSG("_create_controls()", 1, self) # Need the following line as Windows toolbars default to 15x16 self.SetToolBitmapSize(wx.Size(16,16)) self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'), 'Left', 'Scroll left') self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'), 'Right', 'Scroll right') self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase X axis magnification') self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease X axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_Y_PAN_UP,_load_bitmap('stock_up.xpm'), 'Up', 'Scroll up') self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'), 'Down', 'Scroll down') self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase Y axis magnification') self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease Y axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'), 'Save', 'Save plot contents as images') self.AddSeparator() bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT) bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT) bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN) bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP) bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN) bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN) bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE) bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId()) if can_kill: bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel) def set_active(self, ind): """ ind is a list of index numbers for the axes which are to be made active """ DEBUG_MSG("set_active()", 1, self) self._ind = ind if ind != None: self._active = [ self._axes[i] for i in self._ind ] else: self._active = [] # Now update button text wit active axes self._menu.updateButtonText(ind) def get_last_control(self): """Returns the identity of the last toolbar button pressed.""" return self._lastControl def panx(self, direction): DEBUG_MSG("panx()", 1, self) for a in self._active: a.xaxis.pan(direction) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def pany(self, direction): DEBUG_MSG("pany()", 1, self) for a in self._active: a.yaxis.pan(direction) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def zoomx(self, in_out): DEBUG_MSG("zoomx()", 1, self) for a in self._active: a.xaxis.zoom(in_out) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def zoomy(self, in_out): DEBUG_MSG("zoomy()", 1, self) for a in self._active: a.yaxis.zoom(in_out) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def update(self): """ Update the toolbar menu - called when (e.g.) a new subplot or axes are added """ DEBUG_MSG("update()", 1, self) self._axes = self.canvas.figure.get_axes() self._menu.updateAxes(len(self._axes)) def _do_nothing(self, d): """A NULL event handler - does nothing whatsoever""" pass # Local event handlers - mainly supply parameters to pan/scroll functions def _onEnterTool(self, evt): toolId = evt.GetSelection() try: self.button_fn = self._NTB_BUTTON_HANDLER[toolId] except KeyError: self.button_fn = self._do_nothing evt.Skip() def _onLeftScroll(self, evt): self.panx(-1) evt.Skip() def _onRightScroll(self, evt): self.panx(1) evt.Skip() def _onXZoomIn(self, evt): self.zoomx(1) evt.Skip() def _onXZoomOut(self, evt): self.zoomx(-1) evt.Skip() def _onUpScroll(self, evt): self.pany(1) evt.Skip() def _onDownScroll(self, evt): self.pany(-1) evt.Skip() def _onYZoomIn(self, evt): self.zoomy(1) evt.Skip() def _onYZoomOut(self, evt): self.zoomy(-1) evt.Skip() def _onMouseEnterButton(self, button): self._mouseOnButton = button def _onMouseLeaveButton(self, button): if self._mouseOnButton == button: self._mouseOnButton = None def _onMouseWheel(self, evt): if evt.GetWheelRotation() > 0: direction = 1 else: direction = -1 self.button_fn(direction) _onSave = NavigationToolbar2Wx.save def _onClose(self, evt): self.GetParent().Destroy() class StatusBarWx(wx.StatusBar): """ A status bar is added to _FigureFrame to allow measurements and the previously selected scroll function to be displayed as a user convenience. """ def __init__(self, parent): wx.StatusBar.__init__(self, parent, -1) self.SetFieldsCount(2) self.SetStatusText("None", 1) #self.SetStatusText("Measurement: None", 2) #self.Reposition() def set_function(self, string): self.SetStatusText("%s" % string, 1) #def set_measurement(self, string): # self.SetStatusText("Measurement: %s" % string, 2) #< Additions for printing support: Matt Newville class PrintoutWx(wx.Printout): """Simple wrapper around wx Printout class -- all the real work here is scaling the matplotlib canvas bitmap to the current printer's definition. """ def __init__(self, canvas, width=5.5,margin=0.5, title='matplotlib'): wx.Printout.__init__(self,title=title) self.canvas = canvas # width, in inches of output figure (approximate) self.width = width self.margin = margin def HasPage(self, page): #current only supports 1 page print return page == 1 def GetPageInfo(self): return (1, 1, 1, 1) def OnPrintPage(self, page): self.canvas.draw() dc = self.GetDC() (ppw,pph) = self.GetPPIPrinter() # printer's pixels per in (pgw,pgh) = self.GetPageSizePixels() # page size in pixels (dcw,dch) = dc.GetSize() (grw,grh) = self.canvas.GetSizeTuple() # save current figure dpi resolution and bg color, # so that we can temporarily set them to the dpi of # the printer, and the bg color to white bgcolor = self.canvas.figure.get_facecolor() fig_dpi = self.canvas.figure.dpi # draw the bitmap, scaled appropriately vscale = float(ppw) / fig_dpi # set figure resolution,bg color for printer self.canvas.figure.dpi = ppw self.canvas.figure.set_facecolor('#FFFFFF') renderer = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi) self.canvas.figure.draw(renderer) self.canvas.bitmap.SetWidth( int(self.canvas.bitmap.GetWidth() * vscale)) self.canvas.bitmap.SetHeight( int(self.canvas.bitmap.GetHeight()* vscale)) self.canvas.draw() # page may need additional scaling on preview page_scale = 1.0 if self.IsPreview(): page_scale = float(dcw)/pgw # get margin in pixels = (margin in in) * (pixels/in) top_margin = int(self.margin * pph * page_scale) left_margin = int(self.margin * ppw * page_scale) # set scale so that width of output is self.width inches # (assuming grw is size of graph in inches....) user_scale = (self.width * fig_dpi * page_scale)/float(grw) dc.SetDeviceOrigin(left_margin,top_margin) dc.SetUserScale(user_scale,user_scale) # this cute little number avoid API inconsistencies in wx try: dc.DrawBitmap(self.canvas.bitmap, 0, 0) except: try: dc.DrawBitmap(self.canvas.bitmap, (0, 0)) except: pass # restore original figure resolution self.canvas.figure.set_facecolor(bgcolor) self.canvas.figure.dpi = fig_dpi self.canvas.draw() return True #> ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## Toolbar = NavigationToolbarWx FigureManager = FigureManagerWx
77,038
Python
.py
1,793
34.006135
174
0.585817
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,303
backend_cocoaagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_cocoaagg.py
from __future__ import division """ backend_cocoaagg.py A native Cocoa backend via PyObjC in OSX. Author: Charles Moad (cmoad@users.sourceforge.net) Notes: - Requires PyObjC (currently testing v1.3.7) - The Tk backend works nicely on OSX. This code primarily serves as an example of embedding a matplotlib rendering context into a cocoa app using a NSImageView. """ import os, sys try: import objc except: print >>sys.stderr, 'The CococaAgg backend required PyObjC to be installed!' print >>sys.stderr, ' (currently testing v1.3.7)' sys.exit() from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper import matplotlib from matplotlib.figure import Figure from matplotlib.backend_bases import FigureManagerBase from backend_agg import FigureCanvasAgg from matplotlib._pylab_helpers import Gcf mplBundle = NSBundle.bundleWithPath_(os.path.dirname(__file__)) def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass( *args, **kwargs ) canvas = FigureCanvasCocoaAgg(thisFig) return FigureManagerCocoaAgg(canvas, num) def show(): for manager in Gcf.get_all_fig_managers(): manager.show() def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show() class FigureCanvasCocoaAgg(FigureCanvasAgg): def draw(self): FigureCanvasAgg.draw(self) def blit(self, bbox): pass def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ NibClassBuilder.extractClasses('Matplotlib.nib', mplBundle) class MatplotlibController(NibClassBuilder.AutoBaseClass): # available outlets: # NSWindow plotWindow # PlotView plotView def awakeFromNib(self): # Get a reference to the active canvas NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView self.plotWindow.setAcceptsMouseMovedEvents_(True) self.plotWindow.makeKeyAndOrderFront_(self) self.plotWindow.setDelegate_(self)#.plotView) self.plotView.setImageFrameStyle_(NSImageFrameGroove) self.plotView.image_ = NSImage.alloc().initWithSize_((0,0)) self.plotView.setImage_(self.plotView.image_) # Make imageview first responder for key events self.plotWindow.makeFirstResponder_(self.plotView) # Force the first update self.plotView.windowDidResize_(self) def windowDidResize_(self, sender): self.plotView.windowDidResize_(sender) def windowShouldClose_(self, sender): #NSApplication.sharedApplication().stop_(self) self.app.stop_(self) return objc.YES def saveFigure_(self, sender): p = NSSavePanel.savePanel() if(p.runModal() == NSFileHandlingPanelOKButton): self.canvas.print_figure(p.filename()) def printFigure_(self, sender): op = NSPrintOperation.printOperationWithView_(self.plotView) op.runOperation() class PlotWindow(NibClassBuilder.AutoBaseClass): pass class PlotView(NibClassBuilder.AutoBaseClass): def updatePlot(self): w,h = self.canvas.get_width_height() # Remove all previous images for i in xrange(self.image_.representations().count()): self.image_.removeRepresentation_(self.image_.representations().objectAtIndex_(i)) self.image_.setSize_((w,h)) brep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( (self.canvas.buffer_rgba(0,0),'','','',''), # Image data w, # width h, # height 8, # bits per pixel 4, # components per pixel True, # has alpha? False, # is planar? NSCalibratedRGBColorSpace, # color space w*4, # row bytes 32) # bits per pixel self.image_.addRepresentation_(brep) self.setNeedsDisplay_(True) def windowDidResize_(self, sender): w,h = self.bounds().size dpi = self.canvas.figure.dpi self.canvas.figure.set_size_inches(w / dpi, h / dpi) self.canvas.draw() self.updatePlot() def mouseDown_(self, event): loc = self.convertPoint_fromView_(event.locationInWindow(), None) type = event.type() if (type == NSLeftMouseDown): button = 1 else: print >>sys.stderr, 'Unknown mouse event type:', type button = -1 self.canvas.button_press_event(loc.x, loc.y, button) self.updatePlot() def mouseDragged_(self, event): loc = self.convertPoint_fromView_(event.locationInWindow(), None) self.canvas.motion_notify_event(loc.x, loc.y) self.updatePlot() def mouseUp_(self, event): loc = self.convertPoint_fromView_(event.locationInWindow(), None) type = event.type() if (type == NSLeftMouseUp): button = 1 else: print >>sys.stderr, 'Unknown mouse event type:', type button = -1 self.canvas.button_release_event(loc.x, loc.y, button) self.updatePlot() def keyDown_(self, event): self.canvas.key_press_event(event.characters()) self.updatePlot() def keyUp_(self, event): self.canvas.key_release_event(event.characters()) self.updatePlot() class MPLBootstrap(NSObject): # Loads the nib containing the PlotWindow and PlotView def startWithBundle_(self, bundle): #NSApplicationLoad() if not bundle.loadNibFile_externalNameTable_withZone_('Matplotlib.nib', {}, None): print >>sys.stderr, 'Unable to load Matplotlib Cocoa UI!' sys.exit() class FigureManagerCocoaAgg(FigureManagerBase): def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) try: WMEnable('Matplotlib') except: # MULTIPLE FIGURES ARE BUGGY! pass # If there are multiple figures we only need to enable once #self.bootstrap = MPLBootstrap.alloc().init().performSelectorOnMainThread_withObject_waitUntilDone_( # 'startWithBundle:', # mplBundle, # False) def show(self): # Load a new PlotWindow self.bootstrap = MPLBootstrap.alloc().init().performSelectorOnMainThread_withObject_waitUntilDone_( 'startWithBundle:', mplBundle, False) NSApplication.sharedApplication().run() FigureManager = FigureManagerCocoaAgg #### Everything below taken from PyObjC examples #### This is a hack to allow python scripts to access #### the window manager without running pythonw. def S(*args): return ''.join(args) OSErr = objc._C_SHT OUTPSN = 'o^{ProcessSerialNumber=LL}' INPSN = 'n^{ProcessSerialNumber=LL}' FUNCTIONS=[ # These two are public API ( u'GetCurrentProcess', S(OSErr, OUTPSN) ), ( u'SetFrontProcess', S(OSErr, INPSN) ), # This is undocumented SPI ( u'CPSSetProcessName', S(OSErr, INPSN, objc._C_CHARPTR) ), ( u'CPSEnableForegroundOperation', S(OSErr, INPSN) ), ] def WMEnable(name='Python'): if isinstance(name, unicode): name = name.encode('utf8') mainBundle = NSBundle.mainBundle() bPath = os.path.split(os.path.split(os.path.split(sys.executable)[0])[0])[0] if mainBundle.bundlePath() == bPath: return True bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework')) if bndl is None: print >>sys.stderr, 'ApplicationServices missing' return False d = {} objc.loadBundleFunctions(bndl, d, FUNCTIONS) for (fn, sig) in FUNCTIONS: if fn not in d: print >>sys.stderr, 'Missing', fn return False err, psn = d['GetCurrentProcess']() if err: print >>sys.stderr, 'GetCurrentProcess', (err, psn) return False err = d['CPSSetProcessName'](psn, name) if err: print >>sys.stderr, 'CPSSetProcessName', (err, psn) return False err = d['CPSEnableForegroundOperation'](psn) if err: #print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn) return False err = d['SetFrontProcess'](psn) if err: print >>sys.stderr, 'SetFrontProcess', (err, psn) return False return True
8,970
Python
.py
222
33.238739
176
0.669962
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,304
backend_tkagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py
# Todd Miller jmiller@stsci.edu from __future__ import division import os, sys, math import Tkinter as Tk, FileDialog import tkagg # Paint image to Tk photo blitter extension from backend_agg import FigureCanvasAgg import os.path import matplotlib from matplotlib.cbook import is_string_like from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors from matplotlib.figure import Figure from matplotlib._pylab_helpers import Gcf import matplotlib.windowing as windowing from matplotlib.widgets import SubplotTool import matplotlib.cbook as cbook rcParams = matplotlib.rcParams verbose = matplotlib.verbose backend_version = Tk.TkVersion # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 75 cursord = { cursors.MOVE: "fleur", cursors.HAND: "hand2", cursors.POINTER: "arrow", cursors.SELECT_REGION: "tcross", } def round(x): return int(math.floor(x+0.5)) def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg def error_msg_tkpaint(msg, parent=None): import tkMessageBox tkMessageBox.showerror("matplotlib", msg) def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show() def show(): """ Show all the figures and enter the gtk mainloop This should be the last line of your script. This function sets interactive mode to True, as detailed on http://matplotlib.sf.net/interactive.html """ for manager in Gcf.get_all_fig_managers(): manager.show() import matplotlib matplotlib.interactive(True) if rcParams['tk.pythoninspect']: os.environ['PYTHONINSPECT'] = '1' if show._needmain: Tk.mainloop() show._needmain = False show._needmain = True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ _focus = windowing.FocusManager() FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) window = Tk.Tk() canvas = FigureCanvasTkAgg(figure, master=window) figManager = FigureManagerTkAgg(canvas, num, window) if matplotlib.is_interactive(): figManager.show() return figManager class FigureCanvasTkAgg(FigureCanvasAgg): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', } def __init__(self, figure, master=None, resize_callback=None): FigureCanvasAgg.__init__(self, figure) self._idle = True t1,t2,w,h = self.figure.bbox.bounds w, h = int(w), int(h) self._tkcanvas = Tk.Canvas( master=master, width=w, height=h, borderwidth=4) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=w, height=h) self._tkcanvas.create_image(w/2, h/2, image=self._tkphoto) self._resize_callback = resize_callback self._tkcanvas.bind("<Configure>", self.resize) self._tkcanvas.bind("<Key>", self.key_press) self._tkcanvas.bind("<Motion>", self.motion_notify_event) self._tkcanvas.bind("<KeyRelease>", self.key_release) for name in "<Button-1>", "<Button-2>", "<Button-3>": self._tkcanvas.bind(name, self.button_press_event) for name in "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>": self._tkcanvas.bind(name, self.button_release_event) # Mouse wheel on Linux generates button 4/5 events for name in "<Button-4>", "<Button-5>": self._tkcanvas.bind(name, self.scroll_event) # Mouse wheel for windows goes to the window with the focus. # Since the canvas won't usually have the focus, bind the # event to the window containing the canvas instead. # See http://wiki.tcl.tk/3893 (mousewheel) for details root = self._tkcanvas.winfo_toplevel() root.bind("<MouseWheel>", self.scroll_event_windows) self._master = master self._tkcanvas.focus_set() # a dict from func-> cbook.Scheduler threads self.sourced = dict() # call the idle handler def on_idle(*ignore): self.idle_event() return True # disable until you figure out how to handle threads and interrupts #t = cbook.Idle(on_idle) #self._tkcanvas.after_idle(lambda *ignore: t.start()) def resize(self, event): width, height = event.width, event.height if self._resize_callback is not None: self._resize_callback(event) # compute desired figure size in inches dpival = self.figure.dpi winch = width/dpival hinch = height/dpival self.figure.set_size_inches(winch, hinch) self._tkcanvas.delete(self._tkphoto) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=width, height=height) self._tkcanvas.create_image(width/2,height/2,image=self._tkphoto) self.resize_event() self.show() def draw(self): FigureCanvasAgg.draw(self) tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) self._master.update_idletasks() def blit(self, bbox=None): tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2) self._master.update_idletasks() show = draw def draw_idle(self): 'update drawing area only if idle' d = self._idle self._idle = False def idle_draw(*args): self.draw() self._idle = True if d: self._tkcanvas.after_idle(idle_draw) def get_tk_widget(self): """returns the Tk widget used to implement FigureCanvasTkAgg. Although the initial implementation uses a Tk canvas, this routine is intended to hide that fact. """ return self._tkcanvas def motion_notify_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def button_press_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_press_event(self, x, y, num, guiEvent=event) def button_release_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) def scroll_event(self, event): x = event.x y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if num==4: step = -1 elif num==5: step = +1 else: step = 0 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def scroll_event_windows(self, event): """MouseWheel event processor""" # need to find the window that contains the mouse w = event.widget.winfo_containing(event.x_root, event.y_root) if w == self._tkcanvas: x = event.x_root - w.winfo_rootx() y = event.y_root - w.winfo_rooty() y = self.figure.bbox.height - y step = event.delta/120. FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def _get_key(self, event): val = event.keysym_num if val in self.keyvald: key = self.keyvald[val] elif val<256: key = chr(val) else: key = None return key def key_press(self, event): key = self._get_key(event) FigureCanvasBase.key_press_event(self, key, guiEvent=event) def key_release(self, event): key = self._get_key(event) FigureCanvasBase.key_release_event(self, key, guiEvent=event) def flush_events(self): self._master.update() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerTkAgg(FigureManagerBase): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The tk.Toolbar window : The tk.Window """ def __init__(self, canvas, num, window): FigureManagerBase.__init__(self, canvas, num) self.window = window self.window.withdraw() self.window.wm_title("Figure %d" % num) self.canvas = canvas self._num = num t1,t2,w,h = canvas.figure.bbox.bounds w, h = int(w), int(h) self.window.minsize(int(w*3/4),int(h*3/4)) if matplotlib.rcParams['toolbar']=='classic': self.toolbar = NavigationToolbar( canvas, self.window ) elif matplotlib.rcParams['toolbar']=='toolbar2': self.toolbar = NavigationToolbar2TkAgg( canvas, self.window ) else: self.toolbar = None if self.toolbar is not None: self.toolbar.update() self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self._shown = False def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) # attach a show method to the figure for pylab ease of use self.canvas.figure.show = lambda *args: self.show() def resize(self, event): width, height = event.width, event.height self.toolbar.configure(width=width) # , height=height) def show(self): """ this function doesn't segfault but causes the PyEval_RestoreThread: NULL state bug on win32 """ def destroy(*args): self.window = None Gcf.destroy(self._num) if not self._shown: self.canvas._tkcanvas.bind("<Destroy>", destroy) _focus = windowing.FocusManager() if not self._shown: self.window.deiconify() # anim.py requires this if sys.platform=='win32' : self.window.update() else: self.canvas.draw() self._shown = True def destroy(self, *args): if Gcf.get_num_fig_managers()==0 and not matplotlib.is_interactive(): if self.window is not None: self.window.quit() if self.window is not None: #self.toolbar.destroy() self.window.destroy() pass self.window = None def set_window_title(self, title): self.window.wm_title(title) class AxisMenu: def __init__(self, master, naxes): self._master = master self._naxes = naxes self._mbar = Tk.Frame(master=master, relief=Tk.RAISED, borderwidth=2) self._mbar.pack(side=Tk.LEFT) self._mbutton = Tk.Menubutton( master=self._mbar, text="Axes", underline=0) self._mbutton.pack(side=Tk.LEFT, padx="2m") self._mbutton.menu = Tk.Menu(self._mbutton) self._mbutton.menu.add_command( label="Select All", command=self.select_all) self._mbutton.menu.add_command( label="Invert All", command=self.invert_all) self._axis_var = [] self._checkbutton = [] for i in range(naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append(self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) self._mbutton.menu.invoke(self._mbutton.menu.index("Select All")) self._mbutton['menu'] = self._mbutton.menu self._mbar.tk_menuBar(self._mbutton) self.set_active() def adjust(self, naxes): if self._naxes < naxes: for i in range(self._naxes, naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append( self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) elif self._naxes > naxes: for i in range(self._naxes-1, naxes-1, -1): del self._axis_var[i] self._mbutton.menu.forget(self._checkbutton[i]) del self._checkbutton[i] self._naxes = naxes self.set_active() def get_indices(self): a = [i for i in range(len(self._axis_var)) if self._axis_var[i].get()] return a def set_active(self): self._master.set_active(self.get_indices()) def invert_all(self): for a in self._axis_var: a.set(not a.get()) self.set_active() def select_all(self): for a in self._axis_var: a.set(1) self.set_active() class NavigationToolbar(Tk.Frame): """ Public attriubutes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ def _Button(self, text, file, command): file = os.path.join(rcParams['datapath'], 'images', file) im = Tk.PhotoImage(master=self, file=file) b = Tk.Button( master=self, text=text, padx=2, pady=2, image=im, command=command) b._ntimage = im b.pack(side=Tk.LEFT) return b def __init__(self, canvas, window): self.canvas = canvas self.window = window xmin, xmax = canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=width, height=height, borderwidth=2) self.update() # Make axes menu self.bLeft = self._Button( text="Left", file="stock_left.ppm", command=lambda x=-1: self.panx(x)) self.bRight = self._Button( text="Right", file="stock_right.ppm", command=lambda x=1: self.panx(x)) self.bZoomInX = self._Button( text="ZoomInX",file="stock_zoom-in.ppm", command=lambda x=1: self.zoomx(x)) self.bZoomOutX = self._Button( text="ZoomOutX", file="stock_zoom-out.ppm", command=lambda x=-1: self.zoomx(x)) self.bUp = self._Button( text="Up", file="stock_up.ppm", command=lambda y=1: self.pany(y)) self.bDown = self._Button( text="Down", file="stock_down.ppm", command=lambda y=-1: self.pany(y)) self.bZoomInY = self._Button( text="ZoomInY", file="stock_zoom-in.ppm", command=lambda y=1: self.zoomy(y)) self.bZoomOutY = self._Button( text="ZoomOutY",file="stock_zoom-out.ppm", command=lambda y=-1: self.zoomy(y)) self.bSave = self._Button( text="Save", file="stock_save_as.ppm", command=self.save_figure) self.pack(side=Tk.BOTTOM, fill=Tk.X) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def panx(self, direction): for a in self._active: a.xaxis.pan(direction) self.canvas.draw() def pany(self, direction): for a in self._active: a.yaxis.pan(direction) self.canvas.draw() def zoomx(self, direction): for a in self._active: a.xaxis.zoom(direction) self.canvas.draw() def zoomy(self, direction): for a in self._active: a.yaxis.zoom(direction) self.canvas.draw() def save_figure(self): fs = FileDialog.SaveFileDialog(master=self.window, title='Save the figure') try: self.lastDir except AttributeError: self.lastDir = os.curdir fname = fs.go(dir_or_file=self.lastDir) # , pattern="*.png") if fname is None: # Cancel return self.lastDir = os.path.dirname(fname) try: self.canvas.print_figure(fname) except IOError, msg: err = '\n'.join(map(str, msg)) msg = 'Failed to save %s: Error msg was\n\n%s' % ( fname, err) error_msg_tkpaint(msg) def update(self): _focus = windowing.FocusManager() self._axes = self.canvas.figure.axes naxes = len(self._axes) if not hasattr(self, "omenu"): self.set_active(range(naxes)) self.omenu = AxisMenu(master=self, naxes=naxes) else: self.omenu.adjust(naxes) class NavigationToolbar2TkAgg(NavigationToolbar2, Tk.Frame): """ Public attriubutes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ def __init__(self, canvas, window): self.canvas = canvas self.window = window self._idle = True #Tk.Frame.__init__(self, master=self.canvas._tkcanvas) NavigationToolbar2.__init__(self, canvas) def destroy(self, *args): del self.message Tk.Frame.destroy(self, *args) def set_message(self, s): self.message.set(s) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y0 = height-y0 y1 = height-y1 try: self.lastrect except AttributeError: pass else: self.canvas._tkcanvas.delete(self.lastrect) self.lastrect = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1) #self.canvas.draw() def release(self, event): try: self.lastrect except AttributeError: pass else: self.canvas._tkcanvas.delete(self.lastrect) del self.lastrect def set_cursor(self, cursor): self.window.configure(cursor=cursord[cursor]) def _Button(self, text, file, command): file = os.path.join(rcParams['datapath'], 'images', file) im = Tk.PhotoImage(master=self, file=file) b = Tk.Button( master=self, text=text, padx=2, pady=2, image=im, command=command) b._ntimage = im b.pack(side=Tk.LEFT) return b def _init_toolbar(self): xmin, xmax = self.canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=width, height=height, borderwidth=2) self.update() # Make axes menu self.bHome = self._Button( text="Home", file="home.ppm", command=self.home) self.bBack = self._Button( text="Back", file="back.ppm", command = self.back) self.bForward = self._Button(text="Forward", file="forward.ppm", command = self.forward) self.bPan = self._Button( text="Pan", file="move.ppm", command = self.pan) self.bZoom = self._Button( text="Zoom", file="zoom_to_rect.ppm", command = self.zoom) self.bsubplot = self._Button( text="Configure Subplots", file="subplots.ppm", command = self.configure_subplots) self.bsave = self._Button( text="Save", file="filesave.ppm", command = self.save_figure) self.message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self.message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.BOTTOM, fill=Tk.X) def configure_subplots(self): toolfig = Figure(figsize=(6,3)) window = Tk.Tk() canvas = FigureCanvasTkAgg(toolfig, master=window) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def save_figure(self): from tkFileDialog import asksaveasfilename from tkMessageBox import showerror filetypes = self.canvas.get_supported_filetypes().copy() default_filetype = self.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes[default_filetype] del filetypes[default_filetype] sorted_filetypes = filetypes.items() sorted_filetypes.sort() sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) tk_filetypes = [ (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] fname = asksaveasfilename( master=self.window, title='Save the figure', filetypes = tk_filetypes, defaultextension = self.canvas.get_default_filetype() ) if fname == "" or fname == (): return else: try: # This method will handle the delegation to the correct type self.canvas.print_figure(fname) except Exception, e: showerror("Error saving file", str(e)) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def update(self): _focus = windowing.FocusManager() self._axes = self.canvas.figure.axes naxes = len(self._axes) #if not hasattr(self, "omenu"): # self.set_active(range(naxes)) # self.omenu = AxisMenu(master=self, naxes=naxes) #else: # self.omenu.adjust(naxes) NavigationToolbar2.update(self) def dynamic_update(self): 'update drawing area only if idle' # legacy method; new method is canvas.draw_idle self.canvas.draw_idle() FigureManager = FigureManagerTkAgg
24,593
Python
.py
608
30.379934
166
0.582998
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,305
tkagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/tkagg.py
import _tkagg import Tkinter as Tk def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() else: bbox_array = None try: tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array)) except Tk.TclError, v: try: try: _tkagg.tkinit(tk.interpaddr(), 1) except AttributeError: _tkagg.tkinit(id(tk), 0) tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array)) except (ImportError, AttributeError, Tk.TclError): raise def test(aggimage): import time r = Tk.Tk() c = Tk.Canvas(r, width=aggimage.width, height=aggimage.height) c.pack() p = Tk.PhotoImage(width=aggimage.width, height=aggimage.height) blit(p, aggimage) c.create_image(aggimage.width,aggimage.height,image=p) blit(p, aggimage) while 1: r.update_idletasks()
1,003
Python
.py
29
27.37931
91
0.635052
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,306
backend_agg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_agg.py
""" An agg http://antigrain.com/ backend Features that are implemented * capstyles and join styles * dashes * linewidth * lines, rectangles, ellipses * clipping to a rectangle * output to RGBA and PNG * alpha blending * DPI scaling properly - everything scales properly (dashes, linewidths, etc) * draw polygon * freetype2 w/ ft2font TODO: * allow save to file handle * integrate screen dpi w/ ppi and text """ from __future__ import division import numpy as npy from matplotlib import verbose, rcParams from matplotlib.backend_bases import RendererBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.cbook import is_string_like, maxdict from matplotlib.figure import Figure from matplotlib.font_manager import findfont from matplotlib.ft2font import FT2Font, LOAD_FORCE_AUTOHINT from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Bbox from _backend_agg import RendererAgg as _RendererAgg from matplotlib import _png backend_version = 'v2.2' class RendererAgg(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles """ debug=1 texd = maxdict(50) # a cache of tex image rasters _fontd = maxdict(50) def __init__(self, width, height, dpi): if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying') RendererBase.__init__(self) self.dpi = dpi self.width = width self.height = height if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying') self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False) if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done', 'debug-annoying') #self.draw_path = self._renderer.draw_path # see below self.draw_markers = self._renderer.draw_markers self.draw_path_collection = self._renderer.draw_path_collection self.draw_quad_mesh = self._renderer.draw_quad_mesh self.draw_image = self._renderer.draw_image self.copy_from_bbox = self._renderer.copy_from_bbox self.restore_region = self._renderer.restore_region self.tostring_rgba_minimized = self._renderer.tostring_rgba_minimized self.mathtext_parser = MathTextParser('Agg') self.bbox = Bbox.from_bounds(0, 0, self.width, self.height) if __debug__: verbose.report('RendererAgg.__init__ done', 'debug-annoying') def draw_path(self, gc, path, transform, rgbFace=None): nmax = rcParams['agg.path.chunksize'] # here at least for testing npts = path.vertices.shape[0] if nmax > 100 and npts > nmax and path.should_simplify and rgbFace is None: nch = npy.ceil(npts/float(nmax)) chsize = int(npy.ceil(npts/nch)) i0 = npy.arange(0, npts, chsize) i1 = npy.zeros_like(i0) i1[:-1] = i0[1:] - 1 i1[-1] = npts for ii0, ii1 in zip(i0, i1): v = path.vertices[ii0:ii1,:] c = path.codes if c is not None: c = c[ii0:ii1] c[0] = Path.MOVETO # move to end of last chunk p = Path(v, c) self._renderer.draw_path(gc, p, transform, rgbFace) else: self._renderer.draw_path(gc, path, transform, rgbFace) def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ if __debug__: verbose.report('RendererAgg.draw_mathtext', 'debug-annoying') ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) x = int(x) + ox y = int(y) - oy self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) def draw_text(self, gc, x, y, s, prop, angle, ismath): """ Render the text """ if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying') if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) font = self._get_agg_font(prop) if font is None: return None if len(s) == 1 and ord(s) > 127: font.load_char(ord(s), flags=LOAD_FORCE_AUTOHINT) else: # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). font.set_text(s, 0, flags=LOAD_FORCE_AUTOHINT) font.draw_glyphs_to_bitmap() #print x, y, int(x), int(y) self._renderer.draw_text_image(font.get_image(), int(x), int(y) + 1, angle, gc) def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend """ if ismath=='TeX': # todo: handle props size = prop.get_size_in_points() texmanager = self.get_texmanager() Z = texmanager.get_grey(s, size, self.dpi) m,n = Z.shape # TODO: descent of TeX text (I am imitating backend_ps here -JKS) return n, m, 0 if ismath: ox, oy, width, height, descent, fonts, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent font = self._get_agg_font(prop) font.set_text(s, 0.0, flags=LOAD_FORCE_AUTOHINT) # the width and height of unrotated string w, h = font.get_width_height() d = font.get_descent() w /= 64.0 # convert from subpixels h /= 64.0 d /= 64.0 return w, h, d def draw_tex(self, gc, x, y, s, prop, angle): # todo, handle props, angle, origins size = prop.get_size_in_points() texmanager = self.get_texmanager() key = s, size, self.dpi, angle, texmanager.get_font_config() im = self.texd.get(key) if im is None: Z = texmanager.get_grey(s, size, self.dpi) Z = npy.array(Z * 255.0, npy.uint8) self._renderer.draw_text_image(Z, x, y, angle, gc) def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width, self.height def _get_agg_font(self, prop): """ Get the font for text instance t, cacheing for efficiency """ if __debug__: verbose.report('RendererAgg._get_agg_font', 'debug-annoying') key = hash(prop) font = self._fontd.get(key) if font is None: fname = findfont(prop) font = self._fontd.get(fname) if font is None: font = FT2Font(str(fname)) self._fontd[fname] = font self._fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ if __debug__: verbose.report('RendererAgg.points_to_pixels', 'debug-annoying') return points*self.dpi/72.0 def tostring_rgb(self): if __debug__: verbose.report('RendererAgg.tostring_rgb', 'debug-annoying') return self._renderer.tostring_rgb() def tostring_argb(self): if __debug__: verbose.report('RendererAgg.tostring_argb', 'debug-annoying') return self._renderer.tostring_argb() def buffer_rgba(self,x,y): if __debug__: verbose.report('RendererAgg.buffer_rgba', 'debug-annoying') return self._renderer.buffer_rgba(x,y) def clear(self): self._renderer.clear() def option_image_nocomposite(self): # It is generally faster to composite each image directly to # the Figure, and there's no file size benefit to compositing # with the Agg backend return True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ if __debug__: verbose.report('backend_agg.new_figure_manager', 'debug-annoying') FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasAgg(thisFig) manager = FigureManagerBase(canvas, num) return manager class FigureCanvasAgg(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def copy_from_bbox(self, bbox): renderer = self.get_renderer() return renderer.copy_from_bbox(bbox) def restore_region(self, region): renderer = self.get_renderer() return renderer.restore_region(region) def draw(self): """ Draw the figure using the renderer """ if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') self.renderer = self.get_renderer() self.figure.draw(self.renderer) def get_renderer(self): l, b, w, h = self.figure.bbox.bounds key = w, h, self.figure.dpi try: self._lastKey, self.renderer except AttributeError: need_new_renderer = True else: need_new_renderer = (self._lastKey != key) if need_new_renderer: self.renderer = RendererAgg(w, h, self.figure.dpi) self._lastKey = key return self.renderer def tostring_rgb(self): if __debug__: verbose.report('FigureCanvasAgg.tostring_rgb', 'debug-annoying') return self.renderer.tostring_rgb() def tostring_argb(self): if __debug__: verbose.report('FigureCanvasAgg.tostring_argb', 'debug-annoying') return self.renderer.tostring_argb() def buffer_rgba(self,x,y): if __debug__: verbose.report('FigureCanvasAgg.buffer_rgba', 'debug-annoying') return self.renderer.buffer_rgba(x,y) def get_default_filetype(self): return 'png' def print_raw(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = file(filename_or_obj, 'wb') renderer._renderer.write_rgba(filename_or_obj) renderer.dpi = original_dpi print_rgba = print_raw def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = file(filename_or_obj, 'wb') _png.write_png(renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, filename_or_obj, self.figure.dpi) renderer.dpi = original_dpi
11,729
Python
.py
274
33.058394
114
0.60279
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,307
backend_qtagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_qtagg.py
""" Render to qt from agg """ from __future__ import division import os, sys import matplotlib from matplotlib import verbose from matplotlib.figure import Figure from backend_agg import FigureCanvasAgg from backend_qt import qt, FigureManagerQT, FigureCanvasQT,\ show, draw_if_interactive, backend_version, \ NavigationToolbar2QT DEBUG = False def new_figure_manager( num, *args, **kwargs ): """ Create a new figure manager instance """ if DEBUG: print 'backend_qtagg.new_figure_manager' FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass( *args, **kwargs ) canvas = FigureCanvasQTAgg( thisFig ) return FigureManagerQTAgg( canvas, num ) class NavigationToolbar2QTAgg(NavigationToolbar2QT): def _get_canvas(self, fig): return FigureCanvasQTAgg(fig) class FigureManagerQTAgg(FigureManagerQT): def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar']=='classic': print "Classic toolbar is not yet supported" elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2QTAgg(canvas, parent) else: toolbar = None return toolbar class FigureCanvasQTAgg( FigureCanvasAgg, FigureCanvasQT ): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def __init__( self, figure ): if DEBUG: print 'FigureCanvasQtAgg: ', figure FigureCanvasQT.__init__( self, figure ) FigureCanvasAgg.__init__( self, figure ) self.drawRect = False self.rect = [] self.replot = True self.pixmap = qt.QPixmap() def resizeEvent( self, e ): FigureCanvasQT.resizeEvent( self, e ) def drawRectangle( self, rect ): self.rect = rect self.drawRect = True # False in repaint does not clear the image before repainting self.repaint( False ) def paintEvent( self, e ): """ Draw to the Agg backend and then copy the image to the qt.drawable. In Qt, all drawing should be done inside of here when a widget is shown onscreen. """ FigureCanvasQT.paintEvent( self, e ) if DEBUG: print 'FigureCanvasQtAgg.paintEvent: ', self, \ self.get_width_height() p = qt.QPainter( self ) # only replot data when needed if type(self.replot) is bool: # might be a bbox for blitting if self.replot: FigureCanvasAgg.draw( self ) #stringBuffer = str( self.buffer_rgba(0,0) ) # matplotlib is in rgba byte order. # qImage wants to put the bytes into argb format and # is in a 4 byte unsigned int. little endian system is LSB first # and expects the bytes in reverse order (bgra). if ( qt.QImage.systemByteOrder() == qt.QImage.LittleEndian ): stringBuffer = self.renderer._renderer.tostring_bgra() else: stringBuffer = self.renderer._renderer.tostring_argb() qImage = qt.QImage( stringBuffer, self.renderer.width, self.renderer.height, 32, None, 0, qt.QImage.IgnoreEndian ) self.pixmap.convertFromImage( qImage, qt.QPixmap.Color ) p.drawPixmap( qt.QPoint( 0, 0 ), self.pixmap ) # draw the zoom rectangle to the QPainter if ( self.drawRect ): p.setPen( qt.QPen( qt.Qt.black, 1, qt.Qt.DotLine ) ) p.drawRect( self.rect[0], self.rect[1], self.rect[2], self.rect[3] ) # we are blitting here else: bbox = self.replot l, b, r, t = bbox.extents w = int(r) - int(l) h = int(t) - int(b) reg = self.copy_from_bbox(bbox) stringBuffer = reg.to_string_argb() qImage = qt.QImage(stringBuffer, w, h, 32, None, 0, qt.QImage.IgnoreEndian) self.pixmap.convertFromImage(qImage, qt.QPixmap.Color) p.drawPixmap(qt.QPoint(l, self.renderer.height-t), self.pixmap) p.end() self.replot = False self.drawRect = False def draw( self ): """ Draw the figure when xwindows is ready for the update """ if DEBUG: print "FigureCanvasQtAgg.draw", self self.replot = True FigureCanvasAgg.draw(self) self.repaint(False) def blit(self, bbox=None): """ Blit the region in bbox """ self.replot = bbox self.repaint(False) def print_figure(self, *args, **kwargs): FigureCanvasAgg.print_figure(self, *args, **kwargs) self.draw()
4,972
Python
.py
121
31.636364
87
0.612401
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,308
backend_gdk.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_gdk.py
from __future__ import division import math import os import sys import warnings def fn_name(): return sys._getframe(1).f_code.co_name import gobject import gtk; gdk = gtk.gdk import pango pygtk_version_required = (2,2,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required import numpy as npy import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase from matplotlib.cbook import is_string_like from matplotlib.figure import Figure from matplotlib.mathtext import MathTextParser from matplotlib.transforms import Affine2D from matplotlib.backends._backend_gdk import pixbuf_get_pixels_array backend_version = "%d.%d.%d" % gtk.pygtk_version _debug = False # Image formats that this backend supports - for FileChooser and print_figure() IMAGE_FORMAT = ['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp'] # , 'raw', 'rgb'] IMAGE_FORMAT.sort() IMAGE_FORMAT_DEFAULT = 'png' class RendererGDK(RendererBase): fontweights = { 100 : pango.WEIGHT_ULTRALIGHT, 200 : pango.WEIGHT_LIGHT, 300 : pango.WEIGHT_LIGHT, 400 : pango.WEIGHT_NORMAL, 500 : pango.WEIGHT_NORMAL, 600 : pango.WEIGHT_BOLD, 700 : pango.WEIGHT_BOLD, 800 : pango.WEIGHT_HEAVY, 900 : pango.WEIGHT_ULTRABOLD, 'ultralight' : pango.WEIGHT_ULTRALIGHT, 'light' : pango.WEIGHT_LIGHT, 'normal' : pango.WEIGHT_NORMAL, 'medium' : pango.WEIGHT_NORMAL, 'semibold' : pango.WEIGHT_BOLD, 'bold' : pango.WEIGHT_BOLD, 'heavy' : pango.WEIGHT_HEAVY, 'ultrabold' : pango.WEIGHT_ULTRABOLD, 'black' : pango.WEIGHT_ULTRABOLD, } # cache for efficiency, these must be at class, not instance level layoutd = {} # a map from text prop tups to pango layouts rotated = {} # a map from text prop tups to rotated text pixbufs def __init__(self, gtkDA, dpi): # widget gtkDA is used for: # '<widget>.create_pango_layout(s)' # cmap line below) self.gtkDA = gtkDA self.dpi = dpi self._cmap = gtkDA.get_colormap() self.mathtext_parser = MathTextParser("Agg") def set_pixmap (self, pixmap): self.gdkDrawable = pixmap def set_width_height (self, width, height): """w,h is the figure w,h not the pixmap w,h """ self.width, self.height = width, height def draw_path(self, gc, path, transform, rgbFace=None): transform = transform + Affine2D(). \ scale(1.0, -1.0).translate(0, self.height) polygons = path.to_polygons(transform, self.width, self.height) for polygon in polygons: # draw_polygon won't take an arbitrary sequence -- it must be a list # of tuples polygon = [(int(round(x)), int(round(y))) for x, y in polygon] if rgbFace is not None: saveColor = gc.gdkGC.foreground gc.gdkGC.foreground = gc.rgb_to_gdk_color(rgbFace) self.gdkDrawable.draw_polygon(gc.gdkGC, True, polygon) gc.gdkGC.foreground = saveColor if gc.gdkGC.line_width > 0: self.gdkDrawable.draw_lines(gc.gdkGC, polygon) def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): if bbox != None: l,b,w,h = bbox.bounds #rectangle = (int(l), self.height-int(b+h), # int(w), int(h)) # set clip rect? im.flipud_out() rows, cols, image_str = im.as_rgba_str() image_array = npy.fromstring(image_str, npy.uint8) image_array.shape = rows, cols, 4 pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True, bits_per_sample=8, width=cols, height=rows) array = pixbuf_get_pixels_array(pixbuf) array[:,:,:] = image_array gc = self.new_gc() y = self.height-y-rows try: # new in 2.2 # can use None instead of gc.gdkGC, if don't need clipping self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0, int(x), int(y), cols, rows, gdk.RGB_DITHER_NONE, 0, 0) except AttributeError: # deprecated in 2.2 pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0, int(x), int(y), cols, rows, gdk.RGB_DITHER_NONE, 0, 0) # unflip im.flipud_out() def draw_text(self, gc, x, y, s, prop, angle, ismath): x, y = int(x), int(y) if x <0 or y <0: # window has shrunk and text is off the edge return if angle not in (0,90): warnings.warn('backend_gdk: unable to draw text at angles ' + 'other than 0 or 90') elif ismath: self._draw_mathtext(gc, x, y, s, prop, angle) elif angle==90: self._draw_rotated_text(gc, x, y, s, prop, angle) else: layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect self.gdkDrawable.draw_layout(gc.gdkGC, x, y-h-b, layout) def _draw_mathtext(self, gc, x, y, s, prop, angle): ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) if angle==90: width, height = height, width x -= width y -= height imw = font_image.get_width() imh = font_image.get_height() N = imw * imh # a numpixels by num fonts array Xall = npy.zeros((N,1), npy.uint8) image_str = font_image.as_str() Xall[:,0] = npy.fromstring(image_str, npy.uint8) # get the max alpha at each pixel Xs = npy.amax(Xall,axis=1) # convert it to it's proper shape Xs.shape = imh, imw pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True, bits_per_sample=8, width=imw, height=imh) array = pixbuf_get_pixels_array(pixbuf) rgb = gc.get_rgb() array[:,:,0]=int(rgb[0]*255) array[:,:,1]=int(rgb[1]*255) array[:,:,2]=int(rgb[2]*255) array[:,:,3]=Xs try: # new in 2.2 # can use None instead of gc.gdkGC, if don't need clipping self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0, int(x), int(y), imw, imh, gdk.RGB_DITHER_NONE, 0, 0) except AttributeError: # deprecated in 2.2 pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0, int(x), int(y), imw, imh, gdk.RGB_DITHER_NONE, 0, 0) def _draw_rotated_text(self, gc, x, y, s, prop, angle): """ Draw the text rotated 90 degrees, other angles are not supported """ # this function (and its called functions) is a bottleneck # Pango 1.6 supports rotated text, but pygtk 2.4.0 does not yet have # wrapper functions # GTK+ 2.6 pixbufs support rotation gdrawable = self.gdkDrawable ggc = gc.gdkGC layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect x = int(x-h) y = int(y-w) if x < 0 or y < 0: # window has shrunk and text is off the edge return key = (x,y,s,angle,hash(prop)) imageVert = self.rotated.get(key) if imageVert != None: gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) return imageBack = gdrawable.get_image(x, y, w, h) imageVert = gdrawable.get_image(x, y, h, w) imageFlip = gtk.gdk.Image(type=gdk.IMAGE_FASTEST, visual=gdrawable.get_visual(), width=w, height=h) if imageFlip == None or imageBack == None or imageVert == None: warnings.warn("Could not renderer vertical text") return imageFlip.set_colormap(self._cmap) for i in range(w): for j in range(h): imageFlip.put_pixel(i, j, imageVert.get_pixel(j,w-i-1) ) gdrawable.draw_image(ggc, imageFlip, 0, 0, x, y, w, h) gdrawable.draw_layout(ggc, x, y-b, layout) imageIn = gdrawable.get_image(x, y, w, h) for i in range(w): for j in range(h): imageVert.put_pixel(j, i, imageIn.get_pixel(w-i-1,j) ) gdrawable.draw_image(ggc, imageBack, 0, 0, x, y, w, h) gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) self.rotated[key] = imageVert def _get_pango_layout(self, s, prop): """ Create a pango layout instance for Text 's' with properties 'prop'. Return - pango layout (from cache if already exists) Note that pango assumes a logical DPI of 96 Ref: pango/fonts.c/pango_font_description_set_size() manual page """ # problem? - cache gets bigger and bigger, is never cleared out # two (not one) layouts are created for every text item s (then they # are cached) - why? key = self.dpi, s, hash(prop) value = self.layoutd.get(key) if value != None: return value size = prop.get_size_in_points() * self.dpi / 96.0 size = round(size) font_str = '%s, %s %i' % (prop.get_name(), prop.get_style(), size,) font = pango.FontDescription(font_str) # later - add fontweight to font_str font.set_weight(self.fontweights[prop.get_weight()]) layout = self.gtkDA.create_pango_layout(s) layout.set_font_description(font) inkRect, logicalRect = layout.get_pixel_extents() self.layoutd[key] = layout, inkRect, logicalRect return layout, inkRect, logicalRect def flipy(self): return True def get_canvas_width_height(self): return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): if ismath: ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect return w, h+1, h + 1 def new_gc(self): return GraphicsContextGDK(renderer=self) def points_to_pixels(self, points): return points/72.0 * self.dpi class GraphicsContextGDK(GraphicsContextBase): # a cache shared by all class instances _cached = {} # map: rgb color -> gdk.Color _joind = { 'bevel' : gdk.JOIN_BEVEL, 'miter' : gdk.JOIN_MITER, 'round' : gdk.JOIN_ROUND, } _capd = { 'butt' : gdk.CAP_BUTT, 'projecting' : gdk.CAP_PROJECTING, 'round' : gdk.CAP_ROUND, } def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer self.gdkGC = gtk.gdk.GC(renderer.gdkDrawable) self._cmap = renderer._cmap def rgb_to_gdk_color(self, rgb): """ rgb - an RGB tuple (three 0.0-1.0 values) return an allocated gtk.gdk.Color """ try: return self._cached[tuple(rgb)] except KeyError: color = self._cached[tuple(rgb)] = \ self._cmap.alloc_color( int(rgb[0]*65535),int(rgb[1]*65535),int(rgb[2]*65535)) return color #def set_antialiased(self, b): # anti-aliasing is not supported by GDK def set_capstyle(self, cs): GraphicsContextBase.set_capstyle(self, cs) self.gdkGC.cap_style = self._capd[self._capstyle] def set_clip_rectangle(self, rectangle): GraphicsContextBase.set_clip_rectangle(self, rectangle) if rectangle is None: return l,b,w,h = rectangle.bounds rectangle = (int(l), self.renderer.height-int(b+h)+1, int(w), int(h)) #rectangle = (int(l), self.renderer.height-int(b+h), # int(w+1), int(h+2)) self.gdkGC.set_clip_rectangle(rectangle) def set_dashes(self, dash_offset, dash_list): GraphicsContextBase.set_dashes(self, dash_offset, dash_list) if dash_list == None: self.gdkGC.line_style = gdk.LINE_SOLID else: pixels = self.renderer.points_to_pixels(npy.asarray(dash_list)) dl = [max(1, int(round(val))) for val in pixels] self.gdkGC.set_dashes(dash_offset, dl) self.gdkGC.line_style = gdk.LINE_ON_OFF_DASH def set_foreground(self, fg, isRGB=False): GraphicsContextBase.set_foreground(self, fg, isRGB) self.gdkGC.foreground = self.rgb_to_gdk_color(self.get_rgb()) def set_graylevel(self, frac): GraphicsContextBase.set_graylevel(self, frac) self.gdkGC.foreground = self.rgb_to_gdk_color(self.get_rgb()) def set_joinstyle(self, js): GraphicsContextBase.set_joinstyle(self, js) self.gdkGC.join_style = self._joind[self._joinstyle] def set_linewidth(self, w): GraphicsContextBase.set_linewidth(self, w) if w == 0: self.gdkGC.line_width = 0 else: pixels = self.renderer.points_to_pixels(w) self.gdkGC.line_width = max(1, int(round(pixels))) def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGDK(thisFig) manager = FigureManagerBase(canvas, num) # equals: #manager = FigureManagerBase (FigureCanvasGDK (Figure(*args, **kwargs), # num) return manager class FigureCanvasGDK (FigureCanvasBase): def __init__(self, figure): FigureCanvasBase.__init__(self, figure) self._renderer_init() def _renderer_init(self): self._renderer = RendererGDK (gtk.DrawingArea(), self.figure.dpi) def _render_figure(self, pixmap, width, height): self._renderer.set_pixmap (pixmap) self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format, *args, **kwargs): width, height = self.get_width_height() pixmap = gtk.gdk.Pixmap (None, width, height, depth=24) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) pixbuf.save(filename, format) def get_default_filetype(self): return 'png'
15,968
Python
.py
360
34.216667
80
0.582183
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,309
backend_gtkagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py
""" Render to gtk from agg """ from __future__ import division import os import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\ show, draw_if_interactive,\ error_msg_gtk, NavigationToolbar, PIXELS_PER_INCH, backend_version, \ NavigationToolbar2GTK from matplotlib.backends._gtkagg import agg_to_gtk_drawable DEBUG = False class NavigationToolbar2GTKAgg(NavigationToolbar2GTK): def _get_canvas(self, fig): return FigureCanvasGTKAgg(fig) class FigureManagerGTKAgg(FigureManagerGTK): def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar']=='classic': toolbar = NavigationToolbar (canvas, self.window) elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2GTKAgg (canvas, self.window) else: toolbar = None return toolbar def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ if DEBUG: print 'backend_gtkagg.new_figure_manager' FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGTKAgg(thisFig) return FigureManagerGTKAgg(canvas, num) if DEBUG: print 'backend_gtkagg.new_figure_manager done' class FigureCanvasGTKAgg(FigureCanvasGTK, FigureCanvasAgg): filetypes = FigureCanvasGTK.filetypes.copy() filetypes.update(FigureCanvasAgg.filetypes) def configure_event(self, widget, event=None): if DEBUG: print 'FigureCanvasGTKAgg.configure_event' if widget.window is None: return try: del self.renderer except AttributeError: pass w,h = widget.window.get_size() if w==1 or h==1: return # empty fig # compute desired figure size in inches dpival = self.figure.dpi winch = w/dpival hinch = h/dpival self.figure.set_size_inches(winch, hinch) self._need_redraw = True self.resize_event() if DEBUG: print 'FigureCanvasGTKAgg.configure_event end' return True def _render_figure(self, pixmap, width, height): if DEBUG: print 'FigureCanvasGTKAgg.render_figure' FigureCanvasAgg.draw(self) if DEBUG: print 'FigureCanvasGTKAgg.render_figure pixmap', pixmap #agg_to_gtk_drawable(pixmap, self.renderer._renderer, None) buf = self.buffer_rgba(0,0) ren = self.get_renderer() w = int(ren.width) h = int(ren.height) pixbuf = gtk.gdk.pixbuf_new_from_data( buf, gtk.gdk.COLORSPACE_RGB, True, 8, w, h, w*4) pixmap.draw_pixbuf(pixmap.new_gc(), pixbuf, 0, 0, 0, 0, w, h, gtk.gdk.RGB_DITHER_NONE, 0, 0) if DEBUG: print 'FigureCanvasGTKAgg.render_figure done' def blit(self, bbox=None): if DEBUG: print 'FigureCanvasGTKAgg.blit' if DEBUG: print 'FigureCanvasGTKAgg.blit', self._pixmap agg_to_gtk_drawable(self._pixmap, self.renderer._renderer, bbox) x, y, w, h = self.allocation self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, w, h) if DEBUG: print 'FigureCanvasGTKAgg.done' def print_png(self, filename, *args, **kwargs): # Do this so we can save the resolution of figure in the PNG file agg = self.switch_backends(FigureCanvasAgg) return agg.print_png(filename, *args, **kwargs) """\ Traceback (most recent call last): File "/home/titan/johnh/local/lib/python2.3/site-packages/matplotlib/backends/backend_gtk.py", line 304, in expose_event self._render_figure(self._pixmap, w, h) File "/home/titan/johnh/local/lib/python2.3/site-packages/matplotlib/backends/backend_gtkagg.py", line 77, in _render_figure pixbuf = gtk.gdk.pixbuf_new_from_data( ValueError: data length (3156672) is less then required by the other parameters (3160608) """
4,184
Python
.py
94
37.170213
126
0.680914
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,310
backend_wxagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_wxagg.py
from __future__ import division """ backend_wxagg.py A wxPython backend for Agg. This uses the GUI widgets written by Jeremy O'Donoghue (jeremy@o-donoghue.com) and the Agg backend by John Hunter (jdhunter@ace.bsd.uchicago.edu) Copyright (C) 2003-5 Jeremy O'Donoghue, John Hunter, Illinois Institute of Technology License: This work is licensed under the matplotlib license( PSF compatible). A copy should be included with this source code. """ import wx import matplotlib from matplotlib.figure import Figure from backend_agg import FigureCanvasAgg import backend_wx from backend_wx import FigureManager, FigureManagerWx, FigureCanvasWx, \ FigureFrameWx, DEBUG_MSG, NavigationToolbar2Wx, error_msg_wx, \ draw_if_interactive, show, Toolbar, backend_version class FigureFrameWxAgg(FigureFrameWx): def get_canvas(self, fig): return FigureCanvasWxAgg(self, -1, fig) def _get_toolbar(self, statbar): if matplotlib.rcParams['toolbar']=='classic': toolbar = NavigationToolbarWx(self.canvas, True) elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2WxAgg(self.canvas) toolbar.set_status_bar(statbar) else: toolbar = None return toolbar class FigureCanvasWxAgg(FigureCanvasAgg, FigureCanvasWx): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wxSizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ def draw(self, drawDC=None): """ Render the figure using agg. """ DEBUG_MSG("draw()", 1, self) FigureCanvasAgg.draw(self) self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self._isDrawn = True self.gui_repaint(drawDC=drawDC) def blit(self, bbox=None): """ Transfer the region of the agg buffer defined by bbox to the display. If bbox is None, the entire buffer is transferred. """ if bbox is None: self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self.gui_repaint() return l, b, w, h = bbox.bounds r = l + w t = b + h x = int(l) y = int(self.bitmap.GetHeight() - t) srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destDC = wx.MemoryDC() destDC.SelectObject(self.bitmap) destDC.BeginDrawing() destDC.Blit(x, y, int(w), int(h), srcDC, x, y) destDC.EndDrawing() destDC.SelectObject(wx.NullBitmap) srcDC.SelectObject(wx.NullBitmap) self.gui_repaint() filetypes = FigureCanvasAgg.filetypes def print_figure(self, filename, *args, **kwargs): # Use pure Agg renderer to draw FigureCanvasAgg.print_figure(self, filename, *args, **kwargs) # Restore the current view; this is needed because the # artist contains methods rely on particular attributes # of the rendered figure for determining things like # bounding boxes. if self._isDrawn: self.draw() class NavigationToolbar2WxAgg(NavigationToolbar2Wx): def get_canvas(self, frame, fig): return FigureCanvasWxAgg(frame, -1, fig) def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # in order to expose the Figure constructor to the pylab # interface we need to create the figure here DEBUG_MSG("new_figure_manager()", 3, None) backend_wx._create_wx_app() FigureClass = kwargs.pop('FigureClass', Figure) fig = FigureClass(*args, **kwargs) frame = FigureFrameWxAgg(num, fig) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() return figmgr # # agg/wxPython image conversion functions (wxPython <= 2.6) # def _py_convert_agg_to_wx_image(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ image = wx.EmptyImage(int(agg.width), int(agg.height)) image.SetData(agg.tostring_rgb()) if bbox is None: # agg => rgb -> image return image else: # agg => rgb -> image => bitmap => clipped bitmap => image return wx.ImageFromBitmap(_clipped_image_as_bitmap(image, bbox)) def _py_convert_agg_to_wx_bitmap(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgb -> image => bitmap return wx.BitmapFromImage(_py_convert_agg_to_wx_image(agg, None)) else: # agg => rgb -> image => bitmap => clipped bitmap return _clipped_image_as_bitmap( _py_convert_agg_to_wx_image(agg, None), bbox) def _clipped_image_as_bitmap(image, bbox): """ Convert the region of a wx.Image bounded by bbox to a wx.Bitmap. """ l, b, width, height = bbox.get_bounds() r = l + width t = b + height srcBmp = wx.BitmapFromImage(image) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destBmp = wx.EmptyBitmap(int(width), int(height)) destDC = wx.MemoryDC() destDC.SelectObject(destBmp) destDC.BeginDrawing() x = int(l) y = int(image.GetHeight() - t) destDC.Blit(0, 0, int(width), int(height), srcDC, x, y) destDC.EndDrawing() srcDC.SelectObject(wx.NullBitmap) destDC.SelectObject(wx.NullBitmap) return destBmp # # agg/wxPython image conversion functions (wxPython >= 2.8) # def _py_WX28_convert_agg_to_wx_image(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgb -> image image = wx.EmptyImage(int(agg.width), int(agg.height)) image.SetData(agg.tostring_rgb()) return image else: # agg => rgba buffer -> bitmap => clipped bitmap => image return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox)) def _py_WX28_convert_agg_to_wx_bitmap(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgba buffer -> bitmap return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba(0, 0)) else: # agg => rgba buffer -> bitmap => clipped bitmap return _WX28_clipped_agg_as_bitmap(agg, bbox) def _WX28_clipped_agg_as_bitmap(agg, bbox): """ Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap. Note: agg must be a backend_agg.RendererAgg instance. """ l, b, width, height = bbox.get_bounds() r = l + width t = b + height srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba(0, 0)) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destBmp = wx.EmptyBitmap(int(width), int(height)) destDC = wx.MemoryDC() destDC.SelectObject(destBmp) destDC.BeginDrawing() x = int(l) y = int(int(agg.height) - t) destDC.Blit(0, 0, int(width), int(height), srcDC, x, y) destDC.EndDrawing() srcDC.SelectObject(wx.NullBitmap) destDC.SelectObject(wx.NullBitmap) return destBmp def _use_accelerator(state): """ Enable or disable the WXAgg accelerator, if it is present and is also compatible with whatever version of wxPython is in use. """ global _convert_agg_to_wx_image global _convert_agg_to_wx_bitmap if getattr(wx, '__version__', '0.0')[0:3] < '2.8': # wxPython < 2.8, so use the C++ accelerator or the Python routines if state and _wxagg is not None: _convert_agg_to_wx_image = _wxagg.convert_agg_to_wx_image _convert_agg_to_wx_bitmap = _wxagg.convert_agg_to_wx_bitmap else: _convert_agg_to_wx_image = _py_convert_agg_to_wx_image _convert_agg_to_wx_bitmap = _py_convert_agg_to_wx_bitmap else: # wxPython >= 2.8, so use the accelerated Python routines _convert_agg_to_wx_image = _py_WX28_convert_agg_to_wx_image _convert_agg_to_wx_bitmap = _py_WX28_convert_agg_to_wx_bitmap # try to load the WXAgg accelerator try: import _wxagg except ImportError: _wxagg = None # if it's present, use it _use_accelerator(True)
9,051
Python
.py
233
32.527897
78
0.663621
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,311
backend_template.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_template.py
""" This is a fully functional do nothing backend to provide a template to backend writers. It is fully functional in that you can select it as a backend with import matplotlib matplotlib.use('Template') and your matplotlib scripts will (should!) run without error, though no output is produced. This provides a nice starting point for backend writers because you can selectively implement methods (draw_rectangle, draw_lines, etc...) and slowly see your figure come to life w/o having to have a full blown implementation before getting any results. Copy this to backend_xxx.py and replace all instances of 'template' with 'xxx'. Then implement the class methods and functions below, and add 'xxx' to the switchyard in matplotlib/backends/__init__.py and 'xxx' to the backends list in the validate_backend methon in matplotlib/__init__.py and you're off. You can use your backend with:: import matplotlib matplotlib.use('xxx') from pylab import * plot([1,2,3]) show() matplotlib also supports external backends, so you can place you can use any module in your PYTHONPATH with the syntax:: import matplotlib matplotlib.use('module://my_backend') where my_backend.py is your module name. Thus syntax is also recognized in the rc file and in the -d argument in pylab, eg:: python simple_plot.py -dmodule://my_backend The files that are most relevant to backend_writers are matplotlib/backends/backend_your_backend.py matplotlib/backend_bases.py matplotlib/backends/__init__.py matplotlib/__init__.py matplotlib/_pylab_helpers.py Naming Conventions * classes Upper or MixedUpperCase * varables lower or lowerUpper * functions lower or underscore_separated """ from __future__ import division import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.figure import Figure from matplotlib.transforms import Bbox class RendererTemplate(RendererBase): """ The renderer handles drawing/rendering operations. This is a minimal do-nothing class that can be used to get started when writing a new backend. Refer to backend_bases.RendererBase for documentation of the classes methods. """ def __init__(self, dpi): self.dpi = dpi def draw_path(self, gc, path, transform, rgbFace=None): pass # draw_markers is optional, and we get more correct relative # timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): # pass # draw_path_collection is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_path_collection(self, master_transform, cliprect, clippath, # clippath_trans, paths, all_transforms, offsets, # offsetTrans, facecolors, edgecolors, linewidths, # linestyles, antialiaseds): # pass # draw_quad_mesh is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_quad_mesh(self, master_transform, cliprect, clippath, # clippath_trans, meshWidth, meshHeight, coordinates, # offsets, offsetTrans, facecolors, antialiased, # showedges): # pass def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False): pass def flipy(self): return True def get_canvas_width_height(self): return 100, 100 def get_text_width_height_descent(self, s, prop, ismath): return 1, 1, 1 def new_gc(self): return GraphicsContextTemplate() def points_to_pixels(self, points): # if backend doesn't have dpi, eg, postscript or svg return points # elif backend assumes a value for pixels_per_inch #return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 # else #return points/72.0 * self.dpi.get() class GraphicsContextTemplate(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... See the gtk and postscript backends for examples of mapping the graphics context attributes (cap styles, join styles, line widths, colors) to a particular backend. In GTK this is done by wrapping a gtk.gdk.GC object and forwarding the appropriate calls to it using a dictionary mapping styles to gdk constants. In Postscript, all the work is done by the renderer, mapping line styles to postscript calls. If it's more appropriate to do the mapping at the renderer level (as in the postscript backend), you don't need to override any of the GC methods. If it's more appropriate to wrap an instance (as in the GTK backend) and do the mapping here, you'll need to override several of the setter methods. The base GraphicsContext stores colors as a RGB tuple on the unit interval, eg, (0.5, 0.0, 1.0). You may need to map this to colors appropriate for your backend. """ pass ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def draw_if_interactive(): """ For image backends - is not required For GUI backends - this should be overriden if drawing should be done in interactive python mode """ pass def show(): """ For image backends - is not required For GUI backends - show() is usually the last line of a pylab script and tells the backend that it is time to draw. In interactive mode, this may be a do nothing func. See the GTK backend for an example of how to handle interactive versus batch mode """ for manager in Gcf.get_all_fig_managers(): # do something to display the GUI pass def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # if a main-level app must be created, this is the usual place to # do it -- see backend_wx, backend_wxagg and backend_tkagg for # examples. Not all GUIs require explicit instantiation of a # main-level app (egg backend_gtk, backend_gtkagg) for pylab FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasTemplate(thisFig) manager = FigureManagerTemplate(canvas, num) return manager class FigureCanvasTemplate(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance Note GUI templates will want to connect events for button presses, mouse movements and key presses to functions that call the base class methods button_press_event, button_release_event, motion_notify_event, key_press_event, and key_release_event. See, eg backend_gtk.py, backend_wx.py and backend_tkagg.py """ def draw(self): """ Draw the figure using the renderer """ renderer = RendererTemplate(self.figure.dpi) self.figure.draw(renderer) # You should provide a print_xxx function for every file format # you can write. # If the file type is not in the base set of filetypes, # you should add it to the class-scope filetypes dictionary as follows: filetypes = FigureCanvasBase.filetypes.copy() filetypes['foo'] = 'My magic Foo format' def print_foo(self, filename, *args, **kwargs): """ Write out format foo. The dpi, facecolor and edgecolor are restored to their original values after this call, so you don't need to save and restore them. """ pass def get_default_filetype(self): return 'foo' class FigureManagerTemplate(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ pass ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## FigureManager = FigureManagerTemplate
8,806
Python
.py
199
39.748744
87
0.691426
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,312
backend_qt4agg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_qt4agg.py
""" Render to qt from agg """ from __future__ import division import os, sys import matplotlib from matplotlib.figure import Figure from backend_agg import FigureCanvasAgg from backend_qt4 import QtCore, QtGui, FigureManagerQT, FigureCanvasQT,\ show, draw_if_interactive, backend_version, \ NavigationToolbar2QT DEBUG = False def new_figure_manager( num, *args, **kwargs ): """ Create a new figure manager instance """ if DEBUG: print 'backend_qtagg.new_figure_manager' FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass( *args, **kwargs ) canvas = FigureCanvasQTAgg( thisFig ) return FigureManagerQT( canvas, num ) class NavigationToolbar2QTAgg(NavigationToolbar2QT): def _get_canvas(self, fig): return FigureCanvasQTAgg(fig) class FigureManagerQTAgg(FigureManagerQT): def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar']=='classic': print "Classic toolbar is not supported" elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2QTAgg(canvas, parent) else: toolbar = None return toolbar class FigureCanvasQTAgg( FigureCanvasQT, FigureCanvasAgg ): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def __init__( self, figure ): if DEBUG: print 'FigureCanvasQtAgg: ', figure FigureCanvasQT.__init__( self, figure ) FigureCanvasAgg.__init__( self, figure ) self.drawRect = False self.rect = [] self.replot = True self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) def resizeEvent( self, e ): FigureCanvasQT.resizeEvent( self, e ) def drawRectangle( self, rect ): self.rect = rect self.drawRect = True self.repaint( ) def paintEvent( self, e ): """ Draw to the Agg backend and then copy the image to the qt.drawable. In Qt, all drawing should be done inside of here when a widget is shown onscreen. """ #FigureCanvasQT.paintEvent( self, e ) if DEBUG: print 'FigureCanvasQtAgg.paintEvent: ', self, \ self.get_width_height() # only replot data when needed if type(self.replot) is bool: # might be a bbox for blitting if self.replot: FigureCanvasAgg.draw(self) # matplotlib is in rgba byte order. QImage wants to put the bytes # into argb format and is in a 4 byte unsigned int. Little endian # system is LSB first and expects the bytes in reverse order # (bgra). if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian: stringBuffer = self.renderer._renderer.tostring_bgra() else: stringBuffer = self.renderer._renderer.tostring_argb() qImage = QtGui.QImage(stringBuffer, self.renderer.width, self.renderer.height, QtGui.QImage.Format_ARGB32) p = QtGui.QPainter(self) p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage)) # draw the zoom rectangle to the QPainter if self.drawRect: p.setPen( QtGui.QPen( QtCore.Qt.black, 1, QtCore.Qt.DotLine ) ) p.drawRect( self.rect[0], self.rect[1], self.rect[2], self.rect[3] ) p.end() # we are blitting here else: bbox = self.replot l, b, r, t = bbox.extents w = int(r) - int(l) h = int(t) - int(b) t = int(b) + h reg = self.copy_from_bbox(bbox) stringBuffer = reg.to_string_argb() qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(qImage) p = QtGui.QPainter( self ) p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap) p.end() self.replot = False self.drawRect = False def draw( self ): """ Draw the figure when xwindows is ready for the update """ if DEBUG: print "FigureCanvasQtAgg.draw", self self.replot = True FigureCanvasAgg.draw(self) self.update() # Added following line to improve realtime pan/zoom on windows: QtGui.qApp.processEvents() def blit(self, bbox=None): """ Blit the region in bbox """ self.replot = bbox l, b, w, h = bbox.bounds t = b + h self.update(l, self.renderer.height-t, w, h) def print_figure(self, *args, **kwargs): FigureCanvasAgg.print_figure(self, *args, **kwargs) self.draw()
4,985
Python
.py
124
31.008065
84
0.615305
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,313
__init__.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/__init__.py
import matplotlib import inspect import warnings # ipython relies on interactive_bk being defined here from matplotlib.rcsetup import interactive_bk __all__ = ['backend','show','draw_if_interactive', 'new_figure_manager', 'backend_version'] backend = matplotlib.get_backend() # validates, to match all_backends def pylab_setup(): 'return new_figure_manager, draw_if_interactive and show for pylab' # Import the requested backend into a generic module object if backend.startswith('module://'): backend_name = backend[9:] else: backend_name = 'backend_'+backend backend_name = backend_name.lower() # until we banish mixed case backend_name = 'matplotlib.backends.%s'%backend_name.lower() backend_mod = __import__(backend_name, globals(),locals(),[backend_name]) # Things we pull in from all backends new_figure_manager = backend_mod.new_figure_manager # image backends like pdf, agg or svg do not need to do anything # for "show" or "draw_if_interactive", so if they are not defined # by the backend, just do nothing def do_nothing_show(*args, **kwargs): frame = inspect.currentframe() fname = frame.f_back.f_code.co_filename if fname in ('<stdin>', '<ipython console>'): warnings.warn(""" Your currently selected backend, '%s' does not support show(). Please select a GUI backend in your matplotlibrc file ('%s') or with matplotlib.use()""" % (backend, matplotlib.matplotlib_fname())) def do_nothing(*args, **kwargs): pass backend_version = getattr(backend_mod,'backend_version', 'unknown') show = getattr(backend_mod, 'show', do_nothing_show) draw_if_interactive = getattr(backend_mod, 'draw_if_interactive', do_nothing) # Additional imports which only happen for certain backends. This section # should probably disappear once all backends are uniform. if backend.lower() in ['wx','wxagg']: Toolbar = backend_mod.Toolbar __all__.append('Toolbar') matplotlib.verbose.report('backend %s version %s' % (backend,backend_version)) return new_figure_manager, draw_if_interactive, show
2,225
Python
.py
44
44.045455
82
0.684502
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,314
backend_ps.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_ps.py
""" A PostScript backend, which can produce both PostScript .ps and .eps """ from __future__ import division import glob, math, os, shutil, sys, time def _fn_name(): return sys._getframe(1).f_code.co_name try: from hashlib import md5 except ImportError: from md5 import md5 #Deprecated in 2.5 from tempfile import gettempdir from cStringIO import StringIO from matplotlib import verbose, __version__, rcParams from matplotlib._pylab_helpers import Gcf from matplotlib.afm import AFM from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.cbook import is_string_like, get_realpath_and_stat, \ is_writable_file_like, maxdict from matplotlib.mlab import quad2cubic from matplotlib.figure import Figure from matplotlib.font_manager import findfont, is_opentype_cff_font from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, LOAD_NO_HINTING from matplotlib.ttconv import convert_ttf_to_ps from matplotlib.mathtext import MathTextParser from matplotlib._mathtext_data import uni2type1 from matplotlib.text import Text from matplotlib.path import Path from matplotlib.transforms import IdentityTransform import numpy as npy import binascii import re try: set except NameError: from sets import Set as set if sys.platform.startswith('win'): cmd_split = '&' else: cmd_split = ';' backend_version = 'Level II' debugPS = 0 papersize = {'letter': (8.5,11), 'legal': (8.5,14), 'ledger': (11,17), 'a0': (33.11,46.81), 'a1': (23.39,33.11), 'a2': (16.54,23.39), 'a3': (11.69,16.54), 'a4': (8.27,11.69), 'a5': (5.83,8.27), 'a6': (4.13,5.83), 'a7': (2.91,4.13), 'a8': (2.07,2.91), 'a9': (1.457,2.05), 'a10': (1.02,1.457), 'b0': (40.55,57.32), 'b1': (28.66,40.55), 'b2': (20.27,28.66), 'b3': (14.33,20.27), 'b4': (10.11,14.33), 'b5': (7.16,10.11), 'b6': (5.04,7.16), 'b7': (3.58,5.04), 'b8': (2.51,3.58), 'b9': (1.76,2.51), 'b10': (1.26,1.76)} def _get_papertype(w, h): keys = papersize.keys() keys.sort() keys.reverse() for key in keys: if key.startswith('l'): continue pw, ph = papersize[key] if (w < pw) and (h < ph): return key else: return 'a0' def _num_to_str(val): if is_string_like(val): return val ival = int(val) if val==ival: return str(ival) s = "%1.3f"%val s = s.rstrip("0") s = s.rstrip(".") return s def _nums_to_str(*args): return ' '.join(map(_num_to_str,args)) def quote_ps_string(s): "Quote dangerous characters of S for use in a PostScript string constant." s=s.replace("\\", "\\\\") s=s.replace("(", "\\(") s=s.replace(")", "\\)") s=s.replace("'", "\\251") s=s.replace("`", "\\301") s=re.sub(r"[^ -~\n]", lambda x: r"\%03o"%ord(x.group()), s) return s def seq_allequal(seq1, seq2): """ seq1 and seq2 are either None or sequences or numerix arrays Return True if both are None or both are seqs with identical elements """ if seq1 is None: return seq2 is None if seq2 is None: return False #ok, neither are None:, assuming iterable if len(seq1) != len(seq2): return False return npy.alltrue(npy.equal(seq1, seq2)) class RendererPS(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles. """ fontd = maxdict(50) afmfontd = maxdict(50) def __init__(self, width, height, pswriter, imagedpi=72): """ Although postscript itself is dpi independent, we need to imform the image code about a requested dpi to generate high res images and them scale them before embeddin them """ RendererBase.__init__(self) self.width = width self.height = height self._pswriter = pswriter if rcParams['text.usetex']: self.textcnt = 0 self.psfrag = [] self.imagedpi = imagedpi if rcParams['path.simplify']: self.simplify = (width * imagedpi, height * imagedpi) else: self.simplify = None # current renderer state (None=uninitialised) self.color = None self.linewidth = None self.linejoin = None self.linecap = None self.linedash = None self.fontname = None self.fontsize = None self.hatch = None self.image_magnification = imagedpi/72.0 self._clip_paths = {} self._path_collection_id = 0 self.used_characters = {} self.mathtext_parser = MathTextParser("PS") def track_characters(self, font, s): """Keeps track of which characters are required from each font.""" realpath, stat_key = get_realpath_and_stat(font.fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s]) def merge_used_characters(self, other): for stat_key, (realpath, charset) in other.items(): used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update(charset) def set_color(self, r, g, b, store=1): if (r,g,b) != self.color: if r==g and r==b: self._pswriter.write("%1.3f setgray\n"%r) else: self._pswriter.write("%1.3f %1.3f %1.3f setrgbcolor\n"%(r,g,b)) if store: self.color = (r,g,b) def set_linewidth(self, linewidth, store=1): if linewidth != self.linewidth: self._pswriter.write("%1.3f setlinewidth\n"%linewidth) if store: self.linewidth = linewidth def set_linejoin(self, linejoin, store=1): if linejoin != self.linejoin: self._pswriter.write("%d setlinejoin\n"%linejoin) if store: self.linejoin = linejoin def set_linecap(self, linecap, store=1): if linecap != self.linecap: self._pswriter.write("%d setlinecap\n"%linecap) if store: self.linecap = linecap def set_linedash(self, offset, seq, store=1): if self.linedash is not None: oldo, oldseq = self.linedash if seq_allequal(seq, oldseq): return if seq is not None and len(seq): s="[%s] %d setdash\n"%(_nums_to_str(*seq), offset) self._pswriter.write(s) else: self._pswriter.write("[] 0 setdash\n") if store: self.linedash = (offset,seq) def set_font(self, fontname, fontsize, store=1): if rcParams['ps.useafm']: return if (fontname,fontsize) != (self.fontname,self.fontsize): out = ("/%s findfont\n" "%1.3f scalefont\n" "setfont\n" % (fontname,fontsize)) self._pswriter.write(out) if store: self.fontname = fontname if store: self.fontsize = fontsize def set_hatch(self, hatch): """ hatch can be one of: / - diagonal hatching \ - back diagonal | - vertical - - horizontal + - crossed X - crossed diagonal letters can be combined, in which case all the specified hatchings are done if same letter repeats, it increases the density of hatching in that direction """ hatches = {'horiz':0, 'vert':0, 'diag1':0, 'diag2':0} for letter in hatch: if (letter == '/'): hatches['diag2'] += 1 elif (letter == '\\'): hatches['diag1'] += 1 elif (letter == '|'): hatches['vert'] += 1 elif (letter == '-'): hatches['horiz'] += 1 elif (letter == '+'): hatches['horiz'] += 1 hatches['vert'] += 1 elif (letter.lower() == 'x'): hatches['diag1'] += 1 hatches['diag2'] += 1 def do_hatch(angle, density): if (density == 0): return "" return """\ gsave eoclip %s rotate 0.0 0.0 0.0 0.0 setrgbcolor 0 setlinewidth /hatchgap %d def pathbbox /hatchb exch def /hatchr exch def /hatcht exch def /hatchl exch def hatchl cvi hatchgap idiv hatchgap mul hatchgap hatchr cvi hatchgap idiv hatchgap mul {hatcht m 0 hatchb hatcht sub r } for stroke grestore """ % (angle, 12/density) self._pswriter.write("gsave\n") self._pswriter.write(do_hatch(90, hatches['horiz'])) self._pswriter.write(do_hatch(0, hatches['vert'])) self._pswriter.write(do_hatch(45, hatches['diag1'])) self._pswriter.write(do_hatch(-45, hatches['diag2'])) self._pswriter.write("grestore\n") def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop """ if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() l,b,r,t = texmanager.get_ps_bbox(s, fontsize) w = (r-l) h = (t-b) # TODO: We need a way to get a good baseline from # text.usetex return w, h, 0 if ismath: width, height, descent, pswriter, used_characters = \ self.mathtext_parser.parse(s, 72, prop) return width, height, descent if rcParams['ps.useafm']: if ismath: s = s[1:-1] font = self._get_font_afm(prop) l,b,w,h,d = font.get_str_bbox_and_descent(s) fontsize = prop.get_size_in_points() scale = 0.001*fontsize w *= scale h *= scale d *= scale return w, h, d font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 d = font.get_descent() d /= 64.0 #print s, w, h return w, h, d def flipy(self): 'return true if small y numbers are top for renderer' return False def _get_font_afm(self, prop): key = hash(prop) font = self.afmfontd.get(key) if font is None: fname = findfont(prop, fontext='afm') font = self.afmfontd.get(fname) if font is None: font = AFM(file(findfont(prop, fontext='afm'))) self.afmfontd[fname] = font self.afmfontd[key] = font return font def _get_font_ttf(self, prop): key = hash(prop) font = self.fontd.get(key) if font is None: fname = findfont(prop) font = self.fontd.get(fname) if font is None: font = FT2Font(str(fname)) self.fontd[fname] = font self.fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, 72.0) return font def _rgba(self, im): return im.as_rgba_str() def _rgb(self, im): h,w,s = im.as_rgba_str() rgba = npy.fromstring(s, npy.uint8) rgba.shape = (h, w, 4) rgb = rgba[:,:,:3] return h, w, rgb.tostring() def _gray(self, im, rc=0.3, gc=0.59, bc=0.11): rgbat = im.as_rgba_str() rgba = npy.fromstring(rgbat[2], npy.uint8) rgba.shape = (rgbat[0], rgbat[1], 4) rgba_f = rgba.astype(npy.float32) r = rgba_f[:,:,0] g = rgba_f[:,:,1] b = rgba_f[:,:,2] gray = (r*rc + g*gc + b*bc).astype(npy.uint8) return rgbat[0], rgbat[1], gray.tostring() def _hex_lines(self, s, chars_per_line=128): s = binascii.b2a_hex(s) nhex = len(s) lines = [] for i in range(0,nhex,chars_per_line): limit = min(i+chars_per_line, nhex) lines.append(s[i:limit]) return lines def get_image_magnification(self): """ Get the factor by which to magnify images passed to draw_image. Allows a backend to have images at a different resolution to other artists. """ return self.image_magnification def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): """ Draw the Image instance into the current axes; x is the distance in pixels from the left hand side of the canvas and y is the distance from bottom bbox is a matplotlib.transforms.BBox instance for clipping, or None """ im.flipud_out() if im.is_grayscale: h, w, bits = self._gray(im) imagecmd = "image" else: h, w, bits = self._rgb(im) imagecmd = "false 3 colorimage" hexlines = '\n'.join(self._hex_lines(bits)) xscale, yscale = ( w/self.image_magnification, h/self.image_magnification) figh = self.height*72 #print 'values', origin, flipud, figh, h, y clip = [] if bbox is not None: clipx,clipy,clipw,cliph = bbox.bounds clip.append('%s clipbox' % _nums_to_str(clipw, cliph, clipx, clipy)) if clippath is not None: id = self._get_clip_path(clippath, clippath_trans) clip.append('%s' % id) clip = '\n'.join(clip) #y = figh-(y+h) ps = """gsave %(clip)s %(x)s %(y)s translate %(xscale)s %(yscale)s scale /DataString %(w)s string def %(w)s %(h)s 8 [ %(w)s 0 0 -%(h)s 0 %(h)s ] { currentfile DataString readhexstring pop } bind %(imagecmd)s %(hexlines)s grestore """ % locals() self._pswriter.write(ps) # unflip im.flipud_out() def _convert_path(self, path, transform, simplify=None): path = transform.transform_path(path) ps = [] last_points = None for points, code in path.iter_segments(simplify): if code == Path.MOVETO: ps.append("%g %g m" % tuple(points)) elif code == Path.LINETO: ps.append("%g %g l" % tuple(points)) elif code == Path.CURVE3: points = quad2cubic(*(list(last_points[-2:]) + list(points))) ps.append("%g %g %g %g %g %g c" % tuple(points[2:])) elif code == Path.CURVE4: ps.append("%g %g %g %g %g %g c" % tuple(points)) elif code == Path.CLOSEPOLY: ps.append("cl") last_points = points ps = "\n".join(ps) return ps def _get_clip_path(self, clippath, clippath_transform): id = self._clip_paths.get((clippath, clippath_transform)) if id is None: id = 'c%x' % len(self._clip_paths) ps_cmd = ['/%s {' % id] ps_cmd.append(self._convert_path(clippath, clippath_transform)) ps_cmd.extend(['clip', 'newpath', '} bind def\n']) self._pswriter.write('\n'.join(ps_cmd)) self._clip_paths[(clippath, clippath_transform)] = id return id def draw_path(self, gc, path, transform, rgbFace=None): """ Draws a Path instance using the given affine transform. """ ps = self._convert_path(path, transform, self.simplify) self._draw_ps(ps, gc, rgbFace) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): """ Draw the markers defined by path at each of the positions in x and y. path coordinates are points, x and y coords will be transformed by the transform """ if debugPS: self._pswriter.write('% draw_markers \n') write = self._pswriter.write if rgbFace: if rgbFace[0]==rgbFace[1] and rgbFace[0]==rgbFace[2]: ps_color = '%1.3f setgray' % rgbFace[0] else: ps_color = '%1.3f %1.3f %1.3f setrgbcolor' % rgbFace # construct the generic marker command: ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] # dont want the translate to be global ps_cmd.append(self._convert_path(marker_path, marker_trans)) if rgbFace: ps_cmd.extend(['gsave', ps_color, 'fill', 'grestore']) ps_cmd.extend(['stroke', 'grestore', '} bind def']) tpath = trans.transform_path(path) for vertices, code in tpath.iter_segments(): if len(vertices): x, y = vertices[-2:] ps_cmd.append("%g %g o" % (x, y)) ps = '\n'.join(ps_cmd) self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False) def draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): write = self._pswriter.write path_codes = [] for i, (path, transform) in enumerate(self._iter_collection_raw_paths( master_transform, paths, all_transforms)): name = 'p%x_%x' % (self._path_collection_id, i) ps_cmd = ['/%s {' % name, 'newpath', 'translate'] ps_cmd.append(self._convert_path(path, transform)) ps_cmd.extend(['} bind def\n']) write('\n'.join(ps_cmd)) path_codes.append(name) for xo, yo, path_id, gc, rgbFace in self._iter_collection( path_codes, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): ps = "%g %g %s" % (xo, yo, path_id) self._draw_ps(ps, gc, rgbFace) self._path_collection_id += 1 def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!'): """ draw a Text instance """ w, h, bl = self.get_text_width_height_descent(s, prop, ismath) fontsize = prop.get_size_in_points() corr = 0#w/2*(fontsize-10)/10 pos = _nums_to_str(x-corr, y) thetext = 'psmarker%d' % self.textcnt color = '%1.3f,%1.3f,%1.3f'% gc.get_rgb()[:3] fontcmd = {'sans-serif' : r'{\sffamily %s}', 'monospace' : r'{\ttfamily %s}'}.get( rcParams['font.family'], r'{\rmfamily %s}') s = fontcmd % s tex = r'\color[rgb]{%s} %s' % (color, s) self.psfrag.append(r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}'%(thetext, angle, fontsize, fontsize*1.25, tex)) ps = """\ gsave %(pos)s moveto (%(thetext)s) show grestore """ % locals() self._pswriter.write(ps) self.textcnt += 1 def draw_text(self, gc, x, y, s, prop, angle, ismath): """ draw a Text instance """ # local to avoid repeated attribute lookups write = self._pswriter.write if debugPS: write("% text\n") if ismath=='TeX': return self.tex(gc, x, y, s, prop, angle) elif ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) elif isinstance(s, unicode): return self.draw_unicode(gc, x, y, s, prop, angle) elif rcParams['ps.useafm']: font = self._get_font_afm(prop) l,b,w,h = font.get_str_bbox(s) fontsize = prop.get_size_in_points() l *= 0.001*fontsize b *= 0.001*fontsize w *= 0.001*fontsize h *= 0.001*fontsize if angle==90: l,b = -b, l # todo generalize for arb rotations pos = _nums_to_str(x-l, y-b) thetext = '(%s)' % s fontname = font.get_fontname() fontsize = prop.get_size_in_points() rotate = '%1.1f rotate' % angle setcolor = '%1.3f %1.3f %1.3f setrgbcolor' % gc.get_rgb()[:3] #h = 0 ps = """\ gsave /%(fontname)s findfont %(fontsize)s scalefont setfont %(pos)s moveto %(rotate)s %(thetext)s %(setcolor)s show grestore """ % locals() self._draw_ps(ps, gc, None) else: font = self._get_font_ttf(prop) font.set_text(s, 0, flags=LOAD_NO_HINTING) self.track_characters(font, s) self.set_color(*gc.get_rgb()) self.set_font(font.get_sfnt()[(1,0,0,6)], prop.get_size_in_points()) write("%s m\n"%_nums_to_str(x,y)) if angle: write("gsave\n") write("%s rotate\n"%_num_to_str(angle)) descent = font.get_descent() / 64.0 if descent: write("0 %s rmoveto\n"%_num_to_str(descent)) write("(%s) show\n"%quote_ps_string(s)) if angle: write("grestore\n") def new_gc(self): return GraphicsContextPS() def draw_unicode(self, gc, x, y, s, prop, angle): """draw a unicode string. ps doesn't have unicode support, so we have to do this the hard way """ if rcParams['ps.useafm']: self.set_color(*gc.get_rgb()) font = self._get_font_afm(prop) fontname = font.get_fontname() fontsize = prop.get_size_in_points() scale = 0.001*fontsize thisx = 0 thisy = font.get_str_bbox_and_descent(s)[4] * scale last_name = None lines = [] for c in s: name = uni2type1.get(ord(c), 'question') try: width = font.get_width_from_char_name(name) except KeyError: name = 'question' width = font.get_width_char('?') if last_name is not None: kern = font.get_kern_dist_from_name(last_name, name) else: kern = 0 last_name = name thisx += kern * scale lines.append('%f %f m /%s glyphshow'%(thisx, thisy, name)) thisx += width * scale thetext = "\n".join(lines) ps = """\ gsave /%(fontname)s findfont %(fontsize)s scalefont setfont %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) else: font = self._get_font_ttf(prop) font.set_text(s, 0, flags=LOAD_NO_HINTING) self.track_characters(font, s) self.set_color(*gc.get_rgb()) self.set_font(font.get_sfnt()[(1,0,0,6)], prop.get_size_in_points()) cmap = font.get_charmap() lastgind = None #print 'text', s lines = [] thisx = 0 thisy = font.get_descent() / 64.0 for c in s: ccode = ord(c) gind = cmap.get(ccode) if gind is None: ccode = ord('?') name = '.notdef' gind = 0 else: name = font.get_glyph_name(gind) glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if lastgind is not None: kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT) else: kern = 0 lastgind = gind thisx += kern/64.0 lines.append('%f %f m /%s glyphshow'%(thisx, thisy, name)) thisx += glyph.linearHoriAdvance/65536.0 thetext = '\n'.join(lines) ps = """gsave %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ if debugPS: self._pswriter.write("% mathtext\n") width, height, descent, pswriter, used_characters = \ self.mathtext_parser.parse(s, 72, prop) self.merge_used_characters(used_characters) self.set_color(*gc.get_rgb()) thetext = pswriter.getvalue() ps = """gsave %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None): """ Emit the PostScript sniplet 'ps' with all the attributes from 'gc' applied. 'ps' must consist of PostScript commands to construct a path. The fill and/or stroke kwargs can be set to False if the 'ps' string already includes filling and/or stroking, in which case _draw_ps is just supplying properties and clipping. """ # local variable eliminates all repeated attribute lookups write = self._pswriter.write if debugPS and command: write("% "+command+"\n") mightstroke = (gc.get_linewidth() > 0.0 and (len(gc.get_rgb()) <= 3 or gc.get_rgb()[3] != 0.0)) stroke = stroke and mightstroke fill = (fill and rgbFace is not None and (len(rgbFace) <= 3 or rgbFace[3] != 0.0)) if mightstroke: self.set_linewidth(gc.get_linewidth()) jint = gc.get_joinstyle() self.set_linejoin(jint) cint = gc.get_capstyle() self.set_linecap(cint) self.set_linedash(*gc.get_dashes()) self.set_color(*gc.get_rgb()[:3]) write('gsave\n') cliprect = gc.get_clip_rectangle() if cliprect: x,y,w,h=cliprect.bounds write('%1.4g %1.4g %1.4g %1.4g clipbox\n' % (w,h,x,y)) clippath, clippath_trans = gc.get_clip_path() if clippath: id = self._get_clip_path(clippath, clippath_trans) write('%s\n' % id) # Jochen, is the strip necessary? - this could be a honking big string write(ps.strip()) write("\n") if fill: if stroke: write("gsave\n") self.set_color(store=0, *rgbFace[:3]) write("fill\ngrestore\n") else: self.set_color(store=0, *rgbFace[:3]) write("fill\n") hatch = gc.get_hatch() if hatch: self.set_hatch(hatch) if stroke: write("stroke\n") write("grestore\n") class GraphicsContextPS(GraphicsContextBase): def get_capstyle(self): return {'butt':0, 'round':1, 'projecting':2}[GraphicsContextBase.get_capstyle(self)] def get_joinstyle(self): return {'miter':0, 'round':1, 'bevel':2}[GraphicsContextBase.get_joinstyle(self)] def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasPS(thisFig) manager = FigureManagerPS(canvas, num) return manager class FigureCanvasPS(FigureCanvasBase): def draw(self): pass filetypes = {'ps' : 'Postscript', 'eps' : 'Encapsulated Postscript'} def get_default_filetype(self): return 'ps' def print_ps(self, outfile, *args, **kwargs): return self._print_ps(outfile, 'ps', *args, **kwargs) def print_eps(self, outfile, *args, **kwargs): return self._print_ps(outfile, 'eps', *args, **kwargs) def _print_ps(self, outfile, format, *args, **kwargs): papertype = kwargs.get("papertype", rcParams['ps.papersize']) papertype = papertype.lower() if papertype == 'auto': pass elif papertype not in papersize: raise RuntimeError( '%s is not a valid papertype. Use one \ of %s'% (papertype, ', '.join( papersize.keys() )) ) orientation = kwargs.get("orientation", "portrait").lower() if orientation == 'landscape': isLandscape = True elif orientation == 'portrait': isLandscape = False else: raise RuntimeError('Orientation must be "portrait" or "landscape"') self.figure.set_dpi(72) # Override the dpi kwarg imagedpi = kwargs.get("dpi", 72) facecolor = kwargs.get("facecolor", "w") edgecolor = kwargs.get("edgecolor", "w") if rcParams['text.usetex']: self._print_figure_tex(outfile, format, imagedpi, facecolor, edgecolor, orientation, isLandscape, papertype) else: self._print_figure(outfile, format, imagedpi, facecolor, edgecolor, orientation, isLandscape, papertype) def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w', orientation='portrait', isLandscape=False, papertype=None): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy If outfile is a string, it is interpreted as a file name. If the extension matches .ep* write encapsulated postscript, otherwise write a stand-alone PostScript file. If outfile is a file object, a stand-alone PostScript file is written into this file object. """ isEPSF = format == 'eps' passed_in_file_object = False if is_string_like(outfile): title = outfile tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest()) elif is_writable_file_like(outfile): title = None tmpfile = os.path.join(gettempdir(), md5(str(hash(outfile))).hexdigest()) passed_in_file_object = True else: raise ValueError("outfile must be a path or a file-like object") fh = file(tmpfile, 'w') # find the appropriate papertype width, height = self.figure.get_size_inches() if papertype == 'auto': if isLandscape: papertype = _get_papertype(height, width) else: papertype = _get_papertype(width, height) if isLandscape: paperHeight, paperWidth = papersize[papertype] else: paperWidth, paperHeight = papersize[papertype] if rcParams['ps.usedistiller'] and not papertype == 'auto': # distillers will improperly clip eps files if the pagesize is # too small if width>paperWidth or height>paperHeight: if isLandscape: papertype = _get_papertype(height, width) paperHeight, paperWidth = papersize[papertype] else: papertype = _get_papertype(width, height) paperWidth, paperHeight = papersize[papertype] # center the figure on the paper xo = 72*0.5*(paperWidth - width) yo = 72*0.5*(paperHeight - height) l, b, w, h = self.figure.bbox.bounds llx = xo lly = yo urx = llx + w ury = lly + h rotation = 0 if isLandscape: llx, lly, urx, ury = lly, llx, ury, urx xo, yo = 72*paperHeight - yo, xo rotation = 90 bbox = (llx, lly, urx, ury) # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # write the PostScript headers if isEPSF: print >>fh, "%!PS-Adobe-3.0 EPSF-3.0" else: print >>fh, "%!PS-Adobe-3.0" if title: print >>fh, "%%Title: "+title print >>fh, ("%%Creator: matplotlib version " +__version__+", http://matplotlib.sourceforge.net/") print >>fh, "%%CreationDate: "+time.ctime(time.time()) print >>fh, "%%Orientation: " + orientation if not isEPSF: print >>fh, "%%DocumentPaperSizes: "+papertype print >>fh, "%%%%BoundingBox: %d %d %d %d" % bbox if not isEPSF: print >>fh, "%%Pages: 1" print >>fh, "%%EndComments" Ndict = len(psDefs) print >>fh, "%%BeginProlog" if not rcParams['ps.useafm']: Ndict += len(renderer.used_characters) print >>fh, "/mpldict %d dict def"%Ndict print >>fh, "mpldict begin" for d in psDefs: d=d.strip() for l in d.split('\n'): print >>fh, l.strip() if not rcParams['ps.useafm']: for font_filename, chars in renderer.used_characters.values(): if len(chars): font = FT2Font(font_filename) cmap = font.get_charmap() glyph_ids = [] for c in chars: gind = cmap.get(c) or 0 glyph_ids.append(gind) # The ttf to ps (subsetting) support doesn't work for # OpenType fonts that are Postscript inside (like the # STIX fonts). This will simply turn that off to avoid # errors. if is_opentype_cff_font(font_filename): raise RuntimeError("OpenType CFF fonts can not be saved using the internal Postscript backend at this time.\nConsider using the Cairo backend.") else: fonttype = rcParams['ps.fonttype'] convert_ttf_to_ps(font_filename, fh, rcParams['ps.fonttype'], glyph_ids) print >>fh, "end" print >>fh, "%%EndProlog" if not isEPSF: print >>fh, "%%Page: 1 1" print >>fh, "mpldict begin" #print >>fh, "gsave" print >>fh, "%s translate"%_nums_to_str(xo, yo) if rotation: print >>fh, "%d rotate"%rotation print >>fh, "%s clipbox"%_nums_to_str(width*72, height*72, 0, 0) # write the figure print >>fh, self._pswriter.getvalue() # write the trailer #print >>fh, "grestore" print >>fh, "end" print >>fh, "showpage" if not isEPSF: print >>fh, "%%EOF" fh.close() if rcParams['ps.usedistiller'] == 'ghostscript': gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) if passed_in_file_object: fh = file(tmpfile) print >>outfile, fh.read() else: shutil.move(tmpfile, outfile) def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype): """ If text.usetex is True in rc, a temporary pair of tex/eps files are created to allow tex to manage the text layout via the PSFrags package. These files are processed to yield the final ps or eps file. """ isEPSF = format == 'eps' title = outfile # write to a temp file, we'll move it to outfile when done tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest()) fh = file(tmpfile, 'w') self.figure.dpi = 72 # ignore the dpi kwarg width, height = self.figure.get_size_inches() xo = 0 yo = 0 l, b, w, h = self.figure.bbox.bounds llx = xo lly = yo urx = llx + w ury = lly + h bbox = (llx, lly, urx, ury) # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # write the Encapsulated PostScript headers print >>fh, "%!PS-Adobe-3.0 EPSF-3.0" if title: print >>fh, "%%Title: "+title print >>fh, ("%%Creator: matplotlib version " +__version__+", http://matplotlib.sourceforge.net/") print >>fh, "%%CreationDate: "+time.ctime(time.time()) print >>fh, "%%%%BoundingBox: %d %d %d %d" % bbox print >>fh, "%%EndComments" Ndict = len(psDefs) print >>fh, "%%BeginProlog" print >>fh, "/mpldict %d dict def"%Ndict print >>fh, "mpldict begin" for d in psDefs: d=d.strip() for l in d.split('\n'): print >>fh, l.strip() print >>fh, "end" print >>fh, "%%EndProlog" print >>fh, "mpldict begin" #print >>fh, "gsave" print >>fh, "%s translate"%_nums_to_str(xo, yo) print >>fh, "%s clipbox"%_nums_to_str(width*72, height*72, 0, 0) # write the figure print >>fh, self._pswriter.getvalue() # write the trailer #print >>fh, "grestore" print >>fh, "end" print >>fh, "showpage" fh.close() if isLandscape: # now we are ready to rotate isLandscape = True width, height = height, width bbox = (lly, llx, ury, urx) temp_papertype = _get_papertype(width, height) if papertype=='auto': papertype = temp_papertype paperWidth, paperHeight = papersize[temp_papertype] else: paperWidth, paperHeight = papersize[papertype] if (width>paperWidth or height>paperHeight) and isEPSF: paperWidth, paperHeight = papersize[temp_papertype] verbose.report('Your figure is too big to fit on %s paper. %s \ paper will be used to prevent clipping.'%(papertype, temp_papertype), 'helpful') texmanager = renderer.get_texmanager() font_preamble = texmanager.get_font_preamble() custom_preamble = texmanager.get_custom_preamble() convert_psfrags(tmpfile, renderer.psfrag, font_preamble, custom_preamble, paperWidth, paperHeight, orientation) if rcParams['ps.usedistiller'] == 'ghostscript': gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif rcParams['text.usetex']: if False: pass # for debugging else: gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) if isinstance(outfile, file): fh = file(tmpfile) print >>outfile, fh.read() else: shutil.move(tmpfile, outfile) def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, paperWidth, paperHeight, orientation): """ When we want to use the LaTeX backend with postscript, we write PSFrag tags to a temporary postscript file, each one marking a position for LaTeX to render some text. convert_psfrags generates a LaTeX document containing the commands to convert those tags to text. LaTeX/dvips produces the postscript file that includes the actual text. """ tmpdir = os.path.split(tmpfile)[0] epsfile = tmpfile+'.eps' shutil.move(tmpfile, epsfile) latexfile = tmpfile+'.tex' outfile = tmpfile+'.output' latexh = file(latexfile, 'w') dvifile = tmpfile+'.dvi' psfile = tmpfile+'.ps' if orientation=='landscape': angle = 90 else: angle = 0 if rcParams['text.latex.unicode']: unicode_preamble = """\usepackage{ucs} \usepackage[utf8x]{inputenc}""" else: unicode_preamble = '' s = r"""\documentclass{article} %s %s %s \usepackage[dvips, papersize={%sin,%sin}, body={%sin,%sin}, margin={0in,0in}]{geometry} \usepackage{psfrag} \usepackage[dvips]{graphicx} \usepackage{color} \pagestyle{empty} \begin{document} \begin{figure} \centering \leavevmode %s \includegraphics*[angle=%s]{%s} \end{figure} \end{document} """% (font_preamble, unicode_preamble, custom_preamble, paperWidth, paperHeight, paperWidth, paperHeight, '\n'.join(psfrags), angle, os.path.split(epsfile)[-1]) if rcParams['text.latex.unicode']: latexh.write(s.encode('utf8')) else: try: latexh.write(s) except UnicodeEncodeError, err: verbose.report("You are using unicode and latex, but have " "not enabled the matplotlib 'text.latex.unicode' " "rcParam.", 'helpful') raise latexh.close() # the split drive part of the command is necessary for windows users with # multiple if sys.platform == 'win32': precmd = '%s &&'% os.path.splitdrive(tmpdir)[0] else: precmd = '' command = '%s cd "%s" && latex -interaction=nonstopmode "%s" > "%s"'\ %(precmd, tmpdir, latexfile, outfile) verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError('LaTeX was not able to process your file:\ \nHere is the full report generated by LaTeX: \n\n%s'% fh.read()) else: verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) command = '%s cd "%s" && dvips -q -R0 -o "%s" "%s" > "%s"'%(precmd, tmpdir, os.path.split(psfile)[-1], os.path.split(dvifile)[-1], outfile) verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError('dvips was not able to \ process the following file:\n%s\nHere is the full report generated by dvips: \ \n\n'% dvifile + fh.read()) else: verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) os.remove(epsfile) shutil.move(psfile, tmpfile) if not debugPS: for fname in glob.glob(tmpfile+'.*'): os.remove(fname) def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None): """ Use ghostscript's pswrite or epswrite device to distill a file. This yields smaller files without illegal encapsulated postscript operators. The output is low-level, converting text to outlines. """ paper = '-sPAPERSIZE=%s'% ptype psfile = tmpfile + '.ps' outfile = tmpfile + '.output' dpi = rcParams['ps.distiller.res'] if sys.platform == 'win32': gs_exe = 'gswin32c' else: gs_exe = 'gs' command = '%s -dBATCH -dNOPAUSE -r%d -sDEVICE=pswrite %s -sOutputFile="%s" \ "%s" > "%s"'% (gs_exe, dpi, paper, psfile, tmpfile, outfile) verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError('ghostscript was not able to process \ your image.\nHere is the full report generated by ghostscript:\n\n' + fh.read()) else: verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) os.remove(tmpfile) shutil.move(psfile, tmpfile) if eps: pstoeps(tmpfile, bbox) def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None): """ Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file. This yields smaller files without illegal encapsulated postscript operators. This distiller is preferred, generating high-level postscript output that treats text as text. """ pdffile = tmpfile + '.pdf' psfile = tmpfile + '.ps' outfile = tmpfile + '.output' command = 'ps2pdf -dAutoFilterColorImages=false \ -sColorImageFilter=FlateEncode -sPAPERSIZE=%s "%s" "%s" > "%s"'% \ (ptype, tmpfile, pdffile, outfile) if sys.platform == 'win32': command = command.replace('=', '#') verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError('ps2pdf was not able to process your \ image.\n\Here is the report generated by ghostscript:\n\n' + fh.read()) else: verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) command = 'pdftops -paper match -level2 "%s" "%s" > "%s"'% \ (pdffile, psfile, outfile) verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError('pdftops was not able to process your \ image.\nHere is the full report generated by pdftops: \n\n' + fh.read()) else: verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) os.remove(tmpfile) shutil.move(psfile, tmpfile) if eps: pstoeps(tmpfile, bbox) for fname in glob.glob(tmpfile+'.*'): os.remove(fname) def get_bbox(tmpfile, bbox): """ Use ghostscript's bbox device to find the center of the bounding box. Return an appropriately sized bbox centered around that point. A bit of a hack. """ outfile = tmpfile + '.output' if sys.platform == 'win32': gs_exe = 'gswin32c' else: gs_exe = 'gs' command = '%s -dBATCH -dNOPAUSE -sDEVICE=bbox "%s"' %\ (gs_exe, tmpfile) verbose.report(command, 'debug') stdin, stdout, stderr = os.popen3(command) verbose.report(stdout.read(), 'debug-annoying') bbox_info = stderr.read() verbose.report(bbox_info, 'helpful') bbox_found = re.search('%%HiResBoundingBox: .*', bbox_info) if bbox_found: bbox_info = bbox_found.group() else: raise RuntimeError('Ghostscript was not able to extract a bounding box.\ Here is the Ghostscript output:\n\n%s'% bbox_info) l, b, r, t = [float(i) for i in bbox_info.split()[-4:]] # this is a hack to deal with the fact that ghostscript does not return the # intended bbox, but a tight bbox. For now, we just center the ink in the # intended bbox. This is not ideal, users may intend the ink to not be # centered. if bbox is None: l, b, r, t = (l-1, b-1, r+1, t+1) else: x = (l+r)/2 y = (b+t)/2 dx = (bbox[2]-bbox[0])/2 dy = (bbox[3]-bbox[1])/2 l,b,r,t = (x-dx, y-dy, x+dx, y+dy) bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, npy.ceil(r), npy.ceil(t)) hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (l, b, r, t) return '\n'.join([bbox_info, hires_bbox_info]) def pstoeps(tmpfile, bbox): """ Convert the postscript to encapsulated postscript. """ bbox_info = get_bbox(tmpfile, bbox) epsfile = tmpfile + '.eps' epsh = file(epsfile, 'w') tmph = file(tmpfile) line = tmph.readline() # Modify the header: while line: if line.startswith('%!PS'): print >>epsh, "%!PS-Adobe-3.0 EPSF-3.0" print >>epsh, bbox_info elif line.startswith('%%EndComments'): epsh.write(line) print >>epsh, '%%BeginProlog' print >>epsh, 'save' print >>epsh, 'countdictstack' print >>epsh, 'mark' print >>epsh, 'newpath' print >>epsh, '/showpage {} def' print >>epsh, '/setpagedevice {pop} def' print >>epsh, '%%EndProlog' print >>epsh, '%%Page 1 1' break elif line.startswith('%%Bound') \ or line.startswith('%%HiResBound') \ or line.startswith('%%Pages'): pass else: epsh.write(line) line = tmph.readline() # Now rewrite the rest of the file, and modify the trailer. # This is done in a second loop such that the header of the embedded # eps file is not modified. line = tmph.readline() while line: if line.startswith('%%Trailer'): print >>epsh, '%%Trailer' print >>epsh, 'cleartomark' print >>epsh, 'countdictstack' print >>epsh, 'exch sub { end } repeat' print >>epsh, 'restore' if rcParams['ps.usedistiller'] == 'xpdf': # remove extraneous "end" operator: line = tmph.readline() else: epsh.write(line) line = tmph.readline() tmph.close() epsh.close() os.remove(tmpfile) shutil.move(epsfile, tmpfile) class FigureManagerPS(FigureManagerBase): pass FigureManager = FigureManagerPS # The following Python dictionary psDefs contains the entries for the # PostScript dictionary mpldict. This dictionary implements most of # the matplotlib primitives and some abbreviations. # # References: # http://www.adobe.com/products/postscript/pdfs/PLRM.pdf # http://www.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial/ # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/ # # The usage comments use the notation of the operator summary # in the PostScript Language reference manual. psDefs = [ # x y *m* - "/m { moveto } bind def", # x y *l* - "/l { lineto } bind def", # x y *r* - "/r { rlineto } bind def", # x1 y1 x2 y2 x y *c* - "/c { curveto } bind def", # *closepath* - "/cl { closepath } bind def", # w h x y *box* - """/box { m 1 index 0 r 0 exch r neg 0 r cl } bind def""", # w h x y *clipbox* - """/clipbox { box clip newpath } bind def""", ]
50,262
Python
.py
1,260
30.537302
168
0.573844
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,315
backend_mixed.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_mixed.py
from matplotlib._image import frombuffer from matplotlib.backends.backend_agg import RendererAgg class MixedModeRenderer(object): """ A helper class to implement a renderer that switches between vector and raster drawing. An example may be a PDF writer, where most things are drawn with PDF vector commands, but some very complex objects, such as quad meshes, are rasterised and then output as images. """ def __init__(self, width, height, dpi, vector_renderer, raster_renderer_class=None): """ width: The width of the canvas in logical units height: The height of the canvas in logical units dpi: The dpi of the canvas vector_renderer: An instance of a subclass of RendererBase that will be used for the vector drawing. raster_renderer_class: The renderer class to use for the raster drawing. If not provided, this will use the Agg backend (which is currently the only viable option anyway.) """ if raster_renderer_class is None: raster_renderer_class = RendererAgg self._raster_renderer_class = raster_renderer_class self._width = width self._height = height self.dpi = dpi assert not vector_renderer.option_image_nocomposite() self._vector_renderer = vector_renderer self._raster_renderer = None self._rasterizing = 0 self._set_current_renderer(vector_renderer) _methods = """ close_group draw_image draw_markers draw_path draw_path_collection draw_quad_mesh draw_tex draw_text finalize flipy get_canvas_width_height get_image_magnification get_texmanager get_text_width_height_descent new_gc open_group option_image_nocomposite points_to_pixels strip_math """.split() def _set_current_renderer(self, renderer): self._renderer = renderer for method in self._methods: if hasattr(renderer, method): setattr(self, method, getattr(renderer, method)) renderer.start_rasterizing = self.start_rasterizing renderer.stop_rasterizing = self.stop_rasterizing def start_rasterizing(self): """ Enter "raster" mode. All subsequent drawing commands (until stop_rasterizing is called) will be drawn with the raster backend. If start_rasterizing is called multiple times before stop_rasterizing is called, this method has no effect. """ if self._rasterizing == 0: self._raster_renderer = self._raster_renderer_class( self._width*self.dpi, self._height*self.dpi, self.dpi) self._set_current_renderer(self._raster_renderer) self._rasterizing += 1 def stop_rasterizing(self): """ Exit "raster" mode. All of the drawing that was done since the last start_rasterizing command will be copied to the vector backend by calling draw_image. If stop_rasterizing is called multiple times before start_rasterizing is called, this method has no effect. """ self._rasterizing -= 1 if self._rasterizing == 0: self._set_current_renderer(self._vector_renderer) width, height = self._width * self.dpi, self._height * self.dpi buffer, bounds = self._raster_renderer.tostring_rgba_minimized() l, b, w, h = bounds if w > 0 and h > 0: image = frombuffer(buffer, w, h, True) image.is_grayscale = False image.flipud_out() self._renderer.draw_image(l, height - b - h, image, None) self._raster_renderer = None self._rasterizing = False
3,776
Python
.py
80
37.75
88
0.651902
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,316
backend_emf.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_emf.py
""" Enhanced Metafile backend. See http://pyemf.sourceforge.net for the EMF driver library. """ from __future__ import division try: import pyemf except ImportError: raise ImportError('You must first install pyemf from http://pyemf.sf.net') import os,sys,math,re from matplotlib import verbose, __version__, rcParams from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.figure import Figure from matplotlib.transforms import Bbox from matplotlib.font_manager import findfont, FontProperties from matplotlib.ft2font import FT2Font, KERNING_UNFITTED, KERNING_DEFAULT, KERNING_UNSCALED # Font handling stuff snarfed from backend_ps, but only using TTF fonts _fontd = {} # Debug print stuff debugHandle = False debugPrint = False debugText = False # Hashable font properties class. In EMF, angle of rotation is a part # of the font properties, so a handle to a new font must be obtained # if the rotation changes. class EMFFontProperties(FontProperties): def __init__(self,other,angle): FontProperties.__init__(self,other.get_family(), other.get_style(), other.get_variant(), other.get_weight(), other.get_stretch(), other.get_size()) self.__angle=angle def __hash__(self): return hash( (FontProperties.__hash__(self), self.__angle)) def __str__(self): return str( (FontProperties.__str__(self), self.__angle)) def set_angle(self,angle): self.__angle=angle # Hashable pen (line style) properties. class EMFPen: def __init__(self,emf,gc): self.emf=emf self.gc=gc r,g,b=gc.get_rgb() self.r=int(r*255) self.g=int(g*255) self.b=int(b*255) self.width=int(gc.get_linewidth()) self.style=0 self.set_linestyle() if debugHandle: print "EMFPen: style=%d width=%d rgb=(%d,%d,%d)" % (self.style,self.width,self.r,self.g,self.b) def __hash__(self): return hash((self.style,self.width,self.r,self.g,self.b)) def set_linestyle(self): # Hack. Negative width lines will not get drawn. if self.width<0: self.style=pyemf.PS_NULL else: styles={'solid':pyemf.PS_SOLID, 'dashed':pyemf.PS_DASH, 'dashdot':pyemf.PS_DASHDOT, 'dotted':pyemf.PS_DOT} #style=styles.get(self.gc.get_linestyle('solid')) style=self.gc.get_linestyle('solid') if debugHandle: print "EMFPen: style=%d" % style if style in styles: self.style=styles[style] else: self.style=pyemf.PS_SOLID def get_handle(self): handle=self.emf.CreatePen(self.style,self.width,(self.r,self.g,self.b)) return handle # Hashable brush (fill style) properties. class EMFBrush: def __init__(self,emf,rgb): self.emf=emf r,g,b=rgb self.r=int(r*255) self.g=int(g*255) self.b=int(b*255) if debugHandle: print "EMFBrush: rgb=(%d,%d,%d)" % (self.r,self.g,self.b) def __hash__(self): return hash((self.r,self.g,self.b)) def get_handle(self): handle=self.emf.CreateSolidBrush((self.r,self.g,self.b)) return handle class RendererEMF(RendererBase): """ The renderer handles drawing/rendering operations through a pyemf.EMF instance. """ def __init__(self, outfile, width, height, dpi): "Initialize the renderer with a gd image instance" self.outfile = outfile # a map from get_color args to colors self._cached = {} # dict of hashed properties to already created font handles self._fontHandle = {} self.lastHandle = {'font':-1, 'pen':-1, 'brush':-1} self.emf=pyemf.EMF(width,height,dpi,'in') self.width=int(width*dpi) self.height=int(height*dpi) self.dpi = dpi self.pointstodpi = dpi/72.0 self.hackPointsForMathExponent = 2.0 # set background transparent for text self.emf.SetBkMode(pyemf.TRANSPARENT) # set baseline for text to be bottom left corner self.emf.SetTextAlign( pyemf.TA_BOTTOM|pyemf.TA_LEFT) if debugPrint: print "RendererEMF: (%f,%f) %s dpi=%f" % (self.width,self.height,outfile,dpi) def save(self): self.emf.save(self.outfile) def draw_arc(self, gcEdge, rgbFace, x, y, width, height, angle1, angle2, rotation): """ Draw an arc using GraphicsContext instance gcEdge, centered at x,y, with width and height and angles from 0.0 to 360.0 0 degrees is at 3-o'clock positive angles are anti-clockwise If the color rgbFace is not None, fill the arc with it. """ if debugPrint: print "draw_arc: (%f,%f) angles=(%f,%f) w,h=(%f,%f)" % (x,y,angle1,angle2,width,height) pen=self.select_pen(gcEdge) brush=self.select_brush(rgbFace) # This algorithm doesn't work very well on small circles # because of rounding error. This shows up most obviously on # legends where the circles are small anyway, and it is # compounded by the fact that it puts several circles right # next to each other so the differences are obvious. hw=width/2 hh=height/2 x1=int(x-width/2) y1=int(y-height/2) if brush: self.emf.Pie(int(x-hw),int(self.height-(y-hh)),int(x+hw),int(self.height-(y+hh)),int(x+math.cos(angle1*math.pi/180.0)*hw),int(self.height-(y+math.sin(angle1*math.pi/180.0)*hh)),int(x+math.cos(angle2*math.pi/180.0)*hw),int(self.height-(y+math.sin(angle2*math.pi/180.0)*hh))) else: self.emf.Arc(int(x-hw),int(self.height-(y-hh)),int(x+hw),int(self.height-(y+hh)),int(x+math.cos(angle1*math.pi/180.0)*hw),int(self.height-(y+math.sin(angle1*math.pi/180.0)*hh)),int(x+math.cos(angle2*math.pi/180.0)*hw),int(self.height-(y+math.sin(angle2*math.pi/180.0)*hh))) def draw_image(self, x, y, im, bbox): """ Draw the Image instance into the current axes; x is the distance in pixels from the left hand side of the canvas. y is the distance from the origin. That is, if origin is upper, y is the distance from top. If origin is lower, y is the distance from bottom bbox is a matplotlib.transforms.BBox instance for clipping, or None """ # pyemf2 currently doesn't support bitmaps. pass def draw_line(self, gc, x1, y1, x2, y2): """ Draw a single line from x1,y1 to x2,y2 """ if debugPrint: print "draw_line: (%f,%f) - (%f,%f)" % (x1,y1,x2,y2) if self.select_pen(gc): self.emf.Polyline([(long(x1),long(self.height-y1)),(long(x2),long(self.height-y2))]) else: if debugPrint: print "draw_line: optimizing away (%f,%f) - (%f,%f)" % (x1,y1,x2,y2) def draw_lines(self, gc, x, y): """ x and y are equal length arrays, draw lines connecting each point in x, y """ if debugPrint: print "draw_lines: %d points" % len(str(x)) # optimize away anything that won't actually be drawn. Edge # style must not be PS_NULL for it to appear on screen. if self.select_pen(gc): points = [(long(x[i]), long(self.height-y[i])) for i in range(len(x))] self.emf.Polyline(points) def draw_point(self, gc, x, y): """ Draw a single point at x,y Where 'point' is a device-unit point (or pixel), not a matplotlib point """ if debugPrint: print "draw_point: (%f,%f)" % (x,y) # don't cache this pen pen=EMFPen(self.emf,gc) self.emf.SetPixel(long(x),long(self.height-y),(pen.r,pen.g,pen.b)) def draw_polygon(self, gcEdge, rgbFace, points): """ Draw a polygon using the GraphicsContext instance gc. points is a len vertices tuple, each element giving the x,y coords a vertex If the color rgbFace is not None, fill the polygon with it """ if debugPrint: print "draw_polygon: %d points" % len(points) # optimize away anything that won't actually draw. Either a # face color or edge style must be defined pen=self.select_pen(gcEdge) brush=self.select_brush(rgbFace) if pen or brush: points = [(long(x), long(self.height-y)) for x,y in points] self.emf.Polygon(points) else: points = [(long(x), long(self.height-y)) for x,y in points] if debugPrint: print "draw_polygon: optimizing away polygon: %d points = %s" % (len(points),str(points)) def draw_rectangle(self, gcEdge, rgbFace, x, y, width, height): """ Draw a non-filled rectangle using the GraphicsContext instance gcEdge, with lower left at x,y with width and height. If rgbFace is not None, fill the rectangle with it. """ if debugPrint: print "draw_rectangle: (%f,%f) w=%f,h=%f" % (x,y,width,height) # optimize away anything that won't actually draw. Either a # face color or edge style must be defined pen=self.select_pen(gcEdge) brush=self.select_brush(rgbFace) if pen or brush: self.emf.Rectangle(int(x),int(self.height-y),int(x)+int(width),int(self.height-y)-int(height)) else: if debugPrint: print "draw_rectangle: optimizing away (%f,%f) w=%f,h=%f" % (x,y,width,height) def draw_text(self, gc, x, y, s, prop, angle, ismath=False): """ Draw the text.Text instance s at x,y (display coords) with font properties instance prop at angle in degrees, using GraphicsContext gc **backend implementers note** When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be blotted along with your text. """ if debugText: print "draw_text: (%f,%f) %d degrees: '%s'" % (x,y,angle,s) if ismath: self.draw_math_text(gc,x,y,s,prop,angle) else: self.draw_plain_text(gc,x,y,s,prop,angle) def draw_plain_text(self, gc, x, y, s, prop, angle): """ Draw a text string verbatim; no conversion is done. """ if debugText: print "draw_plain_text: (%f,%f) %d degrees: '%s'" % (x,y,angle,s) if debugText: print " properties:\n"+str(prop) self.select_font(prop,angle) # haxor follows! The subtleties of text placement in EMF # still elude me a bit. It always seems to be too high on the # page, about 10 pixels too high on a 300dpi resolution image. # So, I'm adding this hack for the moment: hackoffsetper300dpi=10 xhack=math.sin(angle*math.pi/180.0)*hackoffsetper300dpi*self.dpi/300.0 yhack=math.cos(angle*math.pi/180.0)*hackoffsetper300dpi*self.dpi/300.0 self.emf.TextOut(long(x+xhack),long(y+yhack),s) def draw_math_text(self, gc, x, y, s, prop, angle): """ Draw a subset of TeX, currently handles exponents only. Since pyemf doesn't have any raster functionality yet, the texmanager.get_rgba won't help. """ if debugText: print "draw_math_text: (%f,%f) %d degrees: '%s'" % (x,y,angle,s) s = s[1:-1] # strip the $ from front and back match=re.match("10\^\{(.+)\}",s) if match: exp=match.group(1) if debugText: print " exponent=%s" % exp font = self._get_font_ttf(prop) font.set_text("10", 0.0) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 self.draw_plain_text(gc,x,y,"10",prop,angle) propexp=prop.copy() propexp.set_size(prop.get_size_in_points()*.8) self.draw_plain_text(gc,x+w+self.points_to_pixels(self.hackPointsForMathExponent),y-(h/2),exp,propexp,angle) else: # if it isn't an exponent, then render the raw TeX string. self.draw_plain_text(gc,x,y,s,prop,angle) def get_math_text_width_height(self, s, prop): """ get the width and height in display coords of the string s with FontPropertry prop, ripped right out of backend_ps. This method must be kept in sync with draw_math_text. """ if debugText: print "get_math_text_width_height:" s = s[1:-1] # strip the $ from front and back match=re.match("10\^\{(.+)\}",s) if match: exp=match.group(1) if debugText: print " exponent=%s" % exp font = self._get_font_ttf(prop) font.set_text("10", 0.0) w1, h1 = font.get_width_height() propexp=prop.copy() propexp.set_size(prop.get_size_in_points()*.8) fontexp=self._get_font_ttf(propexp) fontexp.set_text(exp, 0.0) w2, h2 = fontexp.get_width_height() w=w1+w2 h=h1+(h2/2) w /= 64.0 # convert from subpixels h /= 64.0 w+=self.points_to_pixels(self.hackPointsForMathExponent) if debugText: print " math string=%s w,h=(%f,%f)" % (s, w, h) else: w,h=self.get_text_width_height(s,prop,False) return w, h def flipy(self): """return true if y small numbers are top for renderer Is used for drawing text (text.py) and images (image.py) only """ return True def get_canvas_width_height(self): """ return the canvas width and height in display coords """ return self.width,self.height def set_handle(self,type,handle): """ Update the EMF file with the current handle, but only if it isn't the same as the last one. Don't want to flood the file with duplicate info. """ if self.lastHandle[type] != handle: self.emf.SelectObject(handle) self.lastHandle[type]=handle def get_font_handle(self, prop, angle): """ Look up the handle for the font based on the dict of properties *and* the rotation angle, since in EMF the font rotation is a part of the font definition. """ prop=EMFFontProperties(prop,angle) size=int(prop.get_size_in_points()*self.pointstodpi) face=prop.get_name() key = hash(prop) handle = self._fontHandle.get(key) if handle is None: handle=self.emf.CreateFont(-size, 0, int(angle)*10, int(angle)*10, pyemf.FW_NORMAL, 0, 0, 0, pyemf.ANSI_CHARSET, pyemf.OUT_DEFAULT_PRECIS, pyemf.CLIP_DEFAULT_PRECIS, pyemf.DEFAULT_QUALITY, pyemf.DEFAULT_PITCH | pyemf.FF_DONTCARE, face); if debugHandle: print "get_font_handle: creating handle=%d for face=%s size=%d" % (handle,face,size) self._fontHandle[key]=handle if debugHandle: print " found font handle %d for face=%s size=%d" % (handle,face,size) self.set_handle("font",handle) return handle def select_font(self,prop,angle): handle=self.get_font_handle(prop,angle) self.set_handle("font",handle) def select_pen(self, gc): """ Select a pen that includes the color, line width and line style. Return the pen if it will draw a line, or None if the pen won't produce any output (i.e. the style is PS_NULL) """ pen=EMFPen(self.emf,gc) key=hash(pen) handle=self._fontHandle.get(key) if handle is None: handle=pen.get_handle() self._fontHandle[key]=handle if debugHandle: print " found pen handle %d" % handle self.set_handle("pen",handle) if pen.style != pyemf.PS_NULL: return pen else: return None def select_brush(self, rgb): """ Select a fill color, and return the brush if the color is valid or None if this won't produce a fill operation. """ if rgb is not None: brush=EMFBrush(self.emf,rgb) key=hash(brush) handle=self._fontHandle.get(key) if handle is None: handle=brush.get_handle() self._fontHandle[key]=handle if debugHandle: print " found brush handle %d" % handle self.set_handle("brush",handle) return brush else: return None def _get_font_ttf(self, prop): """ get the true type font properties, used because EMFs on windows will use true type fonts. """ key = hash(prop) font = _fontd.get(key) if font is None: fname = findfont(prop) if debugText: print "_get_font_ttf: name=%s" % fname font = FT2Font(str(fname)) _fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font def get_text_width_height(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop, ripped right out of backend_ps """ if debugText: print "get_text_width_height: ismath=%s properties: %s" % (str(ismath),str(prop)) if ismath: if debugText: print " MATH TEXT! = %s" % str(ismath) w,h = self.get_math_text_width_height(s, prop) return w,h font = self._get_font_ttf(prop) font.set_text(s, 0.0) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 if debugText: print " text string=%s w,h=(%f,%f)" % (s, w, h) return w, h def new_gc(self): return GraphicsContextEMF() def points_to_pixels(self, points): # if backend doesn't have dpi, eg, postscript or svg #return points # elif backend assumes a value for pixels_per_inch #return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 # else return points/72.0 * self.dpi class GraphicsContextEMF(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... See the gtk and postscript backends for examples of mapping the graphics context attributes (cap styles, join styles, line widths, colors) to a particular backend. In GTK this is done by wrapping a gtk.gdk.GC object and forwarding the appropriate calls to it using a dictionary mapping styles to gdk constants. In Postscript, all the work is done by the renderer, mapping line styles to postscript calls. If it's more appropriate to do the mapping at the renderer level (as in the postscript backend), you don't need to override any of the GC methods. If it's more appropriate to wrap an instance (as in the GTK backend) and do the mapping here, you'll need to override several of the setter methods. The base GraphicsContext stores colors as a RGB tuple on the unit interval, eg, (0.5, 0.0, 1.0). You may need to map this to colors appropriate for your backend. """ pass ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def draw_if_interactive(): """ For image backends - is not required For GUI backends - this should be overriden if drawing should be done in interactive python mode """ pass def show(): """ For image backends - is not required For GUI backends - show() is usually the last line of a pylab script and tells the backend that it is time to draw. In interactive mode, this may be a do nothing func. See the GTK backend for an example of how to handle interactive versus batch mode """ for manager in Gcf.get_all_fig_managers(): # do something to display the GUI pass def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # if a main-level app must be created, this is the usual place to # do it -- see backend_wx, backend_wxagg and backend_tkagg for # examples. Not all GUIs require explicit instantiation of a # main-level app (egg backend_gtk, backend_gtkagg) for pylab FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasEMF(thisFig) manager = FigureManagerEMF(canvas, num) return manager class FigureCanvasEMF(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def draw(self): """ Draw the figure using the renderer """ pass filetypes = {'emf': 'Enhanced Metafile'} def print_emf(self, filename, dpi=300, **kwargs): width, height = self.figure.get_size_inches() renderer = RendererEMF(filename,width,height,dpi) self.figure.draw(renderer) renderer.save() def get_default_filetype(self): return 'emf' class FigureManagerEMF(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ pass ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## FigureManager = FigureManagerEMF
22,336
Python
.py
506
35.379447
285
0.610825
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,317
backend_svg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_svg.py
from __future__ import division import os, codecs, base64, tempfile, urllib, gzip, cStringIO try: from hashlib import md5 except ImportError: from md5 import md5 #Deprecated in 2.5 from matplotlib import verbose, __version__, rcParams from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.cbook import is_string_like, is_writable_file_like, maxdict from matplotlib.colors import rgb2hex from matplotlib.figure import Figure from matplotlib.font_manager import findfont, FontProperties from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, LOAD_NO_HINTING from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Affine2D from matplotlib import _png from xml.sax.saxutils import escape as escape_xml_text backend_version = __version__ def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasSVG(thisFig) manager = FigureManagerSVG(canvas, num) return manager _capstyle_d = {'projecting' : 'square', 'butt' : 'butt', 'round': 'round',} class RendererSVG(RendererBase): FONT_SCALE = 100.0 fontd = maxdict(50) def __init__(self, width, height, svgwriter, basename=None): self.width=width self.height=height self._svgwriter = svgwriter if rcParams['path.simplify']: self.simplify = (width, height) else: self.simplify = None self._groupd = {} if not rcParams['svg.image_inline']: assert basename is not None self.basename = basename self._imaged = {} self._clipd = {} self._char_defs = {} self._markers = {} self._path_collection_id = 0 self._imaged = {} self.mathtext_parser = MathTextParser('SVG') svgwriter.write(svgProlog%(width,height,width,height)) def _draw_svg_element(self, element, details, gc, rgbFace): clipid = self._get_gc_clip_svg(gc) if clipid is None: clippath = '' else: clippath = 'clip-path="url(#%s)"' % clipid if gc.get_url() is not None: self._svgwriter.write('<a xlink:href="%s">' % gc.get_url()) style = self._get_style(gc, rgbFace) self._svgwriter.write ('<%s style="%s" %s %s/>\n' % ( element, style, clippath, details)) if gc.get_url() is not None: self._svgwriter.write('</a>') def _get_font(self, prop): key = hash(prop) font = self.fontd.get(key) if font is None: fname = findfont(prop) font = self.fontd.get(fname) if font is None: font = FT2Font(str(fname)) self.fontd[fname] = font self.fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, 72.0) return font def _get_style(self, gc, rgbFace): """ return the style string. style is generated from the GraphicsContext, rgbFace and clippath """ if rgbFace is None: fill = 'none' else: fill = rgb2hex(rgbFace[:3]) offset, seq = gc.get_dashes() if seq is None: dashes = '' else: dashes = 'stroke-dasharray: %s; stroke-dashoffset: %f;' % ( ','.join(['%f'%val for val in seq]), offset) linewidth = gc.get_linewidth() if linewidth: return 'fill: %s; stroke: %s; stroke-width: %f; ' \ 'stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f' % ( fill, rgb2hex(gc.get_rgb()[:3]), linewidth, gc.get_joinstyle(), _capstyle_d[gc.get_capstyle()], dashes, gc.get_alpha(), ) else: return 'fill: %s; opacity: %f' % (\ fill, gc.get_alpha(), ) def _get_gc_clip_svg(self, gc): cliprect = gc.get_clip_rectangle() clippath, clippath_trans = gc.get_clip_path() if clippath is not None: path_data = self._convert_path(clippath, clippath_trans) path = '<path d="%s"/>' % path_data elif cliprect is not None: x, y, w, h = cliprect.bounds y = self.height-(y+h) path = '<rect x="%(x)f" y="%(y)f" width="%(w)f" height="%(h)f"/>' % locals() else: return None id = self._clipd.get(path) if id is None: id = 'p%s' % md5(path).hexdigest() self._svgwriter.write('<defs>\n <clipPath id="%s">\n' % id) self._svgwriter.write(path) self._svgwriter.write('\n </clipPath>\n</defs>') self._clipd[path] = id return id def open_group(self, s): self._groupd[s] = self._groupd.get(s,0) + 1 self._svgwriter.write('<g id="%s%d">\n' % (s, self._groupd[s])) def close_group(self, s): self._svgwriter.write('</g>\n') def option_image_nocomposite(self): """ if svg.image_noscale is True, compositing multiple images into one is prohibited """ return rcParams['svg.image_noscale'] _path_commands = { Path.MOVETO: 'M%f %f', Path.LINETO: 'L%f %f', Path.CURVE3: 'Q%f %f %f %f', Path.CURVE4: 'C%f %f %f %f %f %f' } def _make_flip_transform(self, transform): return (transform + Affine2D() .scale(1.0, -1.0) .translate(0.0, self.height)) def _convert_path(self, path, transform, simplify=None): tpath = transform.transform_path(path) path_data = [] appender = path_data.append path_commands = self._path_commands currpos = 0 for points, code in tpath.iter_segments(simplify): if code == Path.CLOSEPOLY: segment = 'z' else: segment = path_commands[code] % tuple(points) if currpos + len(segment) > 75: appender("\n") currpos = 0 appender(segment) currpos += len(segment) return ''.join(path_data) def draw_path(self, gc, path, transform, rgbFace=None): trans_and_flip = self._make_flip_transform(transform) path_data = self._convert_path(path, trans_and_flip, self.simplify) self._draw_svg_element('path', 'd="%s"' % path_data, gc, rgbFace) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): write = self._svgwriter.write key = self._convert_path(marker_path, marker_trans + Affine2D().scale(1.0, -1.0)) name = self._markers.get(key) if name is None: name = 'm%s' % md5(key).hexdigest() write('<defs><path id="%s" d="%s"/></defs>\n' % (name, key)) self._markers[key] = name clipid = self._get_gc_clip_svg(gc) if clipid is None: clippath = '' else: clippath = 'clip-path="url(#%s)"' % clipid write('<g %s>' % clippath) trans_and_flip = self._make_flip_transform(trans) tpath = trans_and_flip.transform_path(path) for vertices, code in tpath.iter_segments(): if len(vertices): x, y = vertices[-2:] details = 'xlink:href="#%s" x="%f" y="%f"' % (name, x, y) style = self._get_style(gc, rgbFace) self._svgwriter.write ('<use style="%s" %s/>\n' % (style, details)) write('</g>') def draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): write = self._svgwriter.write path_codes = [] write('<defs>\n') for i, (path, transform) in enumerate(self._iter_collection_raw_paths( master_transform, paths, all_transforms)): transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0) d = self._convert_path(path, transform) name = 'coll%x_%x_%s' % (self._path_collection_id, i, md5(d).hexdigest()) write('<path id="%s" d="%s"/>\n' % (name, d)) path_codes.append(name) write('</defs>\n') for xo, yo, path_id, gc, rgbFace in self._iter_collection( path_codes, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): clipid = self._get_gc_clip_svg(gc) url = gc.get_url() if url is not None: self._svgwriter.write('<a xlink:href="%s">' % url) if clipid is not None: write('<g clip-path="url(#%s)">' % clipid) details = 'xlink:href="#%s" x="%f" y="%f"' % (path_id, xo, self.height - yo) style = self._get_style(gc, rgbFace) self._svgwriter.write ('<use style="%s" %s/>\n' % (style, details)) if clipid is not None: write('</g>') if url is not None: self._svgwriter.write('</a>') self._path_collection_id += 1 def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # MGDTODO: Support clippath here trans = [1,0,0,1,0,0] transstr = '' if rcParams['svg.image_noscale']: trans = list(im.get_matrix()) trans[5] = -trans[5] transstr = 'transform="matrix(%f %f %f %f %f %f)" '%tuple(trans) assert trans[1] == 0 assert trans[2] == 0 numrows,numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h,w = im.get_size_out() url = getattr(im, '_url', None) if url is not None: self._svgwriter.write('<a xlink:href="%s">' % url) self._svgwriter.write ( '<image x="%f" y="%f" width="%f" height="%f" ' '%s xlink:href="'%(x/trans[0], (self.height-y)/trans[3]-h, w, h, transstr) ) if rcParams['svg.image_inline']: self._svgwriter.write("data:image/png;base64,\n") stringio = cStringIO.StringIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, stringio) im.flipud_out() self._svgwriter.write(base64.encodestring(stringio.getvalue())) else: self._imaged[self.basename] = self._imaged.get(self.basename,0) + 1 filename = '%s.image%d.png'%(self.basename, self._imaged[self.basename]) verbose.report( 'Writing image file for inclusion: %s' % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) self._svgwriter.write('"/>\n') if url is not None: self._svgwriter.write('</a>') def draw_text(self, gc, x, y, s, prop, angle, ismath): if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) return font = self._get_font(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) y -= font.get_descent() / 64.0 fontsize = prop.get_size_in_points() color = rgb2hex(gc.get_rgb()[:3]) write = self._svgwriter.write if rcParams['svg.embed_char_paths']: new_chars = [] for c in s: path = self._add_char_def(prop, c) if path is not None: new_chars.append(path) if len(new_chars): write('<defs>\n') for path in new_chars: write(path) write('</defs>\n') svg = [] clipid = self._get_gc_clip_svg(gc) if clipid is not None: svg.append('<g clip-path="url(#%s)">\n' % clipid) svg.append('<g style="fill: %s; opacity: %f" transform="' % (color, gc.get_alpha())) if angle != 0: svg.append('translate(%f,%f)rotate(%1.1f)' % (x,y,-angle)) elif x != 0 or y != 0: svg.append('translate(%f,%f)' % (x, y)) svg.append('scale(%f)">\n' % (fontsize / self.FONT_SCALE)) cmap = font.get_charmap() lastgind = None currx = 0 for c in s: charnum = self._get_char_def_id(prop, c) ccode = ord(c) gind = cmap.get(ccode) if gind is None: ccode = ord('?') gind = 0 glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if lastgind is not None: kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT) else: kern = 0 currx += (kern / 64.0) / (self.FONT_SCALE / fontsize) svg.append('<use xlink:href="#%s"' % charnum) if currx != 0: svg.append(' x="%f"' % (currx * (self.FONT_SCALE / fontsize))) svg.append('/>\n') currx += (glyph.linearHoriAdvance / 65536.0) / (self.FONT_SCALE / fontsize) lastgind = gind svg.append('</g>\n') if clipid is not None: svg.append('</g>\n') svg = ''.join(svg) else: thetext = escape_xml_text(s) fontfamily = font.family_name fontstyle = prop.get_style() style = ('font-size: %f; font-family: %s; font-style: %s; fill: %s; opacity: %f' % (fontsize, fontfamily,fontstyle, color, gc.get_alpha())) if angle!=0: transform = 'transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"' % (x,y,-angle,-x,-y) # Inkscape doesn't support rotate(angle x y) else: transform = '' svg = """\ <text style="%(style)s" x="%(x)f" y="%(y)f" %(transform)s>%(thetext)s</text> """ % locals() write(svg) def _add_char_def(self, prop, char): if isinstance(prop, FontProperties): newprop = prop.copy() font = self._get_font(newprop) else: font = prop font.set_size(self.FONT_SCALE, 72) ps_name = font.get_sfnt()[(1,0,0,6)] char_id = urllib.quote('%s-%d' % (ps_name, ord(char))) char_num = self._char_defs.get(char_id, None) if char_num is not None: return None path_data = [] glyph = font.load_char(ord(char), flags=LOAD_NO_HINTING) currx, curry = 0.0, 0.0 for step in glyph.path: if step[0] == 0: # MOVE_TO path_data.append("M%f %f" % (step[1], -step[2])) elif step[0] == 1: # LINE_TO path_data.append("l%f %f" % (step[1] - currx, -step[2] - curry)) elif step[0] == 2: # CURVE3 path_data.append("q%f %f %f %f" % (step[1] - currx, -step[2] - curry, step[3] - currx, -step[4] - curry)) elif step[0] == 3: # CURVE4 path_data.append("c%f %f %f %f %f %f" % (step[1] - currx, -step[2] - curry, step[3] - currx, -step[4] - curry, step[5] - currx, -step[6] - curry)) elif step[0] == 4: # ENDPOLY path_data.append("z") currx, curry = 0.0, 0.0 if step[0] != 4: currx, curry = step[-2], -step[-1] path_data = ''.join(path_data) char_num = 'c_%s' % md5(path_data).hexdigest() path_element = '<path id="%s" d="%s"/>\n' % (char_num, ''.join(path_data)) self._char_defs[char_id] = char_num return path_element def _get_char_def_id(self, prop, char): if isinstance(prop, FontProperties): newprop = prop.copy() font = self._get_font(newprop) else: font = prop font.set_size(self.FONT_SCALE, 72) ps_name = font.get_sfnt()[(1,0,0,6)] char_id = urllib.quote('%s-%d' % (ps_name, ord(char))) return self._char_defs[char_id] def _draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw math text using matplotlib.mathtext """ width, height, descent, svg_elements, used_characters = \ self.mathtext_parser.parse(s, 72, prop) svg_glyphs = svg_elements.svg_glyphs svg_rects = svg_elements.svg_rects color = rgb2hex(gc.get_rgb()[:3]) write = self._svgwriter.write style = "fill: %s" % color if rcParams['svg.embed_char_paths']: new_chars = [] for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs: path = self._add_char_def(font, thetext) if path is not None: new_chars.append(path) if len(new_chars): write('<defs>\n') for path in new_chars: write(path) write('</defs>\n') svg = ['<g style="%s" transform="' % style] if angle != 0: svg.append('translate(%f,%f)rotate(%1.1f)' % (x,y,-angle) ) else: svg.append('translate(%f,%f)' % (x, y)) svg.append('">\n') for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs: charid = self._get_char_def_id(font, thetext) svg.append('<use xlink:href="#%s" transform="translate(%f,%f)scale(%f)"/>\n' % (charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE)) svg.append('</g>\n') else: # not rcParams['svg.embed_char_paths'] svg = ['<text style="%s" x="%f" y="%f"' % (style, x, y)] if angle != 0: svg.append(' transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"' % (x,y,-angle,-x,-y) ) # Inkscape doesn't support rotate(angle x y) svg.append('>\n') curr_x,curr_y = 0.0,0.0 for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs: new_y = - new_y_mtc style = "font-size: %f; font-family: %s" % (fontsize, font.family_name) svg.append('<tspan style="%s"' % style) xadvance = metrics.advance svg.append(' textLength="%f"' % xadvance) dx = new_x - curr_x if dx != 0.0: svg.append(' dx="%f"' % dx) dy = new_y - curr_y if dy != 0.0: svg.append(' dy="%f"' % dy) thetext = escape_xml_text(thetext) svg.append('>%s</tspan>\n' % thetext) curr_x = new_x + xadvance curr_y = new_y svg.append('</text>\n') if len(svg_rects): style = "fill: %s; stroke: none" % color svg.append('<g style="%s" transform="' % style) if angle != 0: svg.append('translate(%f,%f) rotate(%1.1f)' % (x,y,-angle) ) else: svg.append('translate(%f,%f)' % (x, y)) svg.append('">\n') for x, y, width, height in svg_rects: svg.append('<rect x="%f" y="%f" width="%f" height="%f" fill="black" stroke="none" />' % (x, -y + height, width, height)) svg.append("</g>") self.open_group("mathtext") write (''.join(svg)) self.close_group("mathtext") def finalize(self): write = self._svgwriter.write write('</svg>\n') def flipy(self): return True def get_canvas_width_height(self): return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): if ismath: width, height, descent, trash, used_characters = \ self.mathtext_parser.parse(s, 72, prop) return width, height, descent font = self._get_font(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 d = font.get_descent() d /= 64.0 return w, h, d class FigureCanvasSVG(FigureCanvasBase): filetypes = {'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics'} def print_svg(self, filename, *args, **kwargs): if is_string_like(filename): fh_to_close = svgwriter = codecs.open(filename, 'w', 'utf-8') elif is_writable_file_like(filename): svgwriter = codecs.EncodedFile(filename, 'utf-8') fh_to_close = None else: raise ValueError("filename must be a path or a file-like object") return self._print_svg(filename, svgwriter, fh_to_close) def print_svgz(self, filename, *args, **kwargs): if is_string_like(filename): gzipwriter = gzip.GzipFile(filename, 'w') fh_to_close = svgwriter = codecs.EncodedFile(gzipwriter, 'utf-8') elif is_writable_file_like(filename): fh_to_close = gzipwriter = gzip.GzipFile(fileobj=filename, mode='w') svgwriter = codecs.EncodedFile(gzipwriter, 'utf-8') else: raise ValueError("filename must be a path or a file-like object") return self._print_svg(filename, svgwriter, fh_to_close) def _print_svg(self, filename, svgwriter, fh_to_close=None): self.figure.set_dpi(72.0) width, height = self.figure.get_size_inches() w, h = width*72, height*72 if rcParams['svg.image_noscale']: renderer = RendererSVG(w, h, svgwriter, filename) else: renderer = MixedModeRenderer( width, height, 72.0, RendererSVG(w, h, svgwriter, filename)) self.figure.draw(renderer) renderer.finalize() if fh_to_close is not None: svgwriter.close() def get_default_filetype(self): return 'svg' class FigureManagerSVG(FigureManagerBase): pass FigureManager = FigureManagerSVG svgProlog = """\ <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <!-- Created with matplotlib (http://matplotlib.sourceforge.net/) --> <svg width="%ipt" height="%ipt" viewBox="0 0 %i %i" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="svg1"> """
23,593
Python
.py
539
31.729128
136
0.523057
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,318
backend_fltkagg.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_fltkagg.py
""" A backend for FLTK Copyright: Gregory Lielens, Free Field Technologies SA and John D. Hunter 2004 This code is released under the matplotlib license """ from __future__ import division import os, sys, math import fltk as Fltk from backend_agg import FigureCanvasAgg import os.path import matplotlib from matplotlib import rcParams, verbose from matplotlib.cbook import is_string_like from matplotlib.backend_bases import \ RendererBase, GraphicsContextBase, FigureManagerBase, FigureCanvasBase,\ NavigationToolbar2, cursors from matplotlib.figure import Figure from matplotlib._pylab_helpers import Gcf import matplotlib.windowing as windowing from matplotlib.widgets import SubplotTool import thread,time Fl_running=thread.allocate_lock() def Fltk_run_interactive(): global Fl_running if Fl_running.acquire(0): while True: Fltk.Fl.check() time.sleep(0.005) else: print "fl loop already running" # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 75 cursord= { cursors.HAND: Fltk.FL_CURSOR_HAND, cursors.POINTER: Fltk.FL_CURSOR_ARROW, cursors.SELECT_REGION: Fltk.FL_CURSOR_CROSS, cursors.MOVE: Fltk.FL_CURSOR_MOVE } special_key={ Fltk.FL_Shift_R:'shift', Fltk.FL_Shift_L:'shift', Fltk.FL_Control_R:'control', Fltk.FL_Control_L:'control', Fltk.FL_Control_R:'control', Fltk.FL_Control_L:'control', 65515:'win', 65516:'win', } def error_msg_fltk(msg, parent=None): Fltk.fl_message(msg) def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw() def ishow(): """ Show all the figures and enter the fltk mainloop in another thread This allows to keep hand in interractive python session Warning: does not work under windows This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.show() if show._needmain: thread.start_new_thread(Fltk_run_interactive,()) show._needmain = False def show(): """ Show all the figures and enter the fltk mainloop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.show() #mainloop, if an fltk program exist no need to call that #threaded (and interractive) version if show._needmain: Fltk.Fl.run() show._needmain = False show._needmain = True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) window = Fltk.Fl_Double_Window(10,10,30,30) canvas = FigureCanvasFltkAgg(figure) window.end() window.show() window.make_current() figManager = FigureManagerFltkAgg(canvas, num, window) if matplotlib.is_interactive(): figManager.show() return figManager class FltkCanvas(Fltk.Fl_Widget): def __init__(self,x,y,w,h,l,source): Fltk.Fl_Widget.__init__(self, 0, 0, w, h, "canvas") self._source=source self._oldsize=(None,None) self._draw_overlay = False self._button = None self._key = None def draw(self): newsize=(self.w(),self.h()) if(self._oldsize !=newsize): self._oldsize =newsize self._source.resize(newsize) self._source.draw() t1,t2,w,h = self._source.figure.bbox.bounds Fltk.fl_draw_image(self._source.buffer_rgba(0,0),0,0,int(w),int(h),4,0) self.redraw() def blit(self,bbox=None): if bbox is None: t1,t2,w,h = self._source.figure.bbox.bounds else: t1o,t2o,wo,ho = self._source.figure.bbox.bounds t1,t2,w,h = bbox.bounds x,y=int(t1),int(t2) Fltk.fl_draw_image(self._source.buffer_rgba(x,y),x,y,int(w),int(h),4,int(wo)*4) #self.redraw() def handle(self, event): x=Fltk.Fl.event_x() y=Fltk.Fl.event_y() yf=self._source.figure.bbox.height() - y if event == Fltk.FL_FOCUS or event == Fltk.FL_UNFOCUS: return 1 elif event == Fltk.FL_KEYDOWN: ikey= Fltk.Fl.event_key() if(ikey<=255): self._key=chr(ikey) else: try: self._key=special_key[ikey] except: self._key=None FigureCanvasBase.key_press_event(self._source, self._key) return 1 elif event == Fltk.FL_KEYUP: FigureCanvasBase.key_release_event(self._source, self._key) self._key=None elif event == Fltk.FL_PUSH: self.window().make_current() if Fltk.Fl.event_button1(): self._button = 1 elif Fltk.Fl.event_button2(): self._button = 2 elif Fltk.Fl.event_button3(): self._button = 3 else: self._button = None if self._draw_overlay: self._oldx=x self._oldy=y if Fltk.Fl.event_clicks(): FigureCanvasBase.button_press_event(self._source, x, yf, self._button) return 1 else: FigureCanvasBase.button_press_event(self._source, x, yf, self._button) return 1 elif event == Fltk.FL_ENTER: self.take_focus() return 1 elif event == Fltk.FL_LEAVE: return 1 elif event == Fltk.FL_MOVE: FigureCanvasBase.motion_notify_event(self._source, x, yf) return 1 elif event == Fltk.FL_DRAG: self.window().make_current() if self._draw_overlay: self._dx=Fltk.Fl.event_x()-self._oldx self._dy=Fltk.Fl.event_y()-self._oldy Fltk.fl_overlay_rect(self._oldx,self._oldy,self._dx,self._dy) FigureCanvasBase.motion_notify_event(self._source, x, yf) return 1 elif event == Fltk.FL_RELEASE: self.window().make_current() if self._draw_overlay: Fltk.fl_overlay_clear() FigureCanvasBase.button_release_event(self._source, x, yf, self._button) self._button = None return 1 return 0 class FigureCanvasFltkAgg(FigureCanvasAgg): def __init__(self, figure): FigureCanvasAgg.__init__(self,figure) t1,t2,w,h = self.figure.bbox.bounds w, h = int(w), int(h) self.canvas=FltkCanvas(0, 0, w, h, "canvas",self) #self.draw() def resize(self,size): w, h = size # compute desired figure size in inches dpival = self.figure.dpi.get() winch = w/dpival hinch = h/dpival self.figure.set_size_inches(winch,hinch) def draw(self): FigureCanvasAgg.draw(self) self.canvas.redraw() def blit(self,bbox): self.canvas.blit(bbox) show = draw def widget(self): return self.canvas def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ def destroy_figure(ptr,figman): figman.window.hide() Gcf.destroy(figman._num) class FigureManagerFltkAgg(FigureManagerBase): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The fltk.Toolbar window : The fltk.Window """ def __init__(self, canvas, num, window): FigureManagerBase.__init__(self, canvas, num) #Fltk container window t1,t2,w,h = canvas.figure.bbox.bounds w, h = int(w), int(h) self.window = window self.window.size(w,h+30) self.window_title="Figure %d" % num self.window.label(self.window_title) self.window.size_range(350,200) self.window.callback(destroy_figure,self) self.canvas = canvas self._num = num if matplotlib.rcParams['toolbar']=='classic': self.toolbar = NavigationToolbar( canvas, self ) elif matplotlib.rcParams['toolbar']=='toolbar2': self.toolbar = NavigationToolbar2FltkAgg( canvas, self ) else: self.toolbar = None self.window.add_resizable(canvas.widget()) if self.toolbar: self.window.add(self.toolbar.widget()) self.toolbar.update() self.window.show() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) def resize(self, event): width, height = event.width, event.height self.toolbar.configure(width=width) # , height=height) def show(self): _focus = windowing.FocusManager() self.canvas.draw() self.window.redraw() def set_window_title(self, title): self.window_title=title self.window.label(title) class AxisMenu: def __init__(self, toolbar): self.toolbar=toolbar self._naxes = toolbar.naxes self._mbutton = Fltk.Fl_Menu_Button(0,0,50,10,"Axes") self._mbutton.add("Select All",0,select_all,self,0) self._mbutton.add("Invert All",0,invert_all,self,Fltk.FL_MENU_DIVIDER) self._axis_txt=[] self._axis_var=[] for i in range(self._naxes): self._axis_txt.append("Axis %d" % (i+1)) self._mbutton.add(self._axis_txt[i],0,set_active,self,Fltk.FL_MENU_TOGGLE) for i in range(self._naxes): self._axis_var.append(self._mbutton.find_item(self._axis_txt[i])) self._axis_var[i].set() def adjust(self, naxes): if self._naxes < naxes: for i in range(self._naxes, naxes): self._axis_txt.append("Axis %d" % (i+1)) self._mbutton.add(self._axis_txt[i],0,set_active,self,Fltk.FL_MENU_TOGGLE) for i in range(self._naxes, naxes): self._axis_var.append(self._mbutton.find_item(self._axis_txt[i])) self._axis_var[i].set() elif self._naxes > naxes: for i in range(self._naxes-1, naxes-1, -1): self._mbutton.remove(i+2) if(naxes): self._axis_var=self._axis_var[:naxes-1] self._axis_txt=self._axis_txt[:naxes-1] else: self._axis_var=[] self._axis_txt=[] self._naxes = naxes set_active(0,self) def widget(self): return self._mbutton def get_indices(self): a = [i for i in range(len(self._axis_var)) if self._axis_var[i].value()] return a def set_active(ptr,amenu): amenu.toolbar.set_active(amenu.get_indices()) def invert_all(ptr,amenu): for a in amenu._axis_var: if not a.value(): a.set() set_active(ptr,amenu) def select_all(ptr,amenu): for a in amenu._axis_var: a.set() set_active(ptr,amenu) class FLTKButton: def __init__(self, text, file, command,argument,type="classic"): file = os.path.join(rcParams['datapath'], 'images', file) self.im = Fltk.Fl_PNM_Image(file) size=26 if type=="repeat": self.b = Fltk.Fl_Repeat_Button(0,0,size,10) self.b.box(Fltk.FL_THIN_UP_BOX) elif type=="classic": self.b = Fltk.Fl_Button(0,0,size,10) self.b.box(Fltk.FL_THIN_UP_BOX) elif type=="light": self.b = Fltk.Fl_Light_Button(0,0,size+20,10) self.b.box(Fltk.FL_THIN_UP_BOX) elif type=="pushed": self.b = Fltk.Fl_Button(0,0,size,10) self.b.box(Fltk.FL_UP_BOX) self.b.down_box(Fltk.FL_DOWN_BOX) self.b.type(Fltk.FL_TOGGLE_BUTTON) self.tooltiptext=text+" " self.b.tooltip(self.tooltiptext) self.b.callback(command,argument) self.b.image(self.im) self.b.deimage(self.im) self.type=type def widget(self): return self.b class NavigationToolbar: """ Public attriubutes canvas - the FigureCanvas (FigureCanvasFltkAgg = customised fltk.Widget) """ def __init__(self, canvas, figman): #xmin, xmax = canvas.figure.bbox.intervalx().get_bounds() #height, width = 50, xmax-xmin self.canvas = canvas self.figman = figman Fltk.Fl_File_Icon.load_system_icons() self._fc = Fltk.Fl_File_Chooser( ".", "*", Fltk.Fl_File_Chooser.CREATE, "Save Figure" ) self._fc.hide() t1,t2,w,h = canvas.figure.bbox.bounds w, h = int(w), int(h) self._group = Fltk.Fl_Pack(0,h+2,1000,26) self._group.type(Fltk.FL_HORIZONTAL) self._axes=self.canvas.figure.axes self.naxes = len(self._axes) self.omenu = AxisMenu( toolbar=self) self.bLeft = FLTKButton( text="Left", file="stock_left.ppm", command=pan,argument=(self,1,'x'),type="repeat") self.bRight = FLTKButton( text="Right", file="stock_right.ppm", command=pan,argument=(self,-1,'x'),type="repeat") self.bZoomInX = FLTKButton( text="ZoomInX",file="stock_zoom-in.ppm", command=zoom,argument=(self,1,'x'),type="repeat") self.bZoomOutX = FLTKButton( text="ZoomOutX", file="stock_zoom-out.ppm", command=zoom, argument=(self,-1,'x'),type="repeat") self.bUp = FLTKButton( text="Up", file="stock_up.ppm", command=pan,argument=(self,1,'y'),type="repeat") self.bDown = FLTKButton( text="Down", file="stock_down.ppm", command=pan,argument=(self,-1,'y'),type="repeat") self.bZoomInY = FLTKButton( text="ZoomInY", file="stock_zoom-in.ppm", command=zoom,argument=(self,1,'y'),type="repeat") self.bZoomOutY = FLTKButton( text="ZoomOutY",file="stock_zoom-out.ppm", command=zoom, argument=(self,-1,'y'),type="repeat") self.bSave = FLTKButton( text="Save", file="stock_save_as.ppm", command=save_figure, argument=self) self._group.end() def widget(self): return self._group def close(self): Gcf.destroy(self.figman._num) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def update(self): self._axes = self.canvas.figure.axes naxes = len(self._axes) self.omenu.adjust(naxes) def pan(ptr, arg): base,direction,axe=arg for a in base._active: if(axe=='x'): a.panx(direction) else: a.pany(direction) base.figman.show() def zoom(ptr, arg): base,direction,axe=arg for a in base._active: if(axe=='x'): a.zoomx(direction) else: a.zoomy(direction) base.figman.show() def save_figure(ptr,base): filetypes = base.canvas.get_supported_filetypes() default_filetype = base.canvas.get_default_filetype() sorted_filetypes = filetypes.items() sorted_filetypes.sort() selected_filter = 0 filters = [] for i, (ext, name) in enumerate(sorted_filetypes): filter = '%s (*.%s)' % (name, ext) filters.append(filter) if ext == default_filetype: selected_filter = i filters = '\t'.join(filters) file_chooser=base._fc file_chooser.filter(filters) file_chooser.filter_value(selected_filter) file_chooser.show() while file_chooser.visible() : Fltk.Fl.wait() fname=None if(file_chooser.count() and file_chooser.value(0) != None): fname="" (status,fname)=Fltk.fl_filename_absolute(fname, 1024, file_chooser.value(0)) if fname is None: # Cancel return #start from last directory lastDir = os.path.dirname(fname) file_chooser.directory(lastDir) format = sorted_filetypes[file_chooser.filter_value()][0] try: base.canvas.print_figure(fname, format=format) except IOError, msg: err = '\n'.join(map(str, msg)) msg = 'Failed to save %s: Error msg was\n\n%s' % ( fname, err) error_msg_fltk(msg) class NavigationToolbar2FltkAgg(NavigationToolbar2): """ Public attriubutes canvas - the FigureCanvas figman - the Figure manager """ def __init__(self, canvas, figman): self.canvas = canvas self.figman = figman NavigationToolbar2.__init__(self, canvas) self.pan_selected=False self.zoom_selected=False def set_cursor(self, cursor): Fltk.fl_cursor(cursord[cursor],Fltk.FL_BLACK,Fltk.FL_WHITE) def dynamic_update(self): self.canvas.draw() def pan(self,*args): self.pan_selected=not self.pan_selected self.zoom_selected = False self.canvas.canvas._draw_overlay= False if self.pan_selected: self.bPan.widget().value(1) else: self.bPan.widget().value(0) if self.zoom_selected: self.bZoom.widget().value(1) else: self.bZoom.widget().value(0) NavigationToolbar2.pan(self,args) def zoom(self,*args): self.zoom_selected=not self.zoom_selected self.canvas.canvas._draw_overlay=self.zoom_selected self.pan_selected = False if self.pan_selected: self.bPan.widget().value(1) else: self.bPan.widget().value(0) if self.zoom_selected: self.bZoom.widget().value(1) else: self.bZoom.widget().value(0) NavigationToolbar2.zoom(self,args) def configure_subplots(self,*args): window = Fltk.Fl_Double_Window(100,100,480,240) toolfig = Figure(figsize=(6,3)) canvas = FigureCanvasFltkAgg(toolfig) window.end() toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) window.show() canvas.show() def _init_toolbar(self): Fltk.Fl_File_Icon.load_system_icons() self._fc = Fltk.Fl_File_Chooser( ".", "*", Fltk.Fl_File_Chooser.CREATE, "Save Figure" ) self._fc.hide() t1,t2,w,h = self.canvas.figure.bbox.bounds w, h = int(w), int(h) self._group = Fltk.Fl_Pack(0,h+2,1000,26) self._group.type(Fltk.FL_HORIZONTAL) self._axes=self.canvas.figure.axes self.naxes = len(self._axes) self.omenu = AxisMenu( toolbar=self) self.bHome = FLTKButton( text="Home", file="home.ppm", command=self.home,argument=self) self.bBack = FLTKButton( text="Back", file="back.ppm", command=self.back,argument=self) self.bForward = FLTKButton( text="Forward", file="forward.ppm", command=self.forward,argument=self) self.bPan = FLTKButton( text="Pan/Zoom",file="move.ppm", command=self.pan,argument=self,type="pushed") self.bZoom = FLTKButton( text="Zoom to rectangle",file="zoom_to_rect.ppm", command=self.zoom,argument=self,type="pushed") self.bsubplot = FLTKButton( text="Configure Subplots", file="subplots.ppm", command = self.configure_subplots,argument=self,type="pushed") self.bSave = FLTKButton( text="Save", file="filesave.ppm", command=save_figure, argument=self) self._group.end() self.message = Fltk.Fl_Output(0,0,w,8) self._group.add_resizable(self.message) self.update() def widget(self): return self._group def close(self): Gcf.destroy(self.figman._num) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def update(self): self._axes = self.canvas.figure.axes naxes = len(self._axes) self.omenu.adjust(naxes) NavigationToolbar2.update(self) def set_message(self, s): self.message.value(s) FigureManager = FigureManagerFltkAgg
20,839
Python
.py
551
29.076225
166
0.604381
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,319
backend_qt.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_qt.py
from __future__ import division import math import os import sys import matplotlib from matplotlib import verbose from matplotlib.cbook import is_string_like, onetrue from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors from matplotlib._pylab_helpers import Gcf from matplotlib.figure import Figure from matplotlib.mathtext import MathTextParser from matplotlib.widgets import SubplotTool try: import qt except ImportError: raise ImportError("Qt backend requires pyqt to be installed.") backend_version = "0.9.1" def fn_name(): return sys._getframe(1).f_code.co_name DEBUG = False cursord = { cursors.MOVE : qt.Qt.PointingHandCursor, cursors.HAND : qt.Qt.WaitCursor, cursors.POINTER : qt.Qt.ArrowCursor, cursors.SELECT_REGION : qt.Qt.CrossCursor, } def draw_if_interactive(): """ Is called after every pylab drawing command """ if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one """ if qt.QApplication.startingUp(): if DEBUG: print "Starting up QApplication" global qApp qApp = qt.QApplication( [" "] ) qt.QObject.connect( qApp, qt.SIGNAL( "lastWindowClosed()" ), qApp, qt.SLOT( "quit()" ) ) #remember that matplotlib created the qApp - will be used by show() _create_qApp.qAppCreatedHere = True _create_qApp.qAppCreatedHere = False def show(): """ Show all the figures and enter the qt main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if DEBUG: print 'Inside show' figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() if _create_qApp.qAppCreatedHere: qt.qApp.exec_loop() def new_figure_manager( num, *args, **kwargs ): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass( *args, **kwargs ) canvas = FigureCanvasQT( thisFig ) manager = FigureManagerQT( canvas, num ) return manager class FigureCanvasQT( qt.QWidget, FigureCanvasBase ): keyvald = { qt.Qt.Key_Control : 'control', qt.Qt.Key_Shift : 'shift', qt.Qt.Key_Alt : 'alt', } # left 1, middle 2, right 3 buttond = {1:1, 2:3, 4:2} def __init__( self, figure ): if DEBUG: print 'FigureCanvasQt: ', figure _create_qApp() qt.QWidget.__init__( self, None, "QWidget figure" ) FigureCanvasBase.__init__( self, figure ) self.figure = figure self.setMouseTracking( True ) w,h = self.get_width_height() self.resize( w, h ) def enterEvent(self, event): FigureCanvasBase.enter_notify_event(self, event) def leaveEvent(self, event): FigureCanvasBase.leave_notify_event(self, event) def mousePressEvent( self, event ): x = event.pos().x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.pos().y() button = self.buttond[event.button()] FigureCanvasBase.button_press_event( self, x, y, button ) if DEBUG: print 'button pressed:', event.button() def mouseMoveEvent( self, event ): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() FigureCanvasBase.motion_notify_event( self, x, y ) if DEBUG: print 'mouse move' def mouseReleaseEvent( self, event ): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() button = self.buttond[event.button()] FigureCanvasBase.button_release_event( self, x, y, button ) if DEBUG: print 'button released' def keyPressEvent( self, event ): key = self._get_key( event ) FigureCanvasBase.key_press_event( self, key ) if DEBUG: print 'key press', key def keyReleaseEvent( self, event ): key = self._get_key(event) FigureCanvasBase.key_release_event( self, key ) if DEBUG: print 'key release', key def resizeEvent( self, event ): if DEBUG: print 'resize (%d x %d)' % (event.size().width(), event.size().height()) qt.QWidget.resizeEvent( self, event ) w = event.size().width() h = event.size().height() if DEBUG: print "FigureCanvasQt.resizeEvent(", w, ",", h, ")" dpival = self.figure.dpi winch = w/dpival hinch = h/dpival self.figure.set_size_inches( winch, hinch ) self.draw() def resize( self, w, h ): # Pass through to Qt to resize the widget. qt.QWidget.resize( self, w, h ) # Resize the figure by converting pixels to inches. pixelPerInch = self.figure.dpi wInch = w / pixelPerInch hInch = h / pixelPerInch self.figure.set_size_inches( wInch, hInch ) # Redraw everything. self.draw() def sizeHint( self ): w, h = self.get_width_height() return qt.QSize( w, h ) def minumumSizeHint( self ): return qt.QSize( 10, 10 ) def _get_key( self, event ): if event.key() < 256: key = event.text().latin1() elif event.key() in self.keyvald.has_key: key = self.keyvald[ event.key() ] else: key = None return key def flush_events(self): qt.qApp.processEvents() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerQT( FigureManagerBase ): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The qt.QToolBar window : The qt.QMainWindow """ def __init__( self, canvas, num ): if DEBUG: print 'FigureManagerQT.%s' % fn_name() FigureManagerBase.__init__( self, canvas, num ) self.canvas = canvas self.window = qt.QMainWindow( None, None, qt.Qt.WDestructiveClose ) self.window.closeEvent = self._widgetCloseEvent centralWidget = qt.QWidget( self.window ) self.canvas.reparent( centralWidget, qt.QPoint( 0, 0 ) ) # Give the keyboard focus to the figure instead of the manager self.canvas.setFocusPolicy( qt.QWidget.ClickFocus ) self.canvas.setFocus() self.window.setCaption( "Figure %d" % num ) self.window._destroying = False self.toolbar = self._get_toolbar(self.canvas, centralWidget) # Use a vertical layout for the plot and the toolbar. Set the # stretch to all be in the plot so the toolbar doesn't resize. self.layout = qt.QVBoxLayout( centralWidget ) self.layout.addWidget( self.canvas, 1 ) if self.toolbar: self.layout.addWidget( self.toolbar, 0 ) self.window.setCentralWidget( centralWidget ) # Reset the window height so the canvas will be the right # size. This ALMOST works right. The first issue is that the # height w/ a toolbar seems to be off by just a little bit (so # we add 4 pixels). The second is that the total width/height # is slightly smaller that we actually want. It seems like # the border of the window is being included in the size but # AFAIK there is no way to get that size. w = self.canvas.width() h = self.canvas.height() if self.toolbar: h += self.toolbar.height() + 4 self.window.resize( w, h ) if matplotlib.is_interactive(): self.window.show() # attach a show method to the figure for pylab ease of use self.canvas.figure.show = lambda *args: self.window.show() def notify_axes_change( fig ): # This will be called whenever the current axes is changed if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver( notify_axes_change ) def _widgetclosed( self ): if self.window._destroying: return self.window._destroying = True Gcf.destroy(self.num) def _widgetCloseEvent( self, event ): self._widgetclosed() qt.QWidget.closeEvent( self.window, event ) def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'classic': print "Classic toolbar is not yet supported" elif matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent) else: toolbar = None return toolbar def resize(self, width, height): 'set the canvas size in pixels' self.window.resize(width, height) def destroy( self, *args ): if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() if DEBUG: print "destroy figure manager" self.window.close(True) def set_window_title(self, title): self.window.setCaption(title) class NavigationToolbar2QT( NavigationToolbar2, qt.QWidget ): # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home.ppm', 'home'), ('Back', 'Back to previous view','back.ppm', 'back'), ('Forward', 'Forward to next view','forward.ppm', 'forward'), (None, None, None, None), ('Pan', 'Pan axes with left mouse, zoom with right', 'move.ppm', 'pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect.ppm', 'zoom'), (None, None, None, None), ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave.ppm', 'save_figure'), ) def __init__( self, canvas, parent ): self.canvas = canvas self.buttons = {} qt.QWidget.__init__( self, parent ) # Layout toolbar buttons horizontally. self.layout = qt.QHBoxLayout( self ) self.layout.setMargin( 2 ) NavigationToolbar2.__init__( self, canvas ) def _init_toolbar( self ): basedir = os.path.join(matplotlib.rcParams[ 'datapath' ],'images') for text, tooltip_text, image_file, callback in self.toolitems: if text == None: self.layout.addSpacing( 8 ) continue fname = os.path.join( basedir, image_file ) image = qt.QPixmap() image.load( fname ) button = qt.QPushButton( qt.QIconSet( image ), "", self ) qt.QToolTip.add( button, tooltip_text ) self.buttons[ text ] = button # The automatic layout doesn't look that good - it's too close # to the images so add a margin around it. margin = 4 button.setFixedSize( image.width()+margin, image.height()+margin ) qt.QObject.connect( button, qt.SIGNAL( 'clicked()' ), getattr( self, callback ) ) self.layout.addWidget( button ) self.buttons[ 'Pan' ].setToggleButton( True ) self.buttons[ 'Zoom' ].setToggleButton( True ) # Add the x,y location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. self.locLabel = qt.QLabel( "", self ) self.locLabel.setAlignment( qt.Qt.AlignRight | qt.Qt.AlignVCenter ) self.locLabel.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Ignored, qt.QSizePolicy.Ignored)) self.layout.addWidget( self.locLabel, 1 ) # reference holder for subplots_adjust window self.adj_window = None def destroy( self ): for text, tooltip_text, image_file, callback in self.toolitems: if text is not None: qt.QObject.disconnect( self.buttons[ text ], qt.SIGNAL( 'clicked()' ), getattr( self, callback ) ) def pan( self, *args ): self.buttons[ 'Zoom' ].setOn( False ) NavigationToolbar2.pan( self, *args ) def zoom( self, *args ): self.buttons[ 'Pan' ].setOn( False ) NavigationToolbar2.zoom( self, *args ) def dynamic_update( self ): self.canvas.draw() def set_message( self, s ): self.locLabel.setText( s ) def set_cursor( self, cursor ): if DEBUG: print 'Set cursor' , cursor qt.QApplication.restoreOverrideCursor() qt.QApplication.setOverrideCursor( qt.QCursor( cursord[cursor] ) ) def draw_rubberband( self, event, x0, y0, x1, y1 ): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [ int(val)for val in min(x0,x1), min(y0, y1), w, h ] self.canvas.drawRectangle( rect ) def configure_subplots(self): self.adj_window = qt.QMainWindow(None, None, qt.Qt.WDestructiveClose) win = self.adj_window win.setCaption("Subplot Configuration Tool") toolfig = Figure(figsize=(6,3)) toolfig.subplots_adjust(top=0.9) w = int (toolfig.bbox.width) h = int (toolfig.bbox.height) canvas = self._get_canvas(toolfig) tool = SubplotTool(self.canvas.figure, toolfig) centralWidget = qt.QWidget(win) canvas.reparent(centralWidget, qt.QPoint(0, 0)) win.setCentralWidget(centralWidget) layout = qt.QVBoxLayout(centralWidget) layout.addWidget(canvas, 1) win.resize(w, h) canvas.setFocus() win.show() def _get_canvas(self, fig): return FigureCanvasQT(fig) def save_figure( self ): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() default_filetype = self.canvas.get_default_filetype() start = "image." + default_filetype filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname = qt.QFileDialog.getSaveFileName( start, filters, self, "Save image", "Choose a filename to save to", selectedFilter) if fname: try: self.canvas.print_figure( unicode(fname) ) except Exception, e: qt.QMessageBox.critical( self, "Error saving file", str(e), qt.QMessageBox.Ok, qt.QMessageBox.NoButton) def set_history_buttons( self ): canBackward = ( self._views._pos > 0 ) canForward = ( self._views._pos < len( self._views._elements ) - 1 ) self.buttons[ 'Back' ].setEnabled( canBackward ) self.buttons[ 'Forward' ].setEnabled( canForward ) # set icon used when windows are minimized try: # TODO: This is badly broken qt.window_set_default_icon_from_file ( os.path.join( matplotlib.rcParams['datapath'], 'images', 'matplotlib.svg' ) ) except: verbose.report( 'Could not load matplotlib icon: %s' % sys.exc_info()[1] ) def error_msg_qt( msg, parent=None ): if not is_string_like( msg ): msg = ','.join( map( str,msg ) ) qt.QMessageBox.warning( None, "Matplotlib", msg, qt.QMessageBox.Ok ) def exception_handler( type, value, tb ): """Handle uncaught exceptions It does not catch SystemExit """ msg = '' # get the filename attribute if available (for IOError) if hasattr(value, 'filename') and value.filename != None: msg = value.filename + ': ' if hasattr(value, 'strerror') and value.strerror != None: msg += value.strerror else: msg += str(value) if len( msg ) : error_msg_qt( msg ) FigureManager = FigureManagerQT
16,846
Python
.py
392
34.408163
90
0.619956
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,320
backend_gtk.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_gtk.py
from __future__ import division import os, sys def fn_name(): return sys._getframe(1).f_code.co_name try: import gobject import gtk; gdk = gtk.gdk import pango except ImportError: raise ImportError("Gtk* backend requires pygtk to be installed.") pygtk_version_required = (2,2,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required import matplotlib from matplotlib import verbose from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK from matplotlib.cbook import is_string_like, is_writable_file_like from matplotlib.colors import colorConverter from matplotlib.figure import Figure from matplotlib.widgets import SubplotTool from matplotlib import lines from matplotlib import cbook backend_version = "%d.%d.%d" % gtk.pygtk_version _debug = False #_debug = True # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 96 cursord = { cursors.MOVE : gdk.Cursor(gdk.FLEUR), cursors.HAND : gdk.Cursor(gdk.HAND2), cursors.POINTER : gdk.Cursor(gdk.LEFT_PTR), cursors.SELECT_REGION : gdk.Cursor(gdk.TCROSS), } # ref gtk+/gtk/gtkwidget.h def GTK_WIDGET_DRAWABLE(w): flags = w.flags(); return flags & gtk.VISIBLE != 0 and flags & gtk.MAPPED != 0 def draw_if_interactive(): """ Is called after every pylab drawing command """ if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw() def show(mainloop=True): """ Show all the figures and enter the gtk main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if mainloop and gtk.main_level() == 0 and \ len(Gcf.get_all_fig_managers())>0: gtk.main() def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGTK(thisFig) manager = FigureManagerGTK(canvas, num) # equals: #manager = FigureManagerGTK(FigureCanvasGTK(Figure(*args, **kwargs), num) return manager class FigureCanvasGTK (gtk.DrawingArea, FigureCanvasBase): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', } # Setting this as a static constant prevents # this resulting expression from leaking event_mask = (gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.EXPOSURE_MASK | gdk.KEY_PRESS_MASK | gdk.KEY_RELEASE_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK) def __init__(self, figure): if _debug: print 'FigureCanvasGTK.%s' % fn_name() FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('expose_event', self.expose_event) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self._idle_event_id = gobject.idle_add(self.idle_event) def destroy(self): #gtk.DrawingArea.destroy(self) gobject.source_remove(self._idle_event_id) if self._idle_draw_id != 0: gobject.source_remove(self._idle_draw_id) def scroll_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y if event.direction==gdk.SCROLL_UP: step = 1 else: step = -1 FigureCanvasBase.scroll_event(self, x, y, step) return False # finish event propagation? def button_press_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y FigureCanvasBase.button_press_event(self, x, y, event.button) return False # finish event propagation? def button_release_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y FigureCanvasBase.button_release_event(self, x, y, event.button) return False # finish event propagation? def key_press_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() key = self._get_key(event) if _debug: print "hit", key FigureCanvasBase.key_press_event(self, key) return False # finish event propagation? def key_release_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() key = self._get_key(event) if _debug: print "release", key FigureCanvasBase.key_release_event(self, key) return False # finish event propagation? def motion_notify_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state # flipy so y=0 is bottom of canvas y = self.allocation.height - y FigureCanvasBase.motion_notify_event(self, x, y) return False # finish event propagation? def leave_notify_event(self, widget, event): FigureCanvasBase.leave_notify_event(self, event) def enter_notify_event(self, widget, event): FigureCanvasBase.enter_notify_event(self, event) def _get_key(self, event): if event.keyval in self.keyvald: key = self.keyvald[event.keyval] elif event.keyval <256: key = chr(event.keyval) else: key = None ctrl = event.state & gdk.CONTROL_MASK shift = event.state & gdk.SHIFT_MASK return key def configure_event(self, widget, event): if _debug: print 'FigureCanvasGTK.%s' % fn_name() if widget.window is None: return w, h = event.width, event.height if w < 3 or h < 3: return # empty fig # resize the figure (in inches) dpi = self.figure.dpi self.figure.set_size_inches (w/dpi, h/dpi) self._need_redraw = True return False # finish event propagation? def draw(self): # Note: FigureCanvasBase.draw() is inconveniently named as it clashes # with the deprecated gtk.Widget.draw() self._need_redraw = True if GTK_WIDGET_DRAWABLE(self): self.queue_draw() # do a synchronous draw (its less efficient than an async draw, # but is required if/when animation is used) self.window.process_updates (False) def draw_idle(self): def idle_draw(*args): self.draw() self._idle_draw_id = 0 return False if self._idle_draw_id == 0: self._idle_draw_id = gobject.idle_add(idle_draw) def _renderer_init(self): """Override by GTK backends to select a different renderer Renderer should provide the methods: set_pixmap () set_width_height () that are used by _render_figure() / _pixmap_prepare() """ self._renderer = RendererGDK (self, self.figure.dpi) def _pixmap_prepare(self, width, height): """ Make sure _._pixmap is at least width, height, create new pixmap if necessary """ if _debug: print 'FigureCanvasGTK.%s' % fn_name() create_pixmap = False if width > self._pixmap_width: # increase the pixmap in 10%+ (rather than 1 pixel) steps self._pixmap_width = max (int (self._pixmap_width * 1.1), width) create_pixmap = True if height > self._pixmap_height: self._pixmap_height = max (int (self._pixmap_height * 1.1), height) create_pixmap = True if create_pixmap: self._pixmap = gdk.Pixmap (self.window, self._pixmap_width, self._pixmap_height) self._renderer.set_pixmap (self._pixmap) def _render_figure(self, pixmap, width, height): """used by GTK and GTKcairo. GTKAgg overrides """ self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) def expose_event(self, widget, event): """Expose_event for all GTK backends. Should not be overridden. """ if _debug: print 'FigureCanvasGTK.%s' % fn_name() if GTK_WIDGET_DRAWABLE(self): if self._need_redraw: x, y, w, h = self.allocation self._pixmap_prepare (w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False x, y, w, h = event.area self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, x, y, x, y, w, h) return False # finish event propagation? filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' filetypes['png'] = 'Portable Network Graphics' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format): if self.flags() & gtk.REALIZED == 0: # for self.window(for pixmap) and has a side effect of altering # figure width,height (via configure-event?) gtk.DrawingArea.realize(self) width, height = self.get_width_height() pixmap = gdk.Pixmap (self.window, width, height) self._renderer.set_pixmap (pixmap) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) if is_string_like(filename): try: pixbuf.save(filename, format) except gobject.GError, exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) elif is_writable_file_like(filename): if hasattr(pixbuf, 'save_to_callback'): def save_callback(buf, data=None): data.write(buf) try: pixbuf.save_to_callback(save_callback, format, user_data=filename) except gobject.GError, exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) else: raise ValueError("Saving to a Python file-like object is only supported by PyGTK >= 2.8") else: raise ValueError("filename must be a path or a file-like object") def get_default_filetype(self): return 'png' def flush_events(self): gtk.gdk.threads_enter() while gtk.events_pending(): gtk.main_iteration(True) gtk.gdk.flush() gtk.gdk.threads_leave() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerGTK(FigureManagerBase): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The gtk.Toolbar (gtk only) vbox : The gtk.VBox containing the canvas and toolbar (gtk only) window : The gtk.Window (gtk only) """ def __init__(self, canvas, num): if _debug: print 'FigureManagerGTK.%s' % fn_name() FigureManagerBase.__init__(self, canvas, num) self.window = gtk.Window() self.window.set_title("Figure %d" % num) self.vbox = gtk.VBox() self.window.add(self.vbox) self.vbox.show() self.canvas.show() # attach a show method to the figure for pylab ease of use self.canvas.figure.show = lambda *args: self.window.show() self.vbox.pack_start(self.canvas, True, True) self.toolbar = self._get_toolbar(canvas) # calculate size for window w = int (self.canvas.figure.bbox.width) h = int (self.canvas.figure.bbox.height) if self.toolbar is not None: self.toolbar.show() self.vbox.pack_end(self.toolbar, False, False) tb_w, tb_h = self.toolbar.size_request() h += tb_h self.window.set_default_size (w, h) def destroy(*args): Gcf.destroy(num) self.window.connect("destroy", destroy) self.window.connect("delete_event", destroy) if matplotlib.is_interactive(): self.window.show() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.canvas.grab_focus() def destroy(self, *args): if _debug: print 'FigureManagerGTK.%s' % fn_name() self.vbox.destroy() self.window.destroy() self.canvas.destroy() self.toolbar.destroy() self.__dict__.clear() if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ gtk.main_level() >= 1: gtk.main_quit() def show(self): # show the figure window self.window.show() def full_screen_toggle (self): self._full_screen_flag = not self._full_screen_flag if self._full_screen_flag: self.window.fullscreen() else: self.window.unfullscreen() _full_screen_flag = False def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'classic': toolbar = NavigationToolbar (canvas, self.window) elif matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2GTK (canvas, self.window) else: toolbar = None return toolbar def set_window_title(self, title): self.window.set_title(title) def resize(self, width, height): 'set the canvas size in pixels' #_, _, cw, ch = self.canvas.allocation #_, _, ww, wh = self.window.allocation #self.window.resize (width-cw+ww, height-ch+wh) self.window.resize(width, height) class NavigationToolbar2GTK(NavigationToolbar2, gtk.Toolbar): # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home.png', 'home'), ('Back', 'Back to previous view','back.png', 'back'), ('Forward', 'Forward to next view','forward.png', 'forward'), ('Pan', 'Pan axes with left mouse, zoom with right', 'move.png','pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect.png', 'zoom'), (None, None, None, None), ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave.png', 'save_figure'), ) def __init__(self, canvas, window): self.win = window gtk.Toolbar.__init__(self) NavigationToolbar2.__init__(self, canvas) self._idle_draw_id = 0 def set_message(self, s): if self._idle_draw_id == 0: self.message.set_label(s) def set_cursor(self, cursor): self.canvas.window.set_cursor(cursord[cursor]) def release(self, event): try: del self._imageBack except AttributeError: pass def dynamic_update(self): # legacy method; new method is canvas.draw_idle self.canvas.draw_idle() def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' drawable = self.canvas.window if drawable is None: return gc = drawable.new_gc() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [int(val)for val in min(x0,x1), min(y0, y1), w, h] try: lastrect, imageBack = self._imageBack except AttributeError: #snap image back if event.inaxes is None: return ax = event.inaxes l,b,w,h = [int(val) for val in ax.bbox.bounds] b = int(height)-(b+h) axrect = l,b,w,h self._imageBack = axrect, drawable.get_image(*axrect) drawable.draw_rectangle(gc, False, *rect) self._idle_draw_id = 0 else: def idle_draw(*args): drawable.draw_image(gc, imageBack, 0, 0, *lastrect) drawable.draw_rectangle(gc, False, *rect) self._idle_draw_id = 0 return False if self._idle_draw_id == 0: self._idle_draw_id = gobject.idle_add(idle_draw) def _init_toolbar(self): self.set_style(gtk.TOOLBAR_ICONS) if gtk.pygtk_version >= (2,4,0): self._init_toolbar2_4() else: self._init_toolbar2_2() def _init_toolbar2_2(self): basedir = os.path.join(matplotlib.rcParams['datapath'],'images') for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.append_space() continue fname = os.path.join(basedir, image_file) image = gtk.Image() image.set_from_file(fname) w = self.append_item(text, tooltip_text, 'Private', image, getattr(self, callback) ) self.append_space() self.message = gtk.Label() self.append_widget(self.message, None, None) self.message.show() def _init_toolbar2_4(self): basedir = os.path.join(matplotlib.rcParams['datapath'],'images') self.tooltips = gtk.Tooltips() for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue fname = os.path.join(basedir, image_file) image = gtk.Image() image.set_from_file(fname) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) tbutton.connect('clicked', getattr(self, callback)) tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') toolitem = gtk.SeparatorToolItem() self.insert(toolitem, -1) # set_draw() not making separator invisible, # bug #143692 fixed Jun 06 2004, will be in GTK+ 2.6 toolitem.set_draw(False) toolitem.set_expand(True) toolitem = gtk.ToolItem() self.insert(toolitem, -1) self.message = gtk.Label() toolitem.add(self.message) self.show_all() def get_filechooser(self): if gtk.pygtk_version >= (2,4,0): return FileChooserDialog( title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) else: return FileSelection(title='Save the figure', parent=self.win,) def save_figure(self, button): fname, format = self.get_filechooser().get_filename_from_user() if fname: try: self.canvas.print_figure(fname, format=format) except Exception, e: error_msg_gtk(str(e), parent=self) def configure_subplots(self, button): toolfig = Figure(figsize=(6,3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int (toolfig.bbox.width) h = int (toolfig.bbox.height) window = gtk.Window() window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = gtk.VBox() window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True) window.show() def _get_canvas(self, fig): return FigureCanvasGTK(fig) class NavigationToolbar(gtk.Toolbar): """ Public attributes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image, callback(str), callback_arg, scroll(bool) toolitems = ( ('Left', 'Pan left with click or wheel mouse (bidirectional)', gtk.STOCK_GO_BACK, 'panx', -1, True), ('Right', 'Pan right with click or wheel mouse (bidirectional)', gtk.STOCK_GO_FORWARD, 'panx', 1, True), ('Zoom In X', 'Zoom In X (shrink the x axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_IN, 'zoomx', 1, True), ('Zoom Out X', 'Zoom Out X (expand the x axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_OUT, 'zoomx', -1, True), (None, None, None, None, None, None,), ('Up', 'Pan up with click or wheel mouse (bidirectional)', gtk.STOCK_GO_UP, 'pany', 1, True), ('Down', 'Pan down with click or wheel mouse (bidirectional)', gtk.STOCK_GO_DOWN, 'pany', -1, True), ('Zoom In Y', 'Zoom in Y (shrink the y axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_IN, 'zoomy', 1, True), ('Zoom Out Y', 'Zoom Out Y (expand the y axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_OUT, 'zoomy', -1, True), (None, None, None, None, None, None,), ('Save', 'Save the figure', gtk.STOCK_SAVE, 'save_figure', None, False), ) def __init__(self, canvas, window): """ figManager is the FigureManagerGTK instance that contains the toolbar, with attributes figure, window and drawingArea """ gtk.Toolbar.__init__(self) self.canvas = canvas # Note: gtk.Toolbar already has a 'window' attribute self.win = window self.set_style(gtk.TOOLBAR_ICONS) if gtk.pygtk_version >= (2,4,0): self._create_toolitems_2_4() self.update = self._update_2_4 self.fileselect = FileChooserDialog( title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) else: self._create_toolitems_2_2() self.update = self._update_2_2 self.fileselect = FileSelection(title='Save the figure', parent=self.win) self.show_all() self.update() def _create_toolitems_2_4(self): # use the GTK+ 2.4 GtkToolbar API iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR self.tooltips = gtk.Tooltips() for text, tooltip_text, image_num, callback, callback_arg, scroll \ in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue image = gtk.Image() image.set_from_stock(image_num, iconSize) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) if callback_arg: tbutton.connect('clicked', getattr(self, callback), callback_arg) else: tbutton.connect('clicked', getattr(self, callback)) if scroll: tbutton.connect('scroll_event', getattr(self, callback)) tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') # Axes toolitem, is empty at start, update() adds a menu if >=2 axes self.axes_toolitem = gtk.ToolItem() self.insert(self.axes_toolitem, 0) self.axes_toolitem.set_tooltip ( self.tooltips, tip_text='Select axes that controls affect', tip_private = 'Private') align = gtk.Alignment (xalign=0.5, yalign=0.5, xscale=0.0, yscale=0.0) self.axes_toolitem.add(align) self.menubutton = gtk.Button ("Axes") align.add (self.menubutton) def position_menu (menu): """Function for positioning a popup menu. Place menu below the menu button, but ensure it does not go off the bottom of the screen. The default is to popup menu at current mouse position """ x0, y0 = self.window.get_origin() x1, y1, m = self.window.get_pointer() x2, y2 = self.menubutton.get_pointer() sc_h = self.get_screen().get_height() # requires GTK+ 2.2 + w, h = menu.size_request() x = x0 + x1 - x2 y = y0 + y1 - y2 + self.menubutton.allocation.height y = min(y, sc_h - h) return x, y, True def button_clicked (button, data=None): self.axismenu.popup (None, None, position_menu, 0, gtk.get_current_event_time()) self.menubutton.connect ("clicked", button_clicked) def _update_2_4(self): # for GTK+ 2.4+ # called by __init__() and FigureManagerGTK self._axes = self.canvas.figure.axes if len(self._axes) >= 2: self.axismenu = self._make_axis_menu() self.menubutton.show_all() else: self.menubutton.hide() self.set_active(range(len(self._axes))) def _create_toolitems_2_2(self): # use the GTK+ 2.2 (and lower) GtkToolbar API iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR for text, tooltip_text, image_num, callback, callback_arg, scroll \ in self.toolitems: if text is None: self.append_space() continue image = gtk.Image() image.set_from_stock(image_num, iconSize) item = self.append_item(text, tooltip_text, 'Private', image, getattr(self, callback), callback_arg) if scroll: item.connect("scroll_event", getattr(self, callback)) self.omenu = gtk.OptionMenu() self.omenu.set_border_width(3) self.insert_widget( self.omenu, 'Select axes that controls affect', 'Private', 0) def _update_2_2(self): # for GTK+ 2.2 and lower # called by __init__() and FigureManagerGTK self._axes = self.canvas.figure.axes if len(self._axes) >= 2: # set up the axis menu self.omenu.set_menu( self._make_axis_menu() ) self.omenu.show_all() else: self.omenu.hide() self.set_active(range(len(self._axes))) def _make_axis_menu(self): # called by self._update*() def toggled(item, data=None): if item == self.itemAll: for item in items: item.set_active(True) elif item == self.itemInvert: for item in items: item.set_active(not item.get_active()) ind = [i for i,item in enumerate(items) if item.get_active()] self.set_active(ind) menu = gtk.Menu() self.itemAll = gtk.MenuItem("All") menu.append(self.itemAll) self.itemAll.connect("activate", toggled) self.itemInvert = gtk.MenuItem("Invert") menu.append(self.itemInvert) self.itemInvert.connect("activate", toggled) items = [] for i in range(len(self._axes)): item = gtk.CheckMenuItem("Axis %d" % (i+1)) menu.append(item) item.connect("toggled", toggled) item.set_active(True) items.append(item) menu.show_all() return menu def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def panx(self, button, direction): 'panx in direction' for a in self._active: a.xaxis.pan(direction) self.canvas.draw() return True def pany(self, button, direction): 'pany in direction' for a in self._active: a.yaxis.pan(direction) self.canvas.draw() return True def zoomx(self, button, direction): 'zoomx in direction' for a in self._active: a.xaxis.zoom(direction) self.canvas.draw() return True def zoomy(self, button, direction): 'zoomy in direction' for a in self._active: a.yaxis.zoom(direction) self.canvas.draw() return True def get_filechooser(self): if gtk.pygtk_version >= (2,4,0): return FileChooserDialog( title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) else: return FileSelection(title='Save the figure', parent=self.win) def save_figure(self, button): fname, format = self.get_filechooser().get_filename_from_user() if fname: try: self.canvas.print_figure(fname, format=format) except Exception, e: error_msg_gtk(str(e), parent=self) if gtk.pygtk_version >= (2,4,0): class FileChooserDialog(gtk.FileChooserDialog): """GTK+ 2.4 file selector which remembers the last file/directory selected and presents the user with a menu of supported image formats """ def __init__ (self, title = 'Save file', parent = None, action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), path = None, filetypes = [], default_filetype = None ): super (FileChooserDialog, self).__init__ (title, parent, action, buttons) self.set_default_response (gtk.RESPONSE_OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = gtk.HBox (spacing=10) hbox.pack_start (gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start (cbox) self.filetypes = filetypes self.sorted_filetypes = filetypes.items() self.sorted_filetypes.sort() default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): cbox.append_text ("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name (filename) cbox.connect ("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox) def get_filename_from_user (self): while True: filename = None if self.run() != int(gtk.RESPONSE_OK): break filename = self.get_filename() break self.hide() return filename, self.ext else: class FileSelection(gtk.FileSelection): """GTK+ 2.2 and lower file selector which remembers the last file/directory selected """ def __init__(self, path=None, title='Select a file', parent=None): super(FileSelection, self).__init__(title) if path: self.path = path else: self.path = os.getcwd() + os.sep if parent: self.set_transient_for(parent) def get_filename_from_user(self, path=None, title=None): if path: self.path = path if title: self.set_title(title) self.set_filename(self.path) filename = None if self.run() == int(gtk.RESPONSE_OK): self.path = filename = self.get_filename() self.hide() ext = None if filename is not None: ext = os.path.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] return filename, ext class DialogLineprops: """ A GUI dialog for controlling lineprops """ signals = ( 'on_combobox_lineprops_changed', 'on_combobox_linestyle_changed', 'on_combobox_marker_changed', 'on_colorbutton_linestyle_color_set', 'on_colorbutton_markerface_color_set', 'on_dialog_lineprops_okbutton_clicked', 'on_dialog_lineprops_cancelbutton_clicked', ) linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()] linestyled = dict([ (s,i) for i,s in enumerate(linestyles)]) markers = [m for m in lines.Line2D.markers if cbook.is_string_like(m)] markerd = dict([(s,i) for i,s in enumerate(markers)]) def __init__(self, lines): import gtk.glade datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): raise IOError('Could not find gladefile lineprops.glade in %s'%datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') self.wtree.signal_autoconnect(dict([(s, getattr(self, s)) for s in self.signals])) self.dlg = self.wtree.get_widget('dialog_lineprops') self.lines = lines cbox = self.wtree.get_widget('combobox_lineprops') cbox.set_active(0) self.cbox_lineprops = cbox cbox = self.wtree.get_widget('combobox_linestyles') for ls in self.linestyles: cbox.append_text(ls) cbox.set_active(0) self.cbox_linestyles = cbox cbox = self.wtree.get_widget('combobox_markers') for m in self.markers: cbox.append_text(m) cbox.set_active(0) self.cbox_markers = cbox self._lastcnt = 0 self._inited = True def show(self): 'populate the combo box' self._updateson = False # flush the old cbox = self.cbox_lineprops for i in range(self._lastcnt-1,-1,-1): cbox.remove_text(i) # add the new for line in self.lines: cbox.append_text(line.get_label()) cbox.set_active(0) self._updateson = True self._lastcnt = len(self.lines) self.dlg.show() def get_active_line(self): 'get the active line' ind = self.cbox_lineprops.get_active() line = self.lines[ind] return line def get_active_linestyle(self): 'get the active lineinestyle' ind = self.cbox_linestyles.get_active() ls = self.linestyles[ind] return ls def get_active_marker(self): 'get the active lineinestyle' ind = self.cbox_markers.get_active() m = self.markers[ind] return m def _update(self): 'update the active line props from the widgets' if not self._inited or not self._updateson: return line = self.get_active_line() ls = self.get_active_linestyle() marker = self.get_active_marker() line.set_linestyle(ls) line.set_marker(marker) button = self.wtree.get_widget('colorbutton_linestyle') color = button.get_color() r, g, b = [val/65535. for val in color.red, color.green, color.blue] line.set_color((r,g,b)) button = self.wtree.get_widget('colorbutton_markerface') color = button.get_color() r, g, b = [val/65535. for val in color.red, color.green, color.blue] line.set_markerfacecolor((r,g,b)) line.figure.canvas.draw() def on_combobox_lineprops_changed(self, item): 'update the widgets from the active line' if not self._inited: return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if ls is None: ls = 'None' self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if marker is None: marker = 'None' self.cbox_markers.set_active(self.markerd[marker]) r,g,b = colorConverter.to_rgb(line.get_color()) color = gtk.gdk.Color(*[int(val*65535) for val in r,g,b]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) r,g,b = colorConverter.to_rgb(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val*65535) for val in r,g,b]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True def on_combobox_linestyle_changed(self, item): self._update() def on_combobox_marker_changed(self, item): self._update() def on_colorbutton_linestyle_color_set(self, button): self._update() def on_colorbutton_markerface_color_set(self, button): 'called colorbutton marker clicked' self._update() def on_dialog_lineprops_okbutton_clicked(self, button): self._update() self.dlg.hide() def on_dialog_lineprops_cancelbutton_clicked(self, button): self.dlg.hide() # set icon used when windows are minimized # Unfortunately, the SVG renderer (rsvg) leaks memory under earlier # versions of pygtk, so we have to use a PNG file instead. try: if gtk.pygtk_version < (2, 8, 0): icon_filename = 'matplotlib.png' else: icon_filename = 'matplotlib.svg' gtk.window_set_default_icon_from_file ( os.path.join (matplotlib.rcParams['datapath'], 'images', icon_filename)) except: verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1]) def error_msg_gtk(msg, parent=None): if parent is not None: # find the toplevel gtk.Window parent = parent.get_toplevel() if parent.flags() & gtk.TOPLEVEL == 0: parent = None if not is_string_like(msg): msg = ','.join(map(str,msg)) dialog = gtk.MessageDialog( parent = parent, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = msg) dialog.run() dialog.destroy() FigureManager = FigureManagerGTK
43,991
Python
.py
1,045
31.34067
166
0.575965
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,321
backend_cairo.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_cairo.py
""" A Cairo backend for matplotlib Author: Steve Chaplin Cairo is a vector graphics library with cross-device output support. Features of Cairo: * anti-aliasing * alpha channel * saves image files as PNG, PostScript, PDF http://cairographics.org Requires (in order, all available from Cairo website): cairo, pycairo Naming Conventions * classes MixedUpperCase * varables lowerUpper * functions underscore_separated """ from __future__ import division import os, sys, warnings, gzip import numpy as npy def _fn_name(): return sys._getframe(1).f_code.co_name try: import cairo except ImportError: raise ImportError("Cairo backend requires that pycairo is installed.") _version_required = (1,2,0) if cairo.version_info < _version_required: raise ImportError ("Pycairo %d.%d.%d is installed\n" "Pycairo %d.%d.%d or later is required" % (cairo.version_info + _version_required)) backend_version = cairo.version del _version_required from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.cbook import is_string_like from matplotlib.figure import Figure from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Bbox, Affine2D from matplotlib.font_manager import ttfFontProperty from matplotlib import rcParams _debug = False #_debug = True # Image::color_conv(format) for draw_image() if sys.byteorder == 'little': BYTE_FORMAT = 0 # BGRA else: BYTE_FORMAT = 1 # ARGB class RendererCairo(RendererBase): fontweights = { 100 : cairo.FONT_WEIGHT_NORMAL, 200 : cairo.FONT_WEIGHT_NORMAL, 300 : cairo.FONT_WEIGHT_NORMAL, 400 : cairo.FONT_WEIGHT_NORMAL, 500 : cairo.FONT_WEIGHT_NORMAL, 600 : cairo.FONT_WEIGHT_BOLD, 700 : cairo.FONT_WEIGHT_BOLD, 800 : cairo.FONT_WEIGHT_BOLD, 900 : cairo.FONT_WEIGHT_BOLD, 'ultralight' : cairo.FONT_WEIGHT_NORMAL, 'light' : cairo.FONT_WEIGHT_NORMAL, 'normal' : cairo.FONT_WEIGHT_NORMAL, 'medium' : cairo.FONT_WEIGHT_NORMAL, 'semibold' : cairo.FONT_WEIGHT_BOLD, 'bold' : cairo.FONT_WEIGHT_BOLD, 'heavy' : cairo.FONT_WEIGHT_BOLD, 'ultrabold' : cairo.FONT_WEIGHT_BOLD, 'black' : cairo.FONT_WEIGHT_BOLD, } fontangles = { 'italic' : cairo.FONT_SLANT_ITALIC, 'normal' : cairo.FONT_SLANT_NORMAL, 'oblique' : cairo.FONT_SLANT_OBLIQUE, } def __init__(self, dpi): """ """ if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) self.dpi = dpi self.text_ctx = cairo.Context ( cairo.ImageSurface (cairo.FORMAT_ARGB32,1,1)) self.mathtext_parser = MathTextParser('Cairo') def set_ctx_from_surface (self, surface): self.ctx = cairo.Context (surface) self.ctx.save() # restore, save - when call new_gc() def set_width_height(self, width, height): self.width = width self.height = height self.matrix_flipy = cairo.Matrix (yy=-1, y0=self.height) # use matrix_flipy for ALL rendering? # - problem with text? - will need to switch matrix_flipy off, or do a # font transform? def _fill_and_stroke (self, ctx, fill_c, alpha): if fill_c is not None: ctx.save() if len(fill_c) == 3: ctx.set_source_rgba (fill_c[0], fill_c[1], fill_c[2], alpha) else: ctx.set_source_rgba (fill_c[0], fill_c[1], fill_c[2], alpha*fill_c[3]) ctx.fill_preserve() ctx.restore() ctx.stroke() #@staticmethod def convert_path(ctx, tpath): for points, code in tpath.iter_segments(): if code == Path.MOVETO: ctx.move_to(*points) elif code == Path.LINETO: ctx.line_to(*points) elif code == Path.CURVE3: ctx.curve_to(points[0], points[1], points[0], points[1], points[2], points[3]) elif code == Path.CURVE4: ctx.curve_to(*points) elif code == Path.CLOSEPOLY: ctx.close_path() convert_path = staticmethod(convert_path) def draw_path(self, gc, path, transform, rgbFace=None): if len(path.vertices) > 18980: raise ValueError("The Cairo backend can not draw paths longer than 18980 points.") ctx = gc.ctx transform = transform + \ Affine2D().scale(1.0, -1.0).translate(0, self.height) tpath = transform.transform_path(path) ctx.new_path() self.convert_path(ctx, tpath) self._fill_and_stroke(ctx, rgbFace, gc.get_alpha()) def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # bbox - not currently used if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) im.flipud_out() rows, cols, buf = im.color_conv (BYTE_FORMAT) surface = cairo.ImageSurface.create_for_data ( buf, cairo.FORMAT_ARGB32, cols, rows, cols*4) # function does not pass a 'gc' so use renderer.ctx ctx = self.ctx y = self.height - y - rows ctx.set_source_surface (surface, x, y) ctx.paint() im.flipud_out() def draw_text(self, gc, x, y, s, prop, angle, ismath=False): # Note: x,y are device/display coords, not user-coords, unlike other # draw_* methods if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: ctx = gc.ctx ctx.new_path() ctx.move_to (x, y) ctx.select_font_face (prop.get_name(), self.fontangles [prop.get_style()], self.fontweights[prop.get_weight()]) size = prop.get_size_in_points() * self.dpi / 72.0 ctx.save() if angle: ctx.rotate (-angle * npy.pi / 180) ctx.set_font_size (size) ctx.show_text (s.encode("utf-8")) ctx.restore() def _draw_mathtext(self, gc, x, y, s, prop, angle): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) ctx = gc.ctx width, height, descent, glyphs, rects = self.mathtext_parser.parse( s, self.dpi, prop) ctx.save() ctx.translate(x, y) if angle: ctx.rotate (-angle * npy.pi / 180) for font, fontsize, s, ox, oy in glyphs: ctx.new_path() ctx.move_to(ox, oy) fontProp = ttfFontProperty(font) ctx.save() ctx.select_font_face (fontProp.name, self.fontangles [fontProp.style], self.fontweights[fontProp.weight]) size = fontsize * self.dpi / 72.0 ctx.set_font_size(size) ctx.show_text(s.encode("utf-8")) ctx.restore() for ox, oy, w, h in rects: ctx.new_path() ctx.rectangle (ox, oy, w, h) ctx.set_source_rgb (0, 0, 0) ctx.fill_preserve() ctx.restore() def flipy(self): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) return True #return False # tried - all draw objects ok except text (and images?) # which comes out mirrored! def get_canvas_width_height(self): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) if ismath: width, height, descent, fonts, used_characters = self.mathtext_parser.parse( s, self.dpi, prop) return width, height, descent ctx = self.text_ctx ctx.save() ctx.select_font_face (prop.get_name(), self.fontangles [prop.get_style()], self.fontweights[prop.get_weight()]) # Cairo (says it) uses 1/96 inch user space units, ref: cairo_gstate.c # but if /96.0 is used the font is too small size = prop.get_size_in_points() * self.dpi / 72.0 # problem - scale remembers last setting and font can become # enormous causing program to crash # save/restore prevents the problem ctx.set_font_size (size) y_bearing, w, h = ctx.text_extents (s)[1:4] ctx.restore() return w, h, h + y_bearing def new_gc(self): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) self.ctx.restore() # matches save() in set_ctx_from_surface() self.ctx.save() return GraphicsContextCairo (renderer=self) def points_to_pixels(self, points): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) return points/72.0 * self.dpi class GraphicsContextCairo(GraphicsContextBase): _joind = { 'bevel' : cairo.LINE_JOIN_BEVEL, 'miter' : cairo.LINE_JOIN_MITER, 'round' : cairo.LINE_JOIN_ROUND, } _capd = { 'butt' : cairo.LINE_CAP_BUTT, 'projecting' : cairo.LINE_CAP_SQUARE, 'round' : cairo.LINE_CAP_ROUND, } def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer self.ctx = renderer.ctx def set_alpha(self, alpha): self._alpha = alpha rgb = self._rgb self.ctx.set_source_rgba (rgb[0], rgb[1], rgb[2], alpha) #def set_antialiased(self, b): # enable/disable anti-aliasing is not (yet) supported by Cairo def set_capstyle(self, cs): if cs in ('butt', 'round', 'projecting'): self._capstyle = cs self.ctx.set_line_cap (self._capd[cs]) else: raise ValueError('Unrecognized cap style. Found %s' % cs) def set_clip_rectangle(self, rectangle): self._cliprect = rectangle if rectangle is None: return x,y,w,h = rectangle.bounds # pixel-aligned clip-regions are faster x,y,w,h = round(x), round(y), round(w), round(h) ctx = self.ctx ctx.new_path() ctx.rectangle (x, self.renderer.height - h - y, w, h) ctx.clip () # Alternative: just set _cliprect here and actually set cairo clip rect # in fill_and_stroke() inside ctx.save() ... ctx.restore() def set_clip_path(self, path): if path is not None: tpath, affine = path.get_transformed_path_and_affine() ctx = self.ctx ctx.new_path() affine = affine + Affine2D().scale(1.0, -1.0).translate(0.0, self.renderer.height) tpath = affine.transform_path(tpath) RendererCairo.convert_path(ctx, tpath) ctx.clip() def set_dashes(self, offset, dashes): self._dashes = offset, dashes if dashes == None: self.ctx.set_dash([], 0) # switch dashes off else: self.ctx.set_dash ( self.renderer.points_to_pixels (npy.asarray(dashes)), offset) def set_foreground(self, fg, isRGB=None): GraphicsContextBase.set_foreground(self, fg, isRGB) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb) def set_graylevel(self, frac): GraphicsContextBase.set_graylevel(self, frac) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb) def set_joinstyle(self, js): if js in ('miter', 'round', 'bevel'): self._joinstyle = js self.ctx.set_line_join(self._joind[js]) else: raise ValueError('Unrecognized join style. Found %s' % js) def set_linewidth(self, w): self._linewidth = w self.ctx.set_line_width (self.renderer.points_to_pixels(w)) def new_figure_manager(num, *args, **kwargs): # called by backends/__init__.py """ Create a new figure manager instance """ if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasCairo(thisFig) manager = FigureManagerBase(canvas, num) return manager class FigureCanvasCairo (FigureCanvasBase): def print_png(self, fobj, *args, **kwargs): width, height = self.get_width_height() renderer = RendererCairo (self.figure.dpi) renderer.set_width_height (width, height) surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height) renderer.set_ctx_from_surface (surface) self.figure.draw (renderer) surface.write_to_png (fobj) def print_pdf(self, fobj, *args, **kwargs): return self._save(fobj, 'pdf', *args, **kwargs) def print_ps(self, fobj, *args, **kwargs): return self._save(fobj, 'ps', *args, **kwargs) def print_svg(self, fobj, *args, **kwargs): return self._save(fobj, 'svg', *args, **kwargs) def print_svgz(self, fobj, *args, **kwargs): return self._save(fobj, 'svgz', *args, **kwargs) def get_default_filetype(self): return rcParams['cairo.format'] def _save (self, fo, format, **kwargs): # save PDF/PS/SVG orientation = kwargs.get('orientation', 'portrait') dpi = 72 self.figure.dpi = dpi w_in, h_in = self.figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = (height_in_points, width_in_points) if format == 'ps': if not cairo.HAS_PS_SURFACE: raise RuntimeError ('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface (fo, width_in_points, height_in_points) elif format == 'pdf': if not cairo.HAS_PDF_SURFACE: raise RuntimeError ('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface (fo, width_in_points, height_in_points) elif format in ('svg', 'svgz'): if not cairo.HAS_SVG_SURFACE: raise RuntimeError ('cairo has not been compiled with SVG ' 'support enabled') if format == 'svgz': filename = fo if is_string_like(fo): fo = open(fo, 'wb') fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface (fo, width_in_points, height_in_points) else: warnings.warn ("unknown format: %s" % format) return # surface.set_dpi() can be used renderer = RendererCairo (self.figure.dpi) renderer.set_width_height (width_in_points, height_in_points) renderer.set_ctx_from_surface (surface) ctx = renderer.ctx if orientation == 'landscape': ctx.rotate (npy.pi/2) ctx.translate (0, -height_in_points) # cairo/src/cairo_ps_surface.c # '%%Orientation: Portrait' is always written to the file header # '%%Orientation: Landscape' would possibly cause problems # since some printers would rotate again ? # TODO: # add portrait/landscape checkbox to FileChooser self.figure.draw (renderer) show_fig_border = False # for testing figure orientation and scaling if show_fig_border: ctx.new_path() ctx.rectangle(0, 0, width_in_points, height_in_points) ctx.set_line_width(4.0) ctx.set_source_rgb(1,0,0) ctx.stroke() ctx.move_to(30,30) ctx.select_font_face ('sans-serif') ctx.set_font_size(20) ctx.show_text('Origin corner') ctx.show_page() surface.finish()
16,706
Python
.py
391
32.754476
94
0.574954
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,322
backend_gtkcairo.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_gtkcairo.py
""" GTK+ Matplotlib interface using cairo (not GDK) drawing operations. Author: Steve Chaplin """ import gtk if gtk.pygtk_version < (2,7,0): import cairo.gtk from matplotlib.backends import backend_cairo from matplotlib.backends.backend_gtk import * backend_version = 'PyGTK(%d.%d.%d) ' % gtk.pygtk_version + \ 'Pycairo(%s)' % backend_cairo.backend_version _debug = False #_debug = True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ if _debug: print 'backend_gtkcairo.%s()' % fn_name() FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGTKCairo(thisFig) return FigureManagerGTK(canvas, num) class RendererGTKCairo (backend_cairo.RendererCairo): if gtk.pygtk_version >= (2,7,0): def set_pixmap (self, pixmap): self.ctx = pixmap.cairo_create() self.ctx.save() # restore, save - when call new_gc() else: def set_pixmap (self, pixmap): self.ctx = cairo.gtk.gdk_cairo_create (pixmap) self.ctx.save() # restore, save - when call new_gc() class FigureCanvasGTKCairo(backend_cairo.FigureCanvasCairo, FigureCanvasGTK): filetypes = FigureCanvasGTK.filetypes.copy() filetypes.update(backend_cairo.FigureCanvasCairo.filetypes) def _renderer_init(self): """Override to use cairo (rather than GDK) renderer""" if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) self._renderer = RendererGTKCairo (self.figure.dpi) class FigureManagerGTKCairo(FigureManagerGTK): def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar']=='classic': toolbar = NavigationToolbar (canvas, self.window) elif matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2GTKCairo (canvas, self.window) else: toolbar = None return toolbar class NavigationToolbar2Cairo(NavigationToolbar2GTK): def _get_canvas(self, fig): return FigureCanvasGTKCairo(fig)
2,207
Python
.py
52
36.115385
77
0.678037
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,323
backend_qt4.py
numenta_nupic-legacy/external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_qt4.py
from __future__ import division import math import os import sys import matplotlib from matplotlib import verbose from matplotlib.cbook import is_string_like, onetrue from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, IdleEvent, cursors from matplotlib._pylab_helpers import Gcf from matplotlib.figure import Figure from matplotlib.mathtext import MathTextParser from matplotlib.widgets import SubplotTool try: from PyQt4 import QtCore, QtGui, Qt except ImportError: raise ImportError("Qt4 backend requires that PyQt4 is installed.") backend_version = "0.9.1" def fn_name(): return sys._getframe(1).f_code.co_name DEBUG = False cursord = { cursors.MOVE : QtCore.Qt.SizeAllCursor, cursors.HAND : QtCore.Qt.PointingHandCursor, cursors.POINTER : QtCore.Qt.ArrowCursor, cursors.SELECT_REGION : QtCore.Qt.CrossCursor, } def draw_if_interactive(): """ Is called after every pylab drawing command """ if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ if QtGui.QApplication.startingUp(): if DEBUG: print "Starting up QApplication" global qApp qApp = QtGui.QApplication( [" "] ) QtCore.QObject.connect( qApp, QtCore.SIGNAL( "lastWindowClosed()" ), qApp, QtCore.SLOT( "quit()" ) ) #remember that matplotlib created the qApp - will be used by show() _create_qApp.qAppCreatedHere = True _create_qApp.qAppCreatedHere = False def show(): """ Show all the figures and enter the qt main loop This should be the last line of your script """ for manager in Gcf.get_all_fig_managers(): manager.window.show() if DEBUG: print 'Inside show' figManager = Gcf.get_active() if figManager != None: figManager.canvas.draw() if _create_qApp.qAppCreatedHere: QtGui.qApp.exec_() def new_figure_manager( num, *args, **kwargs ): """ Create a new figure manager instance """ thisFig = Figure( *args, **kwargs ) canvas = FigureCanvasQT( thisFig ) manager = FigureManagerQT( canvas, num ) return manager class FigureCanvasQT( QtGui.QWidget, FigureCanvasBase ): keyvald = { QtCore.Qt.Key_Control : 'control', QtCore.Qt.Key_Shift : 'shift', QtCore.Qt.Key_Alt : 'alt', } # left 1, middle 2, right 3 buttond = {1:1, 2:3, 4:2} def __init__( self, figure ): if DEBUG: print 'FigureCanvasQt: ', figure _create_qApp() QtGui.QWidget.__init__( self ) FigureCanvasBase.__init__( self, figure ) self.figure = figure self.setMouseTracking( True ) # hide until we can test and fix #self.startTimer(backend_IdleEvent.milliseconds) w,h = self.get_width_height() self.resize( w, h ) def __timerEvent(self, event): # hide until we can test and fix self.mpl_idle_event(event) def enterEvent(self, event): FigureCanvasBase.enter_notify_event(self, event) def leaveEvent(self, event): FigureCanvasBase.leave_notify_event(self, event) def mousePressEvent( self, event ): x = event.pos().x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.pos().y() button = self.buttond[event.button()] FigureCanvasBase.button_press_event( self, x, y, button ) if DEBUG: print 'button pressed:', event.button() def mouseMoveEvent( self, event ): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() FigureCanvasBase.motion_notify_event( self, x, y ) #if DEBUG: print 'mouse move' def mouseReleaseEvent( self, event ): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() button = self.buttond[event.button()] FigureCanvasBase.button_release_event( self, x, y, button ) if DEBUG: print 'button released' def keyPressEvent( self, event ): key = self._get_key( event ) FigureCanvasBase.key_press_event( self, key ) if DEBUG: print 'key press', key def keyReleaseEvent( self, event ): key = self._get_key(event) FigureCanvasBase.key_release_event( self, key ) if DEBUG: print 'key release', key def resizeEvent( self, event ): if DEBUG: print 'resize (%d x %d)' % (event.size().width(), event.size().height()) QtGui.QWidget.resizeEvent( self, event ) w = event.size().width() h = event.size().height() if DEBUG: print "FigureCanvasQtAgg.resizeEvent(", w, ",", h, ")" dpival = self.figure.dpi winch = w/dpival hinch = h/dpival self.figure.set_size_inches( winch, hinch ) self.draw() def resize( self, w, h ): # Pass through to Qt to resize the widget. QtGui.QWidget.resize( self, w, h ) # Resize the figure by converting pixels to inches. pixelPerInch = self.figure.dpi wInch = w / pixelPerInch hInch = h / pixelPerInch self.figure.set_size_inches( wInch, hInch ) # Redraw everything. self.draw() def sizeHint( self ): w, h = self.get_width_height() return QtCore.QSize( w, h ) def minumumSizeHint( self ): return QtCore.QSize( 10, 10 ) def _get_key( self, event ): if event.key() < 256: key = str(event.text()) elif event.key() in self.keyvald: key = self.keyvald[ event.key() ] else: key = None return key def flush_events(self): Qt.qApp.processEvents() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerQT( FigureManagerBase ): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The qt.QToolBar window : The qt.QMainWindow """ def __init__( self, canvas, num ): if DEBUG: print 'FigureManagerQT.%s' % fn_name() FigureManagerBase.__init__( self, canvas, num ) self.canvas = canvas self.window = QtGui.QMainWindow() self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.window.setWindowTitle("Figure %d" % num) image = os.path.join( matplotlib.rcParams['datapath'],'images','matplotlib.png' ) self.window.setWindowIcon(QtGui.QIcon( image )) # Give the keyboard focus to the figure instead of the manager self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus ) self.canvas.setFocus() QtCore.QObject.connect( self.window, QtCore.SIGNAL( 'destroyed()' ), self._widgetclosed ) self.window._destroying = False self.toolbar = self._get_toolbar(self.canvas, self.window) self.window.addToolBar(self.toolbar) QtCore.QObject.connect(self.toolbar, QtCore.SIGNAL("message"), self.window.statusBar().showMessage) self.window.setCentralWidget(self.canvas) if matplotlib.is_interactive(): self.window.show() # attach a show method to the figure for pylab ease of use self.canvas.figure.show = lambda *args: self.window.show() def notify_axes_change( fig ): # This will be called whenever the current axes is changed if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver( notify_axes_change ) def _widgetclosed( self ): if self.window._destroying: return self.window._destroying = True Gcf.destroy(self.num) def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'classic': print "Classic toolbar is not supported" elif matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent, False) else: toolbar = None return toolbar def resize(self, width, height): 'set the canvas size in pixels' self.window.resize(width, height) def destroy( self, *args ): if self.window._destroying: return self.window._destroying = True QtCore.QObject.disconnect( self.window, QtCore.SIGNAL( 'destroyed()' ), self._widgetclosed ) if self.toolbar: self.toolbar.destroy() if DEBUG: print "destroy figure manager" self.window.close() def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT( NavigationToolbar2, QtGui.QToolBar ): def __init__(self, canvas, parent, coordinates=True): """ coordinates: should we show the coordinates on the right? """ self.canvas = canvas self.coordinates = coordinates QtGui.QToolBar.__init__( self, parent ) NavigationToolbar2.__init__( self, canvas ) def _icon(self, name): return QtGui.QIcon(os.path.join(self.basedir, name)) def _init_toolbar(self): self.basedir = os.path.join(matplotlib.rcParams[ 'datapath' ],'images') a = self.addAction(self._icon('home.svg'), 'Home', self.home) a.setToolTip('Reset original view') a = self.addAction(self._icon('back.svg'), 'Back', self.back) a.setToolTip('Back to previous view') a = self.addAction(self._icon('forward.svg'), 'Forward', self.forward) a.setToolTip('Forward to next view') self.addSeparator() a = self.addAction(self._icon('move.svg'), 'Pan', self.pan) a.setToolTip('Pan axes with left mouse, zoom with right') a = self.addAction(self._icon('zoom_to_rect.svg'), 'Zoom', self.zoom) a.setToolTip('Zoom to rectangle') self.addSeparator() a = self.addAction(self._icon('subplots.png'), 'Subplots', self.configure_subplots) a.setToolTip('Configure subplots') a = self.addAction(self._icon('filesave.svg'), 'Save', self.save_figure) a.setToolTip('Save the figure') self.buttons = {} # Add the x,y location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. if self.coordinates: self.locLabel = QtGui.QLabel( "", self ) self.locLabel.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignTop ) self.locLabel.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) # reference holder for subplots_adjust window self.adj_window = None def dynamic_update( self ): self.canvas.draw() def set_message( self, s ): self.emit(QtCore.SIGNAL("message"), s) if self.coordinates: self.locLabel.setText(s.replace(', ', '\n')) def set_cursor( self, cursor ): if DEBUG: print 'Set cursor' , cursor QtGui.QApplication.restoreOverrideCursor() QtGui.QApplication.setOverrideCursor( QtGui.QCursor( cursord[cursor] ) ) def draw_rubberband( self, event, x0, y0, x1, y1 ): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [ int(val)for val in min(x0,x1), min(y0, y1), w, h ] self.canvas.drawRectangle( rect ) def configure_subplots(self): self.adj_window = QtGui.QMainWindow() win = self.adj_window win.setAttribute(QtCore.Qt.WA_DeleteOnClose) win.setWindowTitle("Subplot Configuration Tool") image = os.path.join( matplotlib.rcParams['datapath'],'images','matplotlib.png' ) win.setWindowIcon(QtGui.QIcon( image )) tool = SubplotToolQt(self.canvas.figure, win) win.setCentralWidget(tool) win.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) win.show() def _get_canvas(self, fig): return FigureCanvasQT(fig) def save_figure( self ): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() default_filetype = self.canvas.get_default_filetype() start = "image." + default_filetype filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname = QtGui.QFileDialog.getSaveFileName( self, "Choose a filename to save to", start, filters, selectedFilter) if fname: try: self.canvas.print_figure( unicode(fname) ) except Exception, e: QtGui.QMessageBox.critical( self, "Error saving file", str(e), QtGui.QMessageBox.Ok, QtGui.QMessageBox.NoButton) class SubplotToolQt( SubplotTool, QtGui.QWidget ): def __init__(self, targetfig, parent): QtGui.QWidget.__init__(self, None) self.targetfig = targetfig self.parent = parent self.sliderleft = QtGui.QSlider(QtCore.Qt.Horizontal) self.sliderbottom = QtGui.QSlider(QtCore.Qt.Vertical) self.sliderright = QtGui.QSlider(QtCore.Qt.Horizontal) self.slidertop = QtGui.QSlider(QtCore.Qt.Vertical) self.sliderwspace = QtGui.QSlider(QtCore.Qt.Horizontal) self.sliderhspace = QtGui.QSlider(QtCore.Qt.Vertical) # constraints QtCore.QObject.connect( self.sliderleft, QtCore.SIGNAL( "valueChanged(int)" ), self.sliderright.setMinimum ) QtCore.QObject.connect( self.sliderright, QtCore.SIGNAL( "valueChanged(int)" ), self.sliderleft.setMaximum ) QtCore.QObject.connect( self.sliderbottom, QtCore.SIGNAL( "valueChanged(int)" ), self.slidertop.setMinimum ) QtCore.QObject.connect( self.slidertop, QtCore.SIGNAL( "valueChanged(int)" ), self.sliderbottom.setMaximum ) sliders = (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop, self.sliderwspace, self.sliderhspace, ) adjustments = ('left:', 'bottom:', 'right:', 'top:', 'wspace:', 'hspace:') for slider, adjustment in zip(sliders, adjustments): slider.setMinimum(0) slider.setMaximum(1000) slider.setSingleStep(5) layout = QtGui.QGridLayout() leftlabel = QtGui.QLabel('left') layout.addWidget(leftlabel, 2, 0) layout.addWidget(self.sliderleft, 2, 1) toplabel = QtGui.QLabel('top') layout.addWidget(toplabel, 0, 2) layout.addWidget(self.slidertop, 1, 2) layout.setAlignment(self.slidertop, QtCore.Qt.AlignHCenter) bottomlabel = QtGui.QLabel('bottom') layout.addWidget(QtGui.QLabel('bottom'), 4, 2) layout.addWidget(self.sliderbottom, 3, 2) layout.setAlignment(self.sliderbottom, QtCore.Qt.AlignHCenter) rightlabel = QtGui.QLabel('right') layout.addWidget(rightlabel, 2, 4) layout.addWidget(self.sliderright, 2, 3) hspacelabel = QtGui.QLabel('hspace') layout.addWidget(hspacelabel, 0, 6) layout.setAlignment(hspacelabel, QtCore.Qt.AlignHCenter) layout.addWidget(self.sliderhspace, 1, 6) layout.setAlignment(self.sliderhspace, QtCore.Qt.AlignHCenter) wspacelabel = QtGui.QLabel('wspace') layout.addWidget(wspacelabel, 4, 6) layout.setAlignment(wspacelabel, QtCore.Qt.AlignHCenter) layout.addWidget(self.sliderwspace, 3, 6) layout.setAlignment(self.sliderwspace, QtCore.Qt.AlignBottom) layout.setRowStretch(1,1) layout.setRowStretch(3,1) layout.setColumnStretch(1,1) layout.setColumnStretch(3,1) layout.setColumnStretch(6,1) self.setLayout(layout) self.sliderleft.setSliderPosition(int(targetfig.subplotpars.left*1000)) self.sliderbottom.setSliderPosition(\ int(targetfig.subplotpars.bottom*1000)) self.sliderright.setSliderPosition(\ int(targetfig.subplotpars.right*1000)) self.slidertop.setSliderPosition(int(targetfig.subplotpars.top*1000)) self.sliderwspace.setSliderPosition(\ int(targetfig.subplotpars.wspace*1000)) self.sliderhspace.setSliderPosition(\ int(targetfig.subplotpars.hspace*1000)) QtCore.QObject.connect( self.sliderleft, QtCore.SIGNAL( "valueChanged(int)" ), self.funcleft ) QtCore.QObject.connect( self.sliderbottom, QtCore.SIGNAL( "valueChanged(int)" ), self.funcbottom ) QtCore.QObject.connect( self.sliderright, QtCore.SIGNAL( "valueChanged(int)" ), self.funcright ) QtCore.QObject.connect( self.slidertop, QtCore.SIGNAL( "valueChanged(int)" ), self.functop ) QtCore.QObject.connect( self.sliderwspace, QtCore.SIGNAL( "valueChanged(int)" ), self.funcwspace ) QtCore.QObject.connect( self.sliderhspace, QtCore.SIGNAL( "valueChanged(int)" ), self.funchspace ) def funcleft(self, val): if val == self.sliderright.value(): val -= 1 self.targetfig.subplots_adjust(left=val/1000.) if self.drawon: self.targetfig.canvas.draw() def funcright(self, val): if val == self.sliderleft.value(): val += 1 self.targetfig.subplots_adjust(right=val/1000.) if self.drawon: self.targetfig.canvas.draw() def funcbottom(self, val): if val == self.slidertop.value(): val -= 1 self.targetfig.subplots_adjust(bottom=val/1000.) if self.drawon: self.targetfig.canvas.draw() def functop(self, val): if val == self.sliderbottom.value(): val += 1 self.targetfig.subplots_adjust(top=val/1000.) if self.drawon: self.targetfig.canvas.draw() def funcwspace(self, val): self.targetfig.subplots_adjust(wspace=val/1000.) if self.drawon: self.targetfig.canvas.draw() def funchspace(self, val): self.targetfig.subplots_adjust(hspace=val/1000.) if self.drawon: self.targetfig.canvas.draw() def error_msg_qt( msg, parent=None ): if not is_string_like( msg ): msg = ','.join( map( str,msg ) ) QtGui.QMessageBox.warning( None, "Matplotlib", msg, QtGui.QMessageBox.Ok ) def exception_handler( type, value, tb ): """Handle uncaught exceptions It does not catch SystemExit """ msg = '' # get the filename attribute if available (for IOError) if hasattr(value, 'filename') and value.filename != None: msg = value.filename + ': ' if hasattr(value, 'strerror') and value.strerror != None: msg += value.strerror else: msg += str(value) if len( msg ) : error_msg_qt( msg ) FigureManager = FigureManagerQT
20,664
Python
.py
459
35.115468
90
0.621144
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,324
run_experiment_classifier_diff.py
numenta_nupic-legacy/scripts/run_experiment_classifier_diff.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """This script is a command-line client of Online Prediction Framework (OPF). It executes a single experiment and diffs the results for the SDRClassifier. """ import sys from nupic.algorithms.sdr_classifier_diff import SDRClassifierDiff from nupic.algorithms.sdr_classifier_factory import SDRClassifierFactory from nupic.frameworks.opf.experiment_runner import (runExperiment, initExperimentPrng) from nupic.support import initLogging def main(): """Run according to options in sys.argv and diff classifiers.""" initLogging(verbose=True) # Initialize PRNGs initExperimentPrng() # Mock out the creation of the SDRClassifier. @staticmethod def _mockCreate(*args, **kwargs): kwargs.pop('implementation', None) return SDRClassifierDiff(*args, **kwargs) SDRClassifierFactory.create = _mockCreate # Run it! runExperiment(sys.argv[1:]) if __name__ == "__main__": main()
1,933
Python
.py
44
40.795455
77
0.702184
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,325
run_opf_experiment.py
numenta_nupic-legacy/scripts/run_opf_experiment.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """This script is a command-line client of Online Prediction Framework (OPF). It executes a single experiment. """ from nupic.frameworks.opf.experiment_runner import main if __name__ == "__main__": main()
1,188
Python
.py
26
44.423077
77
0.678479
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,326
run_nupic_tests.py
numenta_nupic-legacy/scripts/run_nupic_tests.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import os import sys from subprocess import call from optparse import OptionParser from datetime import datetime from pkg_resources import ( DistributionNotFound, get_distribution ) try: pytestXdistAvailable = bool(get_distribution("pytest-xdist")) except DistributionNotFound: print "ERROR: `pytest-xdist` is not installed. Certain testing features" \ " are not available without it. The complete list of python" \ " requirements can be found in requirements.txt." sys.exit(1) def collect_set(option, opt_str, value, parser): """ Collect multiple option values into a single set. Used in conjunction with callback argument to OptionParser.add_option(). """ assert value is None value = set([]) for arg in parser.rargs: if arg[:1] == "-": break value.add(arg) del parser.rargs[:len(value)] setattr(parser.values, option.dest, value) def collect_list(option, opt_str, value, parser): """ Collect multiple option values into a single list. Used in conjunction with callback argument to OptionParser.add_option(). """ assert value is None value = [] for arg in parser.rargs: if arg[:1] == "-": break value.append(arg) del parser.rargs[:len(value)] setattr(parser.values, option.dest, value) parser = OptionParser(usage="%prog [options]\n\nRun NuPIC Python tests.") parser.add_option( "-a", "--all", action="store_true", default=False, dest="all") parser.add_option( "-c", "--coverage", action="store_true", default=False, dest="coverage") parser.add_option( "-m", "--filtermarks", dest="markexpresson", help="Expression for filtering tests by tags that were used to mark the " "test classes and/or methods; presently, 'tag' or 'not tag' are " "supported; e.g., 'not clusterExclusive'") parser.add_option( "-i", "--integration", action="store_true", default=False, dest="integration") parser.add_option( "-w", "--swarming", action="store_true", default=False, dest="swarming") parser.add_option( "-n", "--num", dest="processes") parser.add_option( "-r", "--results", dest="results", action="callback", callback=collect_list) parser.add_option( "-s", dest="tests", action="callback", callback=collect_set) parser.add_option( "-u", "--unit", action="store_true", default=False, dest="unit") parser.add_option( "-x", "--failfast", action="store_true", default=False, dest="failfast") def main(parser, parse_args): """ Parse CLI options and execute tests """ # Default to success, failures will flip it. exitStatus = 0 # Extensions to test spec (args not part of official test runner) parser.add_option( "-t", "--testlist", action="callback", callback=collect_set, dest="testlist_file", help="Test list file, specifying tests (one per line)") parser.add_option( "-v", "--verbose", action="store_true", dest="verbose") # Parse CLI args (options, tests) = parser.parse_args(args=parse_args) tests = set(tests) # Translate spec args to py.test args args = [ "--boxed", # See https://pypi.python.org/pypi/pytest-xdist#boxed "--verbose" ] root = "tests" if options.coverage: args.append("--cov=nupic") if options.processes is not None: # See https://pypi.python.org/pypi/pytest-xdist#parallelization args.extend(["-n", options.processes]) if options.markexpresson is not None: args.extend(["-m", options.markexpresson]) if options.results is not None: results = options.results[:2] format = results.pop(0) if results: runid = results.pop(0) else: runid = datetime.now().strftime('%Y%m%d%H%M%S') results = os.path.join(root, "results", "xunit", str(runid)) try: os.makedirs(results) except os.error: pass args.append("--junitxml=" + os.path.join(results, "results.xml")) if options.tests is not None: tests.update(options.tests) if options.unit or options.all: tests.add(os.path.join(root, "unit")) if options.integration or options.all: tests.add(os.path.join(root, "integration")) if options.swarming or options.all: tests.add(os.path.join(root, "swarming")) if options.verbose: args.append("-v") if options.failfast: args.append("-x") if not tests or options.all: tests.add(os.path.join(root, "external")) tests.add(os.path.join(root, "unit")) # Run tests if options.testlist_file is not None: # Arbitrary test lists if options.testlist_file: testlist = options.testlist_file.pop() if testlist.endswith(".testlist"): testlist = [test.strip() for test in open(testlist).readlines()] else: testlist = options.testlist_file testlist.add(testlist) for test in testlist: specific_args = \ [ arg.replace("results.xml", test.replace("/", "_") + ".xml") if arg.startswith("--junitxml=") else arg for arg in args ] testStatus = call(["py.test"] + specific_args + [test]) # exitStatus defaults to 0, if any test returns non-0, we'll set it. if testStatus is not 0: exitStatus = testStatus else: # Standard tests exitStatus = call(["py.test"] + args + list(tests)) return exitStatus if __name__ == "__main__": # Tests need to run from $NUPIC, so let's change there and at the end back to actual_dir actual_dir=os.getcwd() os.chdir(os.getenv('NUPIC')) result = main(parser, sys.argv[1:]) os.chdir(actual_dir) sys.exit(result)
6,601
Python
.py
213
27.089202
90
0.672245
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,327
temporal_memory_performance_benchmark.py
numenta_nupic-legacy/scripts/temporal_memory_performance_benchmark.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014-2016, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Run various perf scenarios on the Temporal Memory. """ import argparse import csv import numpy import random import sys import time from pkg_resources import resource_filename from nupic.encoders.random_distributed_scalar import RandomDistributedScalarEncoder HOTGYM_PATH = resource_filename( "nupic.datafiles", "extra/hotgym/rec-center-hourly.csv" ) HOTGYM_LENGTH = 4391 def printProgressBar(completed, total, nDots): numberOfDots = lambda n: (n * nDots) // total completedDots = numberOfDots(completed) if completedDots != numberOfDots(completed - 1): print "\r|" + ("." * completedDots) + (" " * (nDots - completedDots)) + "|", sys.stdout.flush() def clearProgressBar(nDots): print "\r" + (" " * (nDots + 2)) class TemporalMemoryPerformanceBenchmark(object): def __init__(self): self.contestants = [] def addContestant(self, constructor, paramsFn, computeFn, name): c = (constructor, paramsFn, computeFn, name) self.contestants.append(c) def _createInstances(self, cellsPerColumn): instances = [] for i in xrange(len(self.contestants)): (constructor, paramsFn, computeFn, name) = self.contestants[i] params = paramsFn(cellsPerColumn=cellsPerColumn) tmInstance = constructor(**params) instances.append(tmInstance) return instances def runSimpleSequence(self, resets, repetitions=1): scalarEncoder = RandomDistributedScalarEncoder(0.88, n=2048, w=41) instances = self._createInstances(cellsPerColumn=32) times = [0.0] * len(self.contestants) duration = 10000 * repetitions increment = 4 sequenceLength = 25 sequence = (i % (sequenceLength * 4) for i in xrange(0, duration * increment, increment)) t = 0 encodedValue = numpy.zeros(2048, dtype=numpy.int32) for value in sequence: scalarEncoder.encodeIntoArray(value, output=encodedValue) activeBits = encodedValue.nonzero()[0] for i in xrange(len(self.contestants)): tmInstance = instances[i] computeFn = self.contestants[i][2] if resets: if value == 0: tmInstance.reset() start = time.clock() computeFn(tmInstance, encodedValue, activeBits) times[i] += time.clock() - start printProgressBar(t, duration, 50) t += 1 clearProgressBar(50) results = [] for i in xrange(len(self.contestants)): name = self.contestants[i][3] results.append((name, times[i],)) return results def runHotgym(self, cellsPerColumn, repetitions=1): scalarEncoder = RandomDistributedScalarEncoder(0.88, n=2048, w=41) instances = self._createInstances(cellsPerColumn=cellsPerColumn) times = [0.0] * len(self.contestants) t = 0 duration = HOTGYM_LENGTH * repetitions for _ in xrange(repetitions): with open(HOTGYM_PATH) as fin: reader = csv.reader(fin) reader.next() reader.next() reader.next() encodedValue = numpy.zeros(2048, dtype=numpy.uint32) for timeStr, valueStr in reader: value = float(valueStr) scalarEncoder.encodeIntoArray(value, output=encodedValue) activeBits = encodedValue.nonzero()[0] for i in xrange(len(self.contestants)): tmInstance = instances[i] computeFn = self.contestants[i][2] start = time.clock() computeFn(tmInstance, encodedValue, activeBits) times[i] += time.clock() - start printProgressBar(t, duration, 50) t += 1 clearProgressBar(50) results = [] for i in xrange(len(self.contestants)): name = self.contestants[i][3] results.append((name, times[i],)) return results def runRandom(self, repetitions=1): scalarEncoder = RandomDistributedScalarEncoder(0.88, n=2048, w=41) instances = self._createInstances(cellsPerColumn=32) times = [0.0] * len(self.contestants) duration = 1000 * repetitions t = 0 encodedValue = numpy.zeros(2048, dtype=numpy.int32) for _ in xrange(duration): activeBits = random.sample(xrange(2048), 40) encodedValue = numpy.zeros(2048, dtype=numpy.int32) encodedValue[activeBits] = 1 for i in xrange(len(self.contestants)): tmInstance = instances[i] computeFn = self.contestants[i][2] start = time.clock() computeFn(tmInstance, encodedValue, activeBits) times[i] += time.clock() - start printProgressBar(t, duration, 50) t += 1 clearProgressBar(50) results = [] for i in xrange(len(self.contestants)): name = self.contestants[i][3] results.append((name, times[i],)) return results # Some tests might change certain model parameters like cellsPerColumn. Add # other arguments to these paramsFns as we add tests that specify other params. def tmParamsFn(cellsPerColumn): return { "columnDimensions": [2048], "cellsPerColumn": cellsPerColumn, "initialPermanence": 0.5, "connectedPermanence": 0.8, "minThreshold": 10, "maxNewSynapseCount": 20, "permanenceIncrement": 0.1, "permanenceDecrement": 0.05, "activationThreshold": 13 } def backtrackingParamsFn(cellsPerColumn): return { "numberOfCols": 2048, "cellsPerColumn": cellsPerColumn, "initialPerm": 0.5, "connectedPerm": 0.8, "minThreshold": 10, "newSynapseCount": 20, "permanenceInc": 0.1, "permanenceDec": 0.05, "activationThreshold": 13, "globalDecay": 0, "burnIn": 1, "checkSynapseConsistency": False, "pamLength": 1, } def tmComputeFn(instance, encoding, activeBits): instance.compute(activeBits, learn=True) def backtrackingComputeFn(instance, encoding, activeBits): instance.compute(encoding, enableLearn=True, enableInference=True) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Run various perf scenarios on the Temporal Memory." ) implNames = ["tm_cpp", "tm_py", "tp_py", "tp_cpp"] testNames = ["simple_sequence", "simple_sequence_no_resets", "hotgym", "hotgym_1_cell", "random", "5_random", "20_simple_sequence", "20_simple_sequence_no_resets", "20_hotgym", "20_hotgym_1_cell"] defaultTests = ["simple_sequence", "simple_sequence_no_resets", "hotgym", "hotgym_1_cell", "random", "5_random"] parser.add_argument("-i", "--implementations", nargs="*", type=str, help=("Which temporal memory implementations to use. " + "Options: %s" % ", ".join(implNames)), default=["tm_cpp"]) parser.add_argument("-t", "--tests", nargs="*", type=str, help=("The tests to run. Options: %s" % ", ".join(testNames)), default=defaultTests) parser.add_argument("--pause", help="Pause before each test.", default=False, action="store_true") parser.add_argument("-o", "--output", help="Output CSV file", type=str, default=None) args = parser.parse_args() # Handle comma-seperated list argument. if len(args.implementations) == 1: args.implementations = args.implementations[0].split(",") if len(args.tests) == 1: args.tests = args.tests[0].split(",") benchmark = TemporalMemoryPerformanceBenchmark() if "tm_cpp" in args.implementations: import nupic.bindings.algorithms benchmark.addContestant( nupic.bindings.algorithms.TemporalMemory, paramsFn=tmParamsFn, computeFn=tmComputeFn, name="tm_cpp") if "tm_py" in args.implementations: import nupic.algorithms.temporal_memory benchmark.addContestant( nupic.algorithms.temporal_memory.TemporalMemory, paramsFn=tmParamsFn, computeFn=tmComputeFn, name="tm_py") if "tp_py" in args.implementations: import nupic.algorithms.backtracking_tm benchmark.addContestant( nupic.algorithms.backtracking_tm.BacktrackingTM, paramsFn=backtrackingParamsFn, computeFn=backtrackingComputeFn, name="tp_py") if "tp_cpp" in args.implementations: import nupic.algorithms.backtracking_tm_cpp benchmark.addContestant( nupic.algorithms.backtracking_tm_cpp.BacktrackingTMCPP, paramsFn=backtrackingParamsFn, computeFn=backtrackingComputeFn, name="tp_cpp") tests = ( ("simple_sequence", "simple repeating sequence", lambda: benchmark.runSimpleSequence(resets=True)), ("simple_sequence_no_resets", "simple repeating sequence (no resets)", lambda: benchmark.runSimpleSequence(resets=False)), ("20_simple_sequence", "simple repeating sequence, times 20", lambda: benchmark.runSimpleSequence(repetitions=20, resets=True)), ("20_simple_sequence_no_resets", "simple repeating sequence, times 20 (no resets)", lambda: benchmark.runSimpleSequence(repetitions=20, resets=False)), ("hotgym", "hotgym", lambda: benchmark.runHotgym(cellsPerColumn=32)), ("hotgym_1_cell", "hotgym (1 cell per column)", lambda: benchmark.runHotgym(cellsPerColumn=1)), ("20_hotgym", "hotgym, 20 times", lambda: benchmark.runHotgym(cellsPerColumn=32, repetitions=20)), ("20_hotgym_1_cell", "hotgym, 20 times (1 cell per column)", lambda: benchmark.runHotgym(cellsPerColumn=1, repetitions=20)), ("random", "random column SDRs", lambda: benchmark.runRandom(repetitions=1)), ("5_random", "random column SDRs, times 5", lambda: benchmark.runRandom(repetitions=5)), ) allResults = {} for name, description, testFn in tests: assert name not in allResults if name in args.tests: print "Test: %s" % description if args.pause: raw_input("Press enter to continue. ") results = testFn() allResults[name] = results for implDescription, t in sorted(results, key=lambda x: x[1]): print "%s: %fs" % (implDescription, t) print print if args.output is not None and len(allResults) > 0: print "Writing results to",args.output print with open(args.output, "wb") as csvFile: writer = csv.writer(csvFile) firstTestName, firstResults = allResults.iteritems().next() orderedImplNames = (implName for implName, t in firstResults) firstRow = ["test"] firstRow.extend(orderedImplNames) writer.writerow(firstRow) for testName, results in allResults.iteritems(): row = [testName] for implDescription, t in results: row.append(t) writer.writerow(row)
11,951
Python
.py
313
31.329073
83
0.655149
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,328
run_swarm.py
numenta_nupic-legacy/scripts/run_swarm.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ @file run_swarm.py This script is the command-line interface for running swarms in nupic.""" import sys import os import optparse import logging logging.basicConfig() from nupic.swarming import permutations_runner from nupic.swarming.permutations_runner import DEFAULT_OPTIONS def runPermutations(args): """ The main function of the RunPermutations utility. This utility will automatically generate and run multiple prediction framework experiments that are permutations of a base experiment via the Grok engine. For example, if you have an experiment that you want to test with 3 possible values of variable A and 2 possible values of variable B, this utility will automatically generate the experiment directories and description files for each of the 6 different experiments. Here is an example permutations file which is read by this script below. The permutations file must be in the same directory as the description.py for the base experiment that you want to permute. It contains a permutations dict, an optional list of the result items to report on for each experiment, and an optional result item to optimize for. When an 'optimize' entry is provided, this tool will attempt to prioritize the order in which the various permutations are run in order to improve the odds of running the best permutations sooner. It does this by watching the results for various parameter values and putting parameter values that give generally better results at the head of the queue. In addition, when the optimize key is provided, we periodically update the UI with the best results obtained so far on that metric. --------------------------------------------------------------------------- permutations = dict( iterationCount = [1000, 5000], coincCount = [50, 100], trainTP = [False], ) report = ['.*reconstructErrAvg', '.*inputPredScore.*', ] optimize = 'postProc_gym1_baseline:inputPredScore' Parameters: ---------------------------------------------------------------------- args: Command-line args; the equivalent of sys.argv[1:] retval: for the actions 'run', 'pickup', and 'dryRun', returns the Hypersearch job ID (in ClinetJobs table); otherwise returns None """ helpString = ( "\n\n%prog [options] permutationsScript\n" "%prog [options] expDescription.json\n\n" "This script runs permutations of an experiment via Grok engine, as " "defined in a\npermutations.py script or an expGenerator experiment " "description json file.\nIn the expDescription.json form, the json file " "MUST have the file extension\n'.json' and MUST conform to " "expGenerator/experimentDescriptionSchema.json.") parser = optparse.OptionParser(usage=helpString) parser.add_option( "--replaceReport", dest="replaceReport", action="store_true", default=DEFAULT_OPTIONS["replaceReport"], help="Replace existing csv report file if it exists. Default is to " "append to the existing file. [default: %default].") parser.add_option( "--action", dest="action", default=DEFAULT_OPTIONS["action"], choices=["run", "pickup", "report", "dryRun"], help="Which action to perform. Possible actions are run, pickup, choices, " "report, list. " "run: run a new HyperSearch via Grok. " "pickup: pick up the latest run of a HyperSearch job. " "dryRun: run a single HypersearchWorker inline within the application " "process without the Grok infrastructure to flush out bugs in " "description and permutations scripts; defaults to " "maxPermutations=1: use --maxPermutations to change this; " "report: just print results from the last or current run. " "[default: %default].") parser.add_option( "--maxPermutations", dest="maxPermutations", default=DEFAULT_OPTIONS["maxPermutations"], type="int", help="Maximum number of models to search. Applies only to the 'run' and " "'dryRun' actions. [default: %default].") parser.add_option( "--exports", dest="exports", default=DEFAULT_OPTIONS["exports"], type="string", help="json dump of environment variable settings that should be applied" "for the job before running. [default: %default].") parser.add_option( "--useTerminators", dest="useTerminators", action="store_true", default=DEFAULT_OPTIONS["useTerminators"], help="Use early model terminators in HyperSearch" "[default: %default].") parser.add_option( "--maxWorkers", dest="maxWorkers", default=DEFAULT_OPTIONS["maxWorkers"], type="int", help="Maximum number of concurrent workers to launch. Applies only to " "the 'run' action. [default: %default].") parser.add_option( "-v", dest="verbosityCount", action="count", default=0, help="Increase verbosity of the output. Specify multiple times for " "increased verbosity. e.g., -vv is more verbose than -v.") parser.add_option( "--timeout", dest="timeout", default=DEFAULT_OPTIONS["timeout"], type="int", help="Time out for this search in minutes" "[default: %default].") parser.add_option( "--overwrite", default=DEFAULT_OPTIONS["overwrite"], action="store_true", help="If 'yes', overwrite existing description.py and permutations.py" " (in the same directory as the <expDescription.json> file) if they" " already exist. [default: %default].") parser.add_option( "--genTopNDescriptions", dest="genTopNDescriptions", default=DEFAULT_OPTIONS["genTopNDescriptions"], type="int", help="Generate description files for the top N models. Each one will be" " placed into it's own subdirectory under the base description file." "[default: %default].") (options, positionalArgs) = parser.parse_args(args) # Get the permutations script's filepath if len(positionalArgs) != 1: parser.error("You must supply the name of exactly one permutations script " "or JSON description file.") fileArgPath = os.path.expanduser(positionalArgs[0]) fileArgPath = os.path.expandvars(fileArgPath) fileArgPath = os.path.abspath(fileArgPath) permWorkDir = os.path.dirname(fileArgPath) outputLabel = os.path.splitext(os.path.basename(fileArgPath))[0] basename = os.path.basename(fileArgPath) fileExtension = os.path.splitext(basename)[1] optionsDict = vars(options) if fileExtension == ".json": returnValue = permutations_runner.runWithJsonFile( fileArgPath, optionsDict, outputLabel, permWorkDir) else: returnValue = permutations_runner.runWithPermutationsScript( fileArgPath, optionsDict, outputLabel, permWorkDir) return returnValue if __name__ == "__main__": runPermutations(sys.argv[1:])
7,908
Python
.py
154
46.201299
96
0.694689
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,329
enc_profile.py
numenta_nupic-legacy/scripts/profiling/enc_profile.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- ## run python -m cProfile --sort cumtime $NUPIC/scripts/profiling/enc_profile.py [nMaxValue nEpochs] import sys import numpy # chose desired Encoder implementations to compare: from nupic.encoders.scalar import ScalarEncoder from nupic.encoders.random_distributed_scalar import RandomDistributedScalarEncoder as RDSE def profileEnc(maxValue, nRuns): minV=0 maxV=nRuns # generate input data data=numpy.random.randint(minV, maxV+1, nRuns) # instantiate measured encoders encScalar = ScalarEncoder(w=21, minval=minV, maxval=maxV, resolution=1) encRDSE = RDSE(resolution=1) # profile! for d in data: encScalar.encode(d) encRDSE.encode(d) print "Scalar n=",encScalar.n," RDSE n=",encRDSE.n if __name__ == "__main__": maxV=500 epochs=10000 if len(sys.argv) == 3: # 2 args + name columns=int(sys.argv[1]) epochs=int(sys.argv[2]) profileEnc(maxV, epochs)
1,881
Python
.py
46
38.630435
100
0.705431
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,330
sp_profile.py
numenta_nupic-legacy/scripts/profiling/sp_profile.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- ## run python -m cProfile --sort cumtime $NUPIC/scripts/profiling/sp_profile.py [nColumns nEpochs] import numpy import sys from nupic.bindings.algorithms import SpatialPooler as CppSP from nupic.algorithms.spatial_pooler import SpatialPooler as PySP def profileSP(spClass, spDim, nRuns): """ profiling performance of SpatialPooler (SP) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param spClass implementation of SP (cpp, py, ..) @param spDim number of columns in SP (in 1D, for 2D see colDim in code) @param nRuns number of calls of the profiled code (epochs) """ # you can change dimensionality here, eg to 2D inDim = [10000, 1, 1] colDim = [spDim, 1, 1] # create SP instance to measure # changing the params here affects the performance sp = spClass( inputDimensions=inDim, columnDimensions=colDim, potentialRadius=3, potentialPct=0.5, globalInhibition=False, localAreaDensity=-1.0, numActiveColumnsPerInhArea=3, stimulusThreshold=1, synPermInactiveDec=0.01, synPermActiveInc=0.1, synPermConnected=0.10, minPctOverlapDutyCycle=0.1, dutyCyclePeriod=10, boostStrength=10.0, seed=42, spVerbosity=0) # generate input data dataDim = inDim dataDim.append(nRuns) data = numpy.random.randint(0, 2, dataDim).astype('float32') for i in xrange(nRuns): # new data every time, this is the worst case performance # real performance would be better, as the input data would not be completely random d = data[:,:,:,i] activeArray = numpy.zeros(colDim) # the actual function to profile! sp.compute(d, True, activeArray) if __name__ == "__main__": columns=2048 epochs=10000 # read params from command line if len(sys.argv) == 3: # 2 args + name columns=int(sys.argv[1]) epochs=int(sys.argv[2]) profileSP(CppSP, columns, epochs)
2,972
Python
.py
75
35.64
98
0.693162
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,331
tm_profile.py
numenta_nupic-legacy/scripts/profiling/tm_profile.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- ## run python -m cProfile --sort cumtime $NUPIC/scripts/profiling/tm_profile.py [nColumns nEpochs] import numpy import sys from nupic.algorithms.backtracking_tm import BacktrackingTM as PyTM from nupic.algorithms.backtracking_tm_cpp import BacktrackingTMCPP as CppTM def profileTM(tmClass, tmDim, nRuns): """ profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @param nRuns number of calls of the profiled code (epochs) """ # create TM instance to measure tm = tmClass(numberOfCols=tmDim) # generate input data data = numpy.random.randint(0, 2, [tmDim, nRuns]).astype('float32') for i in xrange(nRuns): # new data every time, this is the worst case performance # real performance would be better, as the input data would not be completely random d = data[:,i] # the actual function to profile! tm.compute(d, True) if __name__ == "__main__": columns=2048 epochs=10000 # read command line params if len(sys.argv) == 3: # 2 args + name columns=int(sys.argv[1]) epochs=int(sys.argv[2]) profileTM(CppTM, columns, epochs)
2,253
Python
.py
52
40.826923
98
0.706447
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,332
profile_opf_memory.py
numenta_nupic-legacy/scripts/profiling/profile_opf_memory.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """Memory profiling tool.""" import os import subprocess import sys import time def main(expLocation): start = time.time() opfRunnerPath = os.path.join(os.getcwd(), os.path.dirname(__file__), 'run_opf_experiment.py') expPath = os.path.join(os.getcwd(), expLocation) expProc = subprocess.Popen(['python', opfRunnerPath, expPath]) history = [] while True: if expProc.poll() is not None: break process = subprocess.Popen( "ps -o rss,command | grep run_opf_experiment | " "awk '{sum+=$1} END {print sum}'", shell=True, stdout=subprocess.PIPE) try: stdoutList = process.communicate()[0].split('\n') mem = float(stdoutList[0]) * 1024 / 1048576 except ValueError: continue history.append((time.time() - start, mem)) print 'Max memory: ', max([a[1] for a in history]) if __name__ == '__main__': if len(sys.argv) != 2: print ('Usage: profile_opf_memory.py path/to/experiment/\n' ' See run_opf_experiment.py') sys.exit(1) main(sys.argv[1])
2,054
Python
.py
52
35.711538
72
0.645258
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,333
install_python_pip.ps1
numenta_nupic-legacy/ci/appveyor/install_python_pip.ps1
# Sample script to install Python and pip under Windows # Authors: Olivier Grisel and Kyle Kastner # License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ $BASE_URL = "https://www.python.org/ftp/python/" $GET_PIP_URL = "http://releases.numenta.org/pip/1ebd3cb7a5a3073058d0c9552ab074bd/get-pip.py" $GET_PIP_PATH = "C:\get-pip.py" $GET_NUMPY_URL = "https://bitbucket.org/carlkl/mingw-w64-for-python/downloads/numpy-1.9.1+openblas-cp27-none-win_amd64.whl" $GET_NUMPY_PATH = "C:\numpy-1.9.1+openblas-cp27-none-win_amd64.whl" function DownloadPython ($python_version, $platform_suffix) { $webclient = New-Object System.Net.WebClient $filename = "python-" + $python_version + $platform_suffix + ".msi" $url = $BASE_URL + $python_version + "/" + $filename $basedir = $pwd.Path + "\" $filepath = $basedir + $filename if (Test-Path $filename) { Write-Host "Reusing" $filepath return $filepath } # Download and retry up to 5 times in case of network transient errors. Write-Host "Downloading" $filename "from" $url $retry_attempts = 3 for($i=0; $i -lt $retry_attempts; $i++){ try { $webclient.DownloadFile($url, $filepath) break } Catch [Exception]{ Start-Sleep 1 } } Write-Host "File saved at" $filepath return $filepath } function InstallPython ($python_version, $architecture, $python_home) { Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home if ( $(Try { Test-Path $python_home.trim() } Catch { $false }) ) { Write-Host $python_home "already exists, skipping." return $false } if ($architecture -eq "32") { $platform_suffix = "" } else { $platform_suffix = ".amd64" } $filepath = DownloadPython $python_version $platform_suffix Write-Host "Installing" $filepath "to" $python_home $args = "/qn /i $filepath TARGETDIR=$python_home" Write-Host "msiexec.exe" $args Start-Process -FilePath "msiexec.exe" -ArgumentList $args -Wait -Passthru Write-Host "Python $python_version ($architecture) installation complete" return $true } function InstallPip ($python_home) { $pip_path = $python_home + "\Scripts\pip.exe" $python_path = $python_home + "\python.exe" if ( $(Try { Test-Path $pip_path.trim() } Catch { $false }) ) { Write-Host "pip already installed at " $pip_path return $false } Write-Host "Installing pip..." $webclient = New-Object System.Net.WebClient $webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH) Write-Host "Executing:" $python_path $GET_PIP_PATH Start-Process -FilePath "$python_path" -ArgumentList "$GET_PIP_PATH" -Wait -Passthru return $true } function main () { InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHONHOME InstallPip $env:PYTHONHOME $python_path = $env:PYTHONHOME + "\python.exe" $pip_path = $env:PYTHONHOME + "\Scripts\pip.exe" Write-Host "python -m pip install --upgrade pip" & $python_path -m pip install --upgrade pip Write-Host "pip install " wheel & $pip_path install wheel Write-Host "pip install " numpy==1.9.1 #& $pip_path install -i https://pypi.numenta.com/pypi numpy==1.9.1 # Check AppVeyor cloud cache for NumPy wheel if (-Not (Test-Path $GET_NUMPY_PATH)) { $webclient = New-Object System.Net.WebClient $webclient.DownloadFile($GET_NUMPY_URL, $GET_NUMPY_PATH) } & $pip_path install $GET_NUMPY_PATH } main
3,596
Python
.pyt
85
36.976471
123
0.668958
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,334
data_generator.pyw
numenta_nupic-legacy/examples/opf/tools/data_generator.pyw
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- # Author: Surabhi Gupta from Tkinter import * import math from nupic.data.generators import data_generator from nupic.data.generators import distributions class DataGeneratorApp(): def __init__(self, master, width=1200, height=500): """This class can be used to generate artificial datasets for the purpose of testing, debugging and evaluation. Freehand drawing of data patterns is supported using a gui in addition to predefined distributions. The gui also facilitates selection of the sampling rate using a slider """ self.canvas = Canvas(master, bg= 'grey', width=width, height=height) self.canvas.grid(row=0, column=0, columnspan=3, rowspan=1) self.width, self.height = (width, height) self.color='midnight blue' self.master=master self._defineButtons(master) self.x, self.y= None, None #Initializing mouse position self.draw=False self.numLines, self.records=[], {} self.pointer = None self.dg=data_generator.DataGenerator() self.dg.defineField('xPos', dict(dataType='int',minval=0,maxval=self.width, forced=True)) self.dg.defineField('yPos', dict(dataType='int',minval=0,maxval=self.height, forced=True)) #Drawing the vertical grid lines for i in range(width/10, width, width/10): self.canvas.create_line(i, 0, i, height, fill='alice blue') #Drawing the x-axis self.canvas.create_line(0, height*8.5/9, width, height*8.5/9, fill='alice blue') def _drawFreeForm(self, event): """ The last and current x,y cursor coordinates are updated. If in drawing mode, records are created from the x and y coordinates. """ self.lastx, self.lasty = self.x, self.y self.x, self.y=event.x, event.y str = "mouse at x=%d y=%d" % (self.x, self.y) self.master.title(str) if self.pointer is not None: self.canvas.delete(self.pointer) drawPointer=True for x in range(self.x-5, self.x+5): if drawPointer: if x in self.records: self.pointer = self.canvas.create_oval(x-4, self.records[x][1]-4, x+4,\ self.records[x][1]+4, width=0, fill=self.color) drawPointer=False if drawPointer: self.pointer = self.canvas.create_oval(self.x-4, self.height*8.5/9-4, self.x+4, \ self.height*8.5/9+4, width=0, fill=self.color) def _createLine(self, fromX, fromY, toX, toY, width=2): line = self.canvas.create_line(fromX, fromY, toX, toY, fill=self.color, width=width) self.numLines.append(line) return line def motionCallback(self, event, freeForm=True): """ Free form drawing is permitted whenever the mouse is moving.""" self._drawFreeForm(event) def buttonReleaseCallback(self, event): if (self.lastx, self.lasty)<>(None, None): self._createLine(self.lastx, self.lasty, self.lastx, self.height*8.5/9) self._createLine(self.x, self.lasty, self.x, self.y) ############################################################################ def mousePressedMotionCallback(self, event): self.lastx, self.lasty = self.x, self.y self.x, self.y=event.x, event.y str = "mouse at x=%d y=%d" % (self.x, self.y) self.master.title(str) if (self.lastx, self.lasty)<>(None, None): line = self._createLine(self.lastx, self.lasty, self.x, self.y) self.dg.generateRecord([self.x, self.y]) self.records[self.x]=[line, self.y] self._addToLog([self.x, self.y], 'Adding') for i in range(self.lastx, self.x): self.records[i]=['',(self.lasty+self.y)/2] ############################################################################ def mousePressCallback(self, event): """Callback for mouse press. The cursor y-position is marked with a vertical line. """ self.lastx, self.lasty = self.x, self.y self.x, self.y=event.x, event.y if (self.lastx, self.lasty)<>(None, None): self._createLine(self.lastx, self.lasty, self.lastx, self.height*8.5/9) self._createLine(self.x, self.lasty, self.x, self.y) def refreshCallback(self): """Callback for the refresh button. All the currently displayed lines except the x-axis and y-axis are erased and all stored records are removed. """ for i in self.numLines: self.canvas.delete(i) self.records={} self.log.insert('1.0', "Erasing the drawing board\n") self.dg.removeAllRecords() def sineWave(self): """Callback for drawing square waves""" sine = distributions.SineWave(dict(amplitude=0.4, period=self.slider.get())) records = sine.getData(1000) records = [r+0.5 for r in records] self.drawWaveform(records, factor=2) def squareWave(self): """Callback for drawing square waves""" records=[] for i in range(0,500,10): for i in range(0,15,10): for i in range(24): waveValue = self.square_function(i, 1) records.append(waveValue) for i in range(0,15,10): for i in range(24): waveValue = self.square_function(i, 1) if waveValue >= 1: waveValue = waveValue*2 records.append(waveValue) records = [r/2.01 for r in records] self.drawWaveform(records, factor=1) def sinePlusNoise(self): """Callback for drawing noisy sine waves""" records=[] for i in range(15): for i in range(1,360,5): waveValue = self.sine_function(math.radians(i), 1) secondWaveValue = self.sine_function(math.radians(i), 32)/4 finalValue = waveValue + secondWaveValue records.append(finalValue) records = [r+1.0 for r in records] self.drawWaveform(records, factor=5) def sawToothWave(self): """Callback for drawing sawtooth waves""" records=[] for i in range(15): for i in range(1,360, int(self.slider.get())): waveValue = self.sawtooth_function(math.radians(i), 1) records.append(waveValue) records = [r+1.0 for r in records] self.drawWaveform(records, factor=5) def sineCompositeWave(self): """Callback for drawing composite sine waves""" records=[] for i in range(500): for i in range(1,360,10): waveValue = self.sine_function(math.radians(i), 1) secondWaveValue = self.sine_function(math.radians(i), 32) / 4 finalValue = waveValue + secondWaveValue records.append(finalValue) records = [r+1.0 for r in records] self.drawWaveform(records,factor=2) def triangleWave(self): """Callback for drawing triangle waves""" records=[] for i in range(15): for i in range(1,360,int(self.slider.get())): waveValue = self.triangle_function(math.radians(i), 1) records.append(waveValue) records = [r+1.0 for r in records] self.drawWaveform(records,factor=6) def adjustValues(self, records): """ The data points that constitute a waveform in the range (0, 1) are scaled to the height of the window """ for i in xrange(len(records)): #records[i]=records[i]*(self.height*(8.4/9)*0.5) records[i]=records[i]*(self.height*(8.4/9)) return records def drawWaveform(self, records, factor=5): """Refresh and draw a waveform adjusted to the width of the screen and the horizontal density of the waveform""" self.refreshCallback() records = self.adjustValues(records) factor = self.slider.get() for i in range(1,len(records)): #print (i-1)*factor, records[i-1], i*factor, records[i] line = self.canvas.create_line((i-1)*factor, records[i-1]+2, i*factor,\ records[i]+2, fill=self.color, width=2) self.records[i*factor]=[line,records[i]] self.numLines.append(line) ############################################################################ def _addToLog(self, record, operation): """Report creation of new record in the log window.""" self.log.insert('1.0', "%s record %s \n" %(operation, str(record))) self.log.mark_set(INSERT, '0.0') self.log.focus() def _defineButtons(self, master, height=2): """Define the buttons and text box and position them""" twoSine=Button(master, text="Sine Wave", fg="gray77", bg="chocolate1",\ command=self.sineWave) noisySine=Button(master, text="Noisy Sine", fg="gray77", bg="chocolate1", command=self.sinePlusNoise) save=Button(master, text="Save", fg="gray77", bg="chocolate1", command=self.saveFile) refresh=Button(master, text="Clear", fg="gray77", bg="chocolate1", command=self.refreshCallback) triangle=Button(master, text="Triangle", fg="gray77", bg="chocolate1", command=self.triangleWave) sineComposite=Button(master, text="Sine Composite", fg="gray77", bg="chocolate1", command=self.sineCompositeWave) sawTooth=Button(master, text="Saw Tooth", fg="gray77", bg="chocolate1", command=self.sawToothWave) square=Button(master, text="Square Wave", fg="gray77", bg="chocolate1", command=self.squareWave) self.slider=Scale(master, from_=1, to=12, orient=HORIZONTAL, resolution=0.1, bg='gray77', bd=4) #Positioning buttons refresh.grid(row=2, column=0, rowspan=1, sticky=E+W) save.grid(row=3, column=0, rowspan=1, sticky=E+W) noisySine.grid(row=4, column=0, rowspan=1, sticky=E+W) sineComposite.grid(row=2, column=1, rowspan=1, sticky=E+W) triangle.grid(row=3, column=1, rowspan=1, sticky=E+W) sawTooth.grid(row=4, column=1, rowspan=1, sticky=E+W) square.grid(row=5, column=0, rowspan=1, sticky=E+W) twoSine.grid(row=5, column=1, rowspan=1, sticky=E+W) self.slider.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E+W) #Text box with scrollbar frame = Frame(master, bd=1, relief=SUNKEN) frame.grid(row=2, column=2, rowspan=6) frame.grid_rowconfigure(0, pad=0, weight=1) frame.grid_columnconfigure(0, pad=0,weight=1) xscrollbar = Scrollbar(frame, orient=HORIZONTAL) xscrollbar.grid(row=1, column=0, sticky=E+W) yscrollbar = Scrollbar(frame) yscrollbar.grid(row=0, column=1, sticky=N+S) self.log=Text(frame, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, \ yscrollcommand=yscrollbar.set, bg="Black", fg="gray70", height=15, width=70) self.log.grid(row=0, column=0, sticky=N+S, in_=frame) xscrollbar.config(command=self.log.xview) yscrollbar.config(command=self.log.yview) ############################################################################ def saveFile(self, path='output'): """Save the records to a file in numenta format.""" self.dg.saveRecords(path=path) self.log.insert('1.0', "Saving %s records to file %s \n" \ %(str(len(self.records)), str(path+'.csv'))) #Note: The following function definitions will be ported to the distributions #class in future versions def sine_function(self,t, f): return math.sin(t*f) def triangle_function(self,t,f): ''' T is our timestep F changes the speed we get to an inversion point ''' value = t * f # Reduce our value range to 0 to 1 remainder = math.fmod(value, 1) # Mulitply by 4 so we end up with both positive and negative values q = remainder * 4 # Don't go over 1, invert if we do if q > 1: q = 2-q # Don't go under -1, invert if we do if q < -1: rv = -2-q else: rv = q return rv def square_function(self,t,f): if(f == 0): return 0 q = 0.5 - math.fmod(t*f,1) return (0,1)[q > 0] def sawtooth_function(self,t,f): # Get our initial y value value = t * f # Make sure our values fall between .5 and 1 remainder = math.fmod(value + 0.5, 1) # Make sure our values fall between 1 and 2 rv = remainder * 2.0 # Make sure our values fall between -1 and 1 rv = rv - 1.0 return rv ############################################################################ def callBacks(app): app.canvas.bind("<Motion>", app.motionCallback) app.canvas.bind("<ButtonPress-1>", app.mousePressCallback) app.canvas.bind("<B1-Motion>", app.mousePressedMotionCallback) app.canvas.bind("<ButtonRelease-1>", app.buttonReleaseCallback) root = Tk() app = DataGeneratorApp(root) callBacks(app) root.mainloop()
13,486
Python
.pyw
292
39.609589
117
0.645181
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,335
syntactic_sugar_test.py
numenta_nupic-legacy/tests/unit/nupic/engine/syntactic_sugar_test.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import sys import unittest2 as unittest import nupic.engine as net class NetworkSugarTest(unittest.TestCase): def testPhases(self): n = net.Network() self.assertEqual(n.minPhase, 0) self.assertEqual(n.maxPhase, 0) self.assertEqual(n.minEnabledPhase, 0) self.assertEqual(n.maxEnabledPhase, 0) _r1 = n.addRegion('r1', 'TestNode', '') _r2 = n.addRegion('r2', 'TestNode', '') self.assertEqual(n.minPhase, 0) self.assertEqual(n.maxPhase, 1) self.assertEqual(n.minEnabledPhase, 0) self.assertEqual(n.maxEnabledPhase, 1) n.setPhases('r1', (1, 4)) n.setPhases('r2', (2, 3)) self.assertEqual(n.minPhase, 1) self.assertEqual(n.maxPhase, 4) self.assertEqual(n.minEnabledPhase, 1) self.assertEqual(n.maxEnabledPhase, 4) n.minEnabledPhase = 2 n.maxEnabledPhase = 3 self.assertEqual(n.minPhase, 1) self.assertEqual(n.maxPhase, 4) self.assertEqual(n.minEnabledPhase, 2) self.assertEqual(n.maxEnabledPhase, 3) def testRegionCollection(self): n = net.Network() regions = n.regions self.assertEqual(len(regions), 0) r1 = n.addRegion('r1', 'TestNode', '') r2 = n.addRegion('r2', 'TestNode', '') self.assertTrue(r1 is not None) self.assertEqual(len(regions), 2) # test the 'in' operator self.assertTrue('r1' in regions) self.assertTrue('r2' in regions) self.assertFalse('r3' in regions) # test [] operator self.assertEqual(regions['r1'], r1) self.assertEqual(regions['r2'], r2) with self.assertRaises(KeyError): _ = regions['r3'] # for iteration for i, r in enumerate(regions): if i == 0: self.assertEqual(r[0], 'r1') elif i == 1: self.assertEqual(r[0], 'r2') else: self.fail("Expected i == 0 or i == 1") # test .keys() keys = regions.keys() self.assertEqual(keys, list(['r1', 'r2'])) # test .values() values = regions.values() self.assertEqual(len(values), 2) v1 = values.pop() v2 = values.pop() self.assertTrue((v1, v2) == (r1, r2) or (v1, v2) == (r2, r1)) # test .items() items = regions.items() self.assertEqual(len(items), 2) i1 = items.pop() i2 = items.pop() self.assertTrue((i1, i2) == (('r1', r1), ('r2', r2)) or (('r2', r2), ('r1', r1))) @unittest.skipIf(sys.platform.lower().startswith("win"), "Not supported on Windows, yet!") def testRegion(self): r = net.Network().addRegion('r', 'py.TestNode', '') print r.spec self.assertEqual(r.type, 'py.TestNode') self.assertEqual(r.name, 'r') self.assertTrue(r.dimensions.isUnspecified()) @unittest.skipIf(sys.platform.lower().startswith("win"), "Not supported on Windows, yet!") def testSpec(self): ns = net.Region.getSpecFromType('py.TestNode') self.assertEqual(ns.description, 'The node spec of the NuPIC 2 Python TestNode') n = net.Network() r = n.addRegion('r', 'py.TestNode', '') ns2 = r.spec self.assertEqual(ns.singleNodeOnly, ns2.singleNodeOnly) self.assertEqual(ns.description, ns2.description) self.assertEqual(ns.inputs, ns2.inputs) self.assertEqual(ns.outputs, ns2.outputs) self.assertEqual(ns.parameters, ns2.parameters) self.assertEqual(ns.commands, ns2.commands) def testTimer(self): t = net.Timer() self.assertEqual(t.elapsed, 0) self.assertEqual(t.startCount, 0) self.assertEqual(str(t), "[Elapsed: 0 Starts: 0]") t.start() # Dummy time _j = 0 for i in xrange(0, 1000): _j = i t.stop() self.assertTrue(t.elapsed > 0) self.assertEqual(t.startCount, 1) if __name__ == "__main__": unittest.main()
4,744
Python
.tac
127
32.228346
72
0.64412
numenta/nupic-legacy
6,330
1,556
464
AGPL-3.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,336
setup.py
mhagger_git-imerge/setup.py
import errno import subprocess from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() data_files = [] try: completionsdir = subprocess.check_output( ["pkg-config", "--variable=completionsdir", "bash-completion"] ) except OSError as e: if e.errno != errno.ENOENT: raise except subprocess.CalledProcessError: # `bash-completion` is probably not installed. Just skip it. pass else: completionsdir = completionsdir.strip().decode('utf-8') if completionsdir: data_files.append((completionsdir, ["completions/git-imerge"])) setup( name="git-imerge", description="Incremental merge and rebase for Git", url="https://github.com/mhagger/git-imerge", version="1.2.0", author="Michael Haggerty", author_email="mhagger@alum.mit.edu", long_description=long_description, long_description_content_type="text/markdown", license="GPLv2+", py_modules=["gitimerge"], data_files=data_files, entry_points={"console_scripts": ["git-imerge = gitimerge:climain"]}, python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Environment :: Console", "Intended Audience :: Developers", "Topic :: Software Development :: Version Control :: Git", ], )
1,944
Python
.py
52
31.75
85
0.643879
mhagger/git-imerge
2,695
126
76
GPL-2.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,337
gitimerge.py
mhagger_git-imerge/gitimerge.py
# -*- coding: utf-8 -*- # Copyright 2012-2013 Michael Haggerty <mhagger@alum.mit.edu> # # This file is part of git-imerge. # # git-imerge 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. # # 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 # <https://www.gnu.org/licenses/>. r"""Git incremental merge Perform the merge between two branches incrementally. If conflicts are encountered, figure out exactly which pairs of commits conflict, and present the user with one pairwise conflict at a time for resolution. Multiple incremental merges can be in progress at the same time. Each incremental merge has a name, and its progress is recorded in the Git repository as references under 'refs/imerge/NAME'. An incremental merge can be interrupted and resumed arbitrarily, or even pushed to a server to allow somebody else to work on it. Instructions: To start an incremental merge or rebase, use one of the following commands: git-imerge merge BRANCH Analogous to "git merge BRANCH" git-imerge rebase BRANCH Analogous to "git rebase BRANCH" git-imerge drop [commit | commit1..commit2] Drop the specified commit(s) from the current branch git-imerge revert [commit | commit1..commit2] Revert the specified commits by adding new commits that reverse their effects git-imerge start --name=NAME --goal=GOAL BRANCH Start a general imerge Then the tool will present conflicts to you one at a time, similar to "git rebase --incremental". Resolve each conflict, and then git add FILE... git-imerge continue You can view your progress at any time with git-imerge diagram When you have resolved all of the conflicts, simplify and record the result by typing git-imerge finish To get more help about any git-imerge subcommand, type git-imerge SUBCOMMAND --help """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import locale import sys import re import subprocess from subprocess import CalledProcessError from subprocess import check_call import itertools import argparse from io import StringIO import json import os PREFERRED_ENCODING = locale.getpreferredencoding() # Define check_output() for ourselves, including decoding of the # output into PREFERRED_ENCODING: def check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output = communicate(process)[0] retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] # We don't store output in the CalledProcessError because # the "output" keyword parameter was not supported in # Python 2.6: raise CalledProcessError(retcode, cmd) return output STATE_VERSION = (1, 3, 0) ZEROS = '0' * 40 ALLOWED_GOALS = [ 'full', 'rebase', 'rebase-with-history', 'border', 'border-with-history', 'border-with-history2', 'merge', 'drop', 'revert', ] DEFAULT_GOAL = 'merge' class Failure(Exception): """An exception that indicates a normal failure of the script. Failures are reported at top level via sys.exit(str(e)) rather than via a Python stack dump.""" pass class AnsiColor: BLACK = '\033[0;30m' RED = '\033[0;31m' GREEN = '\033[0;32m' YELLOW = '\033[0;33m' BLUE = '\033[0;34m' MAGENTA = '\033[0;35m' CYAN = '\033[0;36m' B_GRAY = '\033[0;37m' D_GRAY = '\033[1;30m' B_RED = '\033[1;31m' B_GREEN = '\033[1;32m' B_YELLOW = '\033[1;33m' B_BLUE = '\033[1;34m' B_MAGENTA = '\033[1;35m' B_CYAN = '\033[1;36m' WHITE = '\033[1;37m' END = '\033[0m' @classmethod def disable(cls): cls.BLACK = '' cls.RED = '' cls.GREEN = '' cls.YELLOW = '' cls.BLUE = '' cls.MAGENTA = '' cls.CYAN = '' cls.B_GRAY = '' cls.D_GRAY = '' cls.B_RED = '' cls.B_GREEN = '' cls.B_YELLOW = '' cls.B_BLUE = '' cls.B_MAGENTA = '' cls.B_CYAN = '' cls.WHITE = '' cls.END = '' def iter_neighbors(iterable): """For an iterable (x0, x1, x2, ...) generate [(x0,x1), (x1,x2), ...].""" i = iter(iterable) try: last = next(i) except StopIteration: return for x in i: yield (last, x) last = x def find_first_false(f, lo, hi): """Return the smallest i in lo <= i < hi for which f(i) returns False using bisection. If there is no such i, return hi. """ # Loop invariant: f(i) returns True for i < lo; f(i) returns False # for i >= hi. while lo < hi: mid = (lo + hi) // 2 if f(mid): lo = mid + 1 else: hi = mid return lo def call_silently(cmd): try: NULL = open(os.devnull, 'w') except (IOError, AttributeError): NULL = subprocess.PIPE p = subprocess.Popen(cmd, stdout=NULL, stderr=NULL) p.communicate() retcode = p.wait() if retcode: raise CalledProcessError(retcode, cmd) def communicate(process, input=None): """Return decoded output from process.""" if input is not None: input = input.encode(PREFERRED_ENCODING) output, error = process.communicate(input) output = None if output is None else output.decode(PREFERRED_ENCODING) error = None if error is None else error.decode(PREFERRED_ENCODING) return (output, error) if sys.hexversion >= 0x03000000: # In Python 3.x, os.environ keys and values must be unicode # strings: def env_encode(s): """Use unicode keys or values unchanged in os.environ.""" return s else: # In Python 2.x, os.environ keys and values must be byte # strings: def env_encode(s): """Encode unicode keys or values for use in os.environ.""" return s.encode(PREFERRED_ENCODING) class UncleanWorkTreeError(Failure): pass class AutomaticMergeFailed(Exception): def __init__(self, commit1, commit2): Exception.__init__( self, 'Automatic merge of %s and %s failed' % (commit1, commit2,) ) self.commit1, self.commit2 = commit1, commit2 class InvalidBranchNameError(Failure): pass class NotFirstParentAncestorError(Failure): def __init__(self, commit1, commit2): Failure.__init__( self, 'Commit "%s" is not a first-parent ancestor of "%s"' % (commit1, commit2), ) class NonlinearAncestryError(Failure): def __init__(self, commit1, commit2): Failure.__init__( self, 'The history "%s..%s" is not linear' % (commit1, commit2), ) class NothingToDoError(Failure): def __init__(self, src_tip, dst_tip): Failure.__init__( self, 'There are no commits on "%s" that are not already in "%s"' % (src_tip, dst_tip), ) class GitTemporaryHead(object): """A context manager that records the current HEAD state then restores it. This should only be used when the working copy is clean. message is used for the reflog. """ def __init__(self, git, message): self.git = git self.message = message def __enter__(self): self.head_name = self.git.get_head_refname() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.head_name: try: self.git.restore_head(self.head_name, self.message) except CalledProcessError as e: raise Failure( 'Could not restore HEAD to %r!: %s\n' % (self.head_name, e.message,) ) return False class GitRepository(object): BRANCH_PREFIX = 'refs/heads/' MERGE_STATE_REFNAME_RE = re.compile( r""" ^ refs\/imerge\/ (?P<name>.+) \/state $ """, re.VERBOSE, ) def __init__(self): self.git_dir_cache = None def git_dir(self): if self.git_dir_cache is None: self.git_dir_cache = check_output( ['git', 'rev-parse', '--git-dir'] ).rstrip('\n') return self.git_dir_cache def check_imerge_name_format(self, name): """Check that name is a valid imerge name.""" try: call_silently( ['git', 'check-ref-format', 'refs/imerge/%s' % (name,)] ) except CalledProcessError: raise Failure('Name %r is not a valid refname component!' % (name,)) def check_branch_name_format(self, name): """Check that name is a valid branch name.""" try: call_silently( ['git', 'check-ref-format', 'refs/heads/%s' % (name,)] ) except CalledProcessError: raise InvalidBranchNameError('Name %r is not a valid branch name!' % (name,)) def iter_existing_imerge_names(self): """Iterate over the names of existing MergeStates in this repo.""" for line in check_output(['git', 'for-each-ref', 'refs/imerge']).splitlines(): (sha1, type, refname) = line.split() if type == 'blob': m = GitRepository.MERGE_STATE_REFNAME_RE.match(refname) if m: yield m.group('name') def set_default_imerge_name(self, name): """Set the default merge to the specified one. name can be None to cause the default to be cleared.""" if name is None: try: check_call(['git', 'config', '--unset', 'imerge.default']) except CalledProcessError as e: if e.returncode == 5: # Value was not set pass else: raise else: check_call(['git', 'config', 'imerge.default', name]) def get_default_imerge_name(self): """Get the name of the default merge, or None if it is currently unset.""" try: return check_output(['git', 'config', 'imerge.default']).rstrip() except CalledProcessError: return None def get_default_edit(self): """Should '--edit' be used when committing intermediate user merges? When 'git imerge continue' or 'git imerge record' finds a user merge that can be committed, should it (by default) ask the user to edit the commit message? This behavior can be configured via 'imerge.editmergemessages'. If it is not configured, return False. Please note that this function is only used to choose the default value. It can be overridden on the command line using '--edit' or '--no-edit'. """ try: return {'true' : True, 'false' : False}[ check_output( ['git', 'config', '--bool', 'imerge.editmergemessages'] ).rstrip() ] except CalledProcessError: return False def unstaged_changes(self): """Return True iff there are unstaged changes in the working copy""" try: check_call(['git', 'diff-files', '--quiet', '--ignore-submodules']) return False except CalledProcessError: return True def uncommitted_changes(self): """Return True iff the index contains uncommitted changes.""" try: check_call([ 'git', 'diff-index', '--cached', '--quiet', '--ignore-submodules', 'HEAD', '--', ]) return False except CalledProcessError: return True def get_commit_sha1(self, arg): """Convert arg into a SHA1 and verify that it refers to a commit. If not, raise ValueError.""" try: return self.rev_parse('%s^{commit}' % (arg,)) except CalledProcessError: raise ValueError('%r does not refer to a valid git commit' % (arg,)) def refresh_index(self): process = subprocess.Popen( ['git', 'update-index', '-q', '--ignore-submodules', '--refresh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out, err = communicate(process) retcode = process.poll() if retcode: raise UncleanWorkTreeError(err.rstrip() or out.rstrip()) def verify_imerge_name_available(self, name): self.check_imerge_name_format(name) if check_output(['git', 'for-each-ref', 'refs/imerge/%s' % (name,)]): raise Failure('Name %r is already in use!' % (name,)) def check_imerge_exists(self, name): """Verify that a MergeState with the given name exists. Just check for the existence, readability, and compatible version of the 'state' reference. If the reference doesn't exist, just return False. If it exists but is unusable for some other reason, raise an exception.""" self.check_imerge_name_format(name) state_refname = 'refs/imerge/%s/state' % (name,) for line in check_output(['git', 'for-each-ref', state_refname]).splitlines(): (sha1, type, refname) = line.split() if refname == state_refname and type == 'blob': self.read_imerge_state_dict(name) # If that didn't throw an exception: return True else: return False def read_imerge_state_dict(self, name): state_string = check_output( ['git', 'cat-file', 'blob', 'refs/imerge/%s/state' % (name,)], ) state = json.loads(state_string) # Convert state['version'] to a tuple of integers, and verify # that it is compatible with this version of the script: version = tuple(int(i) for i in state['version'].split('.')) if version[0] != STATE_VERSION[0] or version[1] > STATE_VERSION[1]: raise Failure( 'The format of imerge %s (%s) is not compatible with this script version.' % (name, state['version'],) ) state['version'] = version return state def read_imerge_state(self, name): """Read the state associated with the specified imerge. Return the tuple (state_dict, {(i1, i2) : (sha1, source), ...}) , where source is 'auto' or 'manual'. Validity is checked only lightly. """ merge_ref_re = re.compile( r""" ^ refs\/imerge\/ """ + re.escape(name) + r""" \/(?P<source>auto|manual)\/ (?P<i1>0|[1-9][0-9]*) \- (?P<i2>0|[1-9][0-9]*) $ """, re.VERBOSE, ) state_ref_re = re.compile( r""" ^ refs\/imerge\/ """ + re.escape(name) + r""" \/state $ """, re.VERBOSE, ) state = None # A map {(i1, i2) : (sha1, source)}: merges = {} # refnames that were found but not understood: unexpected = [] for line in check_output([ 'git', 'for-each-ref', 'refs/imerge/%s' % (name,) ]).splitlines(): (sha1, type, refname) = line.split() m = merge_ref_re.match(refname) if m: if type != 'commit': raise Failure('Reference %r is not a commit!' % (refname,)) i1, i2 = int(m.group('i1')), int(m.group('i2')) source = m.group('source') merges[i1, i2] = (sha1, source) continue m = state_ref_re.match(refname) if m: if type != 'blob': raise Failure('Reference %r is not a blob!' % (refname,)) state = self.read_imerge_state_dict(name) continue unexpected.append(refname) if state is None: raise Failure( 'No state found; it should have been a blob reference at ' '"refs/imerge/%s/state"' % (name,) ) if unexpected: raise Failure( 'Unexpected reference(s) found in "refs/imerge/%s" namespace:\n %s\n' % (name, '\n '.join(unexpected),) ) return (state, merges) def write_imerge_state_dict(self, name, state): state_string = json.dumps(state, sort_keys=True) + '\n' cmd = ['git', 'hash-object', '-t', 'blob', '-w', '--stdin'] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out = communicate(p, input=state_string)[0] retcode = p.poll() if retcode: raise CalledProcessError(retcode, cmd) sha1 = out.strip() check_call([ 'git', 'update-ref', '-m', 'imerge %r: Record state' % (name,), 'refs/imerge/%s/state' % (name,), sha1, ]) def is_ancestor(self, commit1, commit2): """Return True iff commit1 is an ancestor (or equal to) commit2.""" if commit1 == commit2: return True else: return int( check_output([ 'git', 'rev-list', '--count', '--ancestry-path', '%s..%s' % (commit1, commit2,), ]).strip() ) != 0 def is_ff(self, refname, commit): """Would updating refname to commit be a fast-forward update? Return True iff refname is not currently set or it points to an ancestor of commit. """ try: ref_oldval = self.get_commit_sha1(refname) except ValueError: # refname doesn't already exist; no problem. return True else: return self.is_ancestor(ref_oldval, commit) def automerge(self, commit1, commit2, msg=None): """Attempt an automatic merge of commit1 and commit2. Return the SHA1 of the resulting commit, or raise AutomaticMergeFailed on error. This must be called with a clean worktree.""" call_silently(['git', 'checkout', '-f', commit1]) cmd = ['git', '-c', 'rerere.enabled=false', 'merge'] if msg is not None: cmd += ['-m', msg] cmd += [commit2] try: call_silently(cmd) except CalledProcessError: self.abort_merge() raise AutomaticMergeFailed(commit1, commit2) else: return self.get_commit_sha1('HEAD') def manualmerge(self, commit, msg): """Initiate a merge of commit into the current HEAD.""" check_call(['git', 'merge', '--no-commit', '-m', msg, commit,]) def require_clean_work_tree(self, action): """Verify that the current tree is clean. The code is a Python translation of the git-sh-setup(1) function of the same name.""" process = subprocess.Popen( ['git', 'rev-parse', '--verify', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) err = communicate(process)[1] retcode = process.poll() if retcode: raise UncleanWorkTreeError(err.rstrip()) self.refresh_index() error = [] if self.unstaged_changes(): error.append('Cannot %s: You have unstaged changes.' % (action,)) if self.uncommitted_changes(): if not error: error.append('Cannot %s: Your index contains uncommitted changes.' % (action,)) else: error.append('Additionally, your index contains uncommitted changes.') if error: raise UncleanWorkTreeError('\n'.join(error)) def simple_merge_in_progress(self): """Return True iff a merge (of a single branch) is in progress.""" try: with open(os.path.join(self.git_dir(), 'MERGE_HEAD')) as f: heads = [line.rstrip() for line in f] except IOError: return False return len(heads) == 1 def commit_user_merge(self, edit_log_msg=None): """If a merge is in progress and ready to be committed, commit it. If a simple merge is in progress and any changes in the working tree are staged, commit the merge commit and return True. Otherwise, return False. """ if not self.simple_merge_in_progress(): return False # Check if all conflicts are resolved and everything in the # working tree is staged: self.refresh_index() if self.unstaged_changes(): raise UncleanWorkTreeError( 'Cannot proceed: You have unstaged changes.' ) # A merge is in progress, and either all changes have been staged # or no changes are necessary. Create a merge commit. cmd = ['git', 'commit', '--no-verify'] if edit_log_msg is None: edit_log_msg = self.get_default_edit() if edit_log_msg: cmd += ['--edit'] else: cmd += ['--no-edit'] try: check_call(cmd) except CalledProcessError: raise Failure('Could not commit staged changes.') return True def create_commit_chain(self, base, path): """Point refname at the chain of commits indicated by path. path is a list [(commit, metadata), ...]. Create a series of commits corresponding to the entries in path. Each commit's tree is taken from the corresponding old commit, and each commit's metadata is taken from the corresponding metadata commit. Use base as the parent of the first commit, or make the first commit a root commit if base is None. Reuse existing commits from the list whenever possible. Return a commit object corresponding to the last commit in the chain. """ reusing = True if base is None: if not path: raise ValueError('neither base nor path specified') parents = [] else: parents = [base] for (commit, metadata) in path: if reusing: if commit == metadata and self.get_commit_parents(commit) == parents: # We can reuse this commit, too. parents = [commit] continue else: reusing = False # Create a commit, copying the old log message and author info # from the metadata commit: tree = self.get_tree(commit) new_commit = self.commit_tree( tree, parents, msg=self.get_log_message(metadata), metadata=self.get_author_info(metadata), ) parents = [new_commit] [commit] = parents return commit def rev_parse(self, arg): return check_output(['git', 'rev-parse', '--verify', '--quiet', arg]).strip() def rev_list_with_parents(self, *args): """Iterate over (commit, [parent,...]).""" cmd = ['git', 'log', '--format=%H %P'] + list(args) for line in check_output(cmd).splitlines(): commits = line.strip().split() yield (commits[0], commits[1:]) def summarize_commit(self, commit): """Summarize `commit` to stdout.""" check_call(['git', '--no-pager', 'log', '--no-walk', commit]) def get_author_info(self, commit): """Return environment settings to set author metadata. Return a map {str : str}.""" # We use newlines as separators here because msysgit has problems # with NUL characters; see # # https://github.com/mhagger/git-imerge/pull/71 a = check_output([ 'git', '--no-pager', 'log', '-n1', '--format=%an%n%ae%n%ai', commit ]).strip().splitlines() return { 'GIT_AUTHOR_NAME': env_encode(a[0]), 'GIT_AUTHOR_EMAIL': env_encode(a[1]), 'GIT_AUTHOR_DATE': env_encode(a[2]), } def get_log_message(self, commit): contents = check_output([ 'git', 'cat-file', 'commit', commit, ]).splitlines(True) contents = contents[contents.index('\n') + 1:] if contents and contents[-1][-1:] != '\n': contents.append('\n') return ''.join(contents) def get_commit_parents(self, commit): """Return a list containing the parents of commit.""" return check_output( ['git', '--no-pager', 'log', '--no-walk', '--pretty=format:%P', commit] ).strip().split() def get_tree(self, arg): return self.rev_parse('%s^{tree}' % (arg,)) def update_ref(self, refname, value, msg, deref=True): if deref: opt = [] else: opt = ['--no-deref'] check_call(['git', 'update-ref'] + opt + ['-m', msg, refname, value]) def delete_ref(self, refname, msg, deref=True): if deref: opt = [] else: opt = ['--no-deref'] check_call(['git', 'update-ref'] + opt + ['-m', msg, '-d', refname]) def delete_imerge_refs(self, name): stdin = ''.join( 'delete %s\n' % (refname,) for refname in check_output([ 'git', 'for-each-ref', '--format=%(refname)', 'refs/imerge/%s' % (name,) ]).splitlines() ) process = subprocess.Popen( [ 'git', 'update-ref', '-m', 'imerge: remove merge %r' % (name,), '--stdin', ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) out = communicate(process, input=stdin)[0] retcode = process.poll() if retcode: sys.stderr.write( 'Warning: error removing references:\n%s' % (out,) ) def detach(self, msg): """Detach HEAD. msg is used for the reflog.""" self.update_ref('HEAD', 'HEAD^0', msg, deref=False) def reset_hard(self, commit): check_call(['git', 'reset', '--hard', commit]) def amend(self): check_call(['git', 'commit', '--amend']) def abort_merge(self): # We don't use "git merge --abort" here because it was # only added in git version 1.7.4. check_call(['git', 'reset', '--merge']) def compute_best_merge_base(self, tip1, tip2): try: merge_bases = check_output(['git', 'merge-base', '--all', tip1, tip2]).splitlines() except CalledProcessError: raise Failure('Cannot compute merge base for %r and %r' % (tip1, tip2)) if not merge_bases: raise Failure('%r and %r do not have a common merge base' % (tip1, tip2)) if len(merge_bases) == 1: return merge_bases[0] # There are multiple merge bases. The "best" one is the one that # is the "closest" to the tips, which we define to be the one with # the fewest non-merge commits in "merge_base..tip". (It can be # shown that the result is independent of which tip is used in the # computation.) best_base = best_count = None for merge_base in merge_bases: cmd = ['git', 'rev-list', '--no-merges', '--count', '%s..%s' % (merge_base, tip1)] count = int(check_output(cmd).strip()) if best_base is None or count < best_count: best_base = merge_base best_count = count return best_base def linear_ancestry(self, commit1, commit2, first_parent): """Compute a linear ancestry between commit1 and commit2. Our goal is to find a linear series of commits connecting `commit1` and `commit2`. We do so as follows: * If all of the commits in git rev-list --ancestry-path commit1..commit2 are on a linear chain, return that. * If there are multiple paths between `commit1` and `commit2` in that list of commits, then * If `first_parent` is not set, then raise an `NonlinearAncestryError` exception. * If `first_parent` is set, then, at each merge commit, follow the first parent that is in that list of commits. Return a list of SHA-1s in 'chronological' order. Raise NotFirstParentAncestorError if commit1 is not an ancestor of commit2. """ oid1 = self.rev_parse(commit1) oid2 = self.rev_parse(commit2) parentage = {oid1 : []} for (commit, parents) in self.rev_list_with_parents( '--ancestry-path', '--topo-order', '%s..%s' % (oid1, oid2) ): parentage[commit] = parents commits = [] commit = oid2 while commit != oid1: parents = parentage.get(commit, []) # Only consider parents that are in the ancestry path: included_parents = [ parent for parent in parents if parent in parentage ] if not included_parents: raise NotFirstParentAncestorError(commit1, commit2) elif len(included_parents) == 1 or first_parent: parent = included_parents[0] else: raise NonlinearAncestryError(commit1, commit2) commits.append(commit) commit = parent commits.reverse() return commits def get_boundaries(self, tip1, tip2, first_parent): """Get the boundaries of an incremental merge. Given the tips of two branches that should be merged, return (merge_base, commits1, commits2) describing the edges of the imerge. Raise Failure if there are any problems.""" merge_base = self.compute_best_merge_base(tip1, tip2) commits1 = self.linear_ancestry(merge_base, tip1, first_parent) if not commits1: raise NothingToDoError(tip1, tip2) commits2 = self.linear_ancestry(merge_base, tip2, first_parent) if not commits2: raise NothingToDoError(tip2, tip1) return (merge_base, commits1, commits2) def get_head_refname(self, short=False): """Return the name of the reference that is currently checked out. If `short` is set, return it as a branch name. If HEAD is currently detached, return None.""" cmd = ['git', 'symbolic-ref', '--quiet'] if short: cmd += ['--short'] cmd += ['HEAD'] try: return check_output(cmd).strip() except CalledProcessError: return None def restore_head(self, refname, message): check_call(['git', 'symbolic-ref', '-m', message, 'HEAD', refname]) check_call(['git', 'reset', '--hard']) def checkout(self, refname, quiet=False): cmd = ['git', 'checkout'] if quiet: cmd += ['--quiet'] if refname.startswith(GitRepository.BRANCH_PREFIX): target = refname[len(GitRepository.BRANCH_PREFIX):] else: target = '%s^0' % (refname,) cmd += [target] check_call(cmd) def commit_tree(self, tree, parents, msg, metadata=None): """Create a commit containing the specified tree. metadata can be author or committer information to be added to the environment, as str objects; e.g., {'GIT_AUTHOR_NAME' : 'me'}. Return the SHA-1 of the new commit object.""" cmd = ['git', 'commit-tree', tree] for parent in parents: cmd += ['-p', parent] if metadata is not None: env = os.environ.copy() env.update(metadata) else: env = os.environ process = subprocess.Popen( cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) out = communicate(process, input=msg)[0] retcode = process.poll() if retcode: # We don't store the output in the CalledProcessError because # the "output" keyword parameter was not supported in Python # 2.6: raise CalledProcessError(retcode, cmd) return out.strip() def revert(self, commit): """Apply the inverse of commit^..commit to HEAD and commit.""" cmd = ['git', 'revert', '--no-edit'] if len(self.get_commit_parents(commit)) > 1: cmd += ['-m', '1'] cmd += [commit] check_call(cmd) def reparent(self, commit, parent_sha1s, msg=None): """Create a new commit object like commit, but with the specified parents. commit is the SHA1 of an existing commit and parent_sha1s is a list of SHA1s. Create a new commit exactly like that one, except that it has the specified parent commits. Return the SHA1 of the resulting commit object, which is already stored in the object database but is not yet referenced by anything. If msg is set, then use it as the commit message for the new commit.""" old_commit = check_output(['git', 'cat-file', 'commit', commit]) separator = old_commit.index('\n\n') headers = old_commit[:separator + 1].splitlines(True) rest = old_commit[separator + 2:] new_commit = StringIO() for i in range(len(headers)): line = headers[i] if line.startswith('tree '): new_commit.write(line) for parent_sha1 in parent_sha1s: new_commit.write('parent %s\n' % (parent_sha1,)) elif line.startswith('parent '): # Discard old parents: pass else: new_commit.write(line) new_commit.write('\n') if msg is None: new_commit.write(rest) else: new_commit.write(msg) if not msg.endswith('\n'): new_commit.write('\n') process = subprocess.Popen( ['git', 'hash-object', '-t', 'commit', '-w', '--stdin'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) out = communicate(process, input=new_commit.getvalue())[0] retcode = process.poll() if retcode: raise Failure('Could not reparent commit %s' % (commit,)) return out.strip() def temporary_head(self, message): """Return a context manager to manage a temporary HEAD. On entry, record the current HEAD state. On exit, restore it. message is used for the reflog. """ return GitTemporaryHead(self, message) class MergeRecord(object): # Bits for the flags field: # There is a saved successful auto merge: SAVED_AUTO = 0x01 # An auto merge (which may have been unsuccessful) has been done: NEW_AUTO = 0x02 # There is a saved successful manual merge: SAVED_MANUAL = 0x04 # A manual merge (which may have been unsuccessful) has been done: NEW_MANUAL = 0x08 # A merge that is currently blocking the merge frontier: BLOCKED = 0x10 # Some useful bit combinations: SAVED = SAVED_AUTO | SAVED_MANUAL NEW = NEW_AUTO | NEW_MANUAL AUTO = SAVED_AUTO | NEW_AUTO MANUAL = SAVED_MANUAL | NEW_MANUAL ALLOWED_INITIAL_FLAGS = [ SAVED_AUTO, SAVED_MANUAL, NEW_AUTO, NEW_MANUAL, ] def __init__(self, sha1=None, flags=0): # The currently believed correct merge, or None if it is # unknown or the best attempt was unsuccessful. self.sha1 = sha1 if self.sha1 is None: if flags != 0: raise ValueError('Initial flags (%s) for sha1=None should be 0' % (flags,)) elif flags not in self.ALLOWED_INITIAL_FLAGS: raise ValueError('Initial flags (%s) is invalid' % (flags,)) # See bits above. self.flags = flags def record_merge(self, sha1, source): """Record a merge at this position. source must be SAVED_AUTO, SAVED_MANUAL, NEW_AUTO, or NEW_MANUAL.""" if source == self.SAVED_AUTO: # SAVED_AUTO is recorded in any case, but only used if it # is the only info available. if self.flags & (self.MANUAL | self.NEW) == 0: self.sha1 = sha1 self.flags |= source elif source == self.NEW_AUTO: # NEW_AUTO is silently ignored if any MANUAL value is # already recorded. if self.flags & self.MANUAL == 0: self.sha1 = sha1 self.flags |= source elif source == self.SAVED_MANUAL: # SAVED_MANUAL is recorded in any case, but only used if # no NEW_MANUAL is available. if self.flags & self.NEW_MANUAL == 0: self.sha1 = sha1 self.flags |= source elif source == self.NEW_MANUAL: # NEW_MANUAL is always used, and also causes NEW_AUTO to # be forgotten if present. self.sha1 = sha1 self.flags = (self.flags | source) & ~self.NEW_AUTO else: raise ValueError('Undefined source: %s' % (source,)) def record_blocked(self, blocked): if blocked: self.flags |= self.BLOCKED else: self.flags &= ~self.BLOCKED def is_known(self): return self.sha1 is not None def is_blocked(self): return self.flags & self.BLOCKED != 0 def is_manual(self): return self.flags & self.MANUAL != 0 def save(self, git, name, i1, i2): """If this record has changed, save it.""" def set_ref(source): git.update_ref( 'refs/imerge/%s/%s/%d-%d' % (name, source, i1, i2), self.sha1, 'imerge %r: Record %s merge' % (name, source,), ) def clear_ref(source): git.delete_ref( 'refs/imerge/%s/%s/%d-%d' % (name, source, i1, i2), 'imerge %r: Remove obsolete %s merge' % (name, source,), ) if self.flags & self.MANUAL: if self.flags & self.AUTO: # Any MANUAL obsoletes any AUTO: if self.flags & self.SAVED_AUTO: clear_ref('auto') self.flags &= ~self.AUTO if self.flags & self.NEW_MANUAL: # Convert NEW_MANUAL to SAVED_MANUAL. if self.sha1: set_ref('manual') self.flags |= self.SAVED_MANUAL elif self.flags & self.SAVED_MANUAL: # Delete any existing SAVED_MANUAL: clear_ref('manual') self.flags &= ~self.SAVED_MANUAL self.flags &= ~self.NEW_MANUAL elif self.flags & self.NEW_AUTO: # Convert NEW_AUTO to SAVED_AUTO. if self.sha1: set_ref('auto') self.flags |= self.SAVED_AUTO elif self.flags & self.SAVED_AUTO: # Delete any existing SAVED_AUTO: clear_ref('auto') self.flags &= ~self.SAVED_AUTO self.flags &= ~self.NEW_AUTO class UnexpectedMergeFailure(Exception): def __init__(self, msg, i1, i2): Exception.__init__(self, msg) self.i1, self.i2 = i1, i2 class BlockCompleteError(Exception): pass class FrontierBlockedError(Exception): def __init__(self, msg, i1, i2): Exception.__init__(self, msg) self.i1 = i1 self.i2 = i2 class NotABlockingCommitError(Exception): pass def find_frontier_blocks(block): """Iterate over the frontier blocks for the specified block. Use bisection to find the blocks. Iterate over the blocks starting in the bottom left and ending at the top right. Record in block any blockers that we find. We make the following assumptions (using Python subscript notation): 0. All of the merges in block[1:,0] and block[0,1:] are already known. (This is an invariant of the Block class.) 1. If a direct merge can be done between block[i1-1,0] and block[0,i2-1], then all of the pairwise merges in block[1:i1, 1:i2] can also be done. 2. If a direct merge fails between block[i1-1,0] and block[0,i2-1], then all of the pairwise merges in block[i1-1:,i2-1:] would also fail. Under these assumptions, the merge frontier is a stepstair pattern going from the bottom-left to the top-right, and bisection can be used to find the transition between mergeable and conflicting in any row or column. Of course these assumptions are not rigorously true, so the frontier blocks returned by this function are only an approximation. We check for and correct inconsistencies later. """ # Given that these diagrams typically have few blocks, check # the end of a range first to see if the whole range can be # determined, and fall back to bisection otherwise. We # determine the frontier block by block, starting in the lower # left. if block.len1 <= 1 or block.len2 <= 1 or block.is_blocked(1, 1): return if block.is_mergeable(block.len1 - 1, block.len2 - 1): # The whole block is mergable! yield block return if not block.is_mergeable(1, 1): # There are no mergeable blocks in block; therefore, # block[1,1] must itself be unmergeable. Record that # fact: block[1, 1].record_blocked(True) return # At this point, we know that there is at least one mergeable # commit in the first column. Find the height of the success # block in column 1: i1 = 1 i2 = find_first_false( lambda i: block.is_mergeable(i1, i), 2, block.len2, ) # Now we know that (1,i2-1) is mergeable but (1,i2) is not; # e.g., (i1, i2) is like 'A' (or maybe 'B') in the following # diagram (where '*' means mergeable, 'x' means not mergeable, # and '?' means indeterminate) and that the merge under 'A' is # not mergeable: # # i1 # # 0123456 # 0 ******* # 1 **????? # i2 2 **????? # 3 **????? # 4 *Axxxxx # 5 *xxxxxx # B while True: if i2 == 1: break # At this point in the loop, we know that any blocks to # the left of 'A' have already been recorded, (i1, i2-1) # is mergeable but (i1, i2) is not; e.g., we are at a # place like 'A' in the following diagram: # # i1 # # 0123456 # 0 **|**** # 1 **|*??? # i2 2 **|*??? # 3 **|Axxx # 4 --+xxxx # 5 *xxxxxx # # This implies that (i1, i2) is the first unmergeable # commit in a blocker block (though blocker blocks are not # recorded explicitly). It also implies that a mergeable # block has its last mergeable commit somewhere in row # i2-1; find its width. if ( i1 == block.len1 - 1 or block.is_mergeable(block.len1 - 1, i2 - 1) ): yield block[:block.len1, :i2] break else: i1 = find_first_false( lambda i: block.is_mergeable(i, i2 - 1), i1 + 1, block.len1 - 1, ) yield block[:i1, :i2] # At this point in the loop, (i1-1, i2-1) is mergeable but # (i1, i2-1) is not; e.g., 'A' in the following diagram: # # i1 # # 0123456 # 0 **|*|** # 1 **|*|?? # i2 2 --+-+xx # 3 **|xxAx # 4 --+xxxx # 5 *xxxxxx # # The block ending at (i1-1,i2-1) has just been recorded. # Now find the height of the conflict rectangle at column # i1 and fill it in: if i2 - 1 == 1 or not block.is_mergeable(i1, 1): break else: i2 = find_first_false( lambda i: block.is_mergeable(i1, i), 2, i2 - 1, ) def write_diagram_with_axes(f, diagram, tip1, tip2): """Write a diagram of one-space-wide characters to file-like object f. Include integers along the top and left sides showing the indexes corresponding to the rows and columns. """ len1 = len(diagram) len2 = len(diagram[0]) # Write the line of i1 numbers: f.write(' ') for i1 in range(0, len1, 5): f.write('%5d' % (i1,)) if (len1 - 1) % 5 == 0: # The last multiple-of-five integer that we just wrote was # the index of the last column. We're done. f.write('\n') else: if (len1 - 1) % 5 == 1: # Add an extra space so that the numbers don't run together: f.write(' ') f.write('%s%d\n' % (' ' * ((len1 - 1) % 5 - 1), len1 - 1,)) # Write a line of '|' marks under the numbers emitted above: f.write(' ') for i1 in range(0, len1, 5): f.write('%5s' % ('|',)) if (len1 - 1) % 5 == 0: # The last multiple-of-five integer was at the last # column. We're done. f.write('\n') elif (len1 - 1) % 5 == 1: # Tilt the tick mark to account for the extra space: f.write(' /\n') else: f.write('%s|\n' % (' ' * ((len1 - 1) % 5 - 1),)) # Write the actual body of the diagram: for i2 in range(len2): if i2 % 5 == 0 or i2 == len2 - 1: f.write('%4d - ' % (i2,)) else: f.write(' ') for i1 in range(len1): f.write(diagram[i1][i2]) if tip1 and i2 == 0: f.write(' - %s\n' % (tip1,)) else: f.write('\n') if tip2: f.write(' |\n') f.write(' %s\n' % (tip2,)) class MergeFrontier(object): """The merge frontier within a Block, and a strategy for filling it. """ # Additional codes used in the 2D array returned from create_diagram() FRONTIER_WITHIN = 0x10 FRONTIER_RIGHT_EDGE = 0x20 FRONTIER_BOTTOM_EDGE = 0x40 FRONTIER_MASK = 0x70 def __init__(self, block): self.block = block def __nonzero__(self): """Alias for __bool__.""" return self.__bool__() @classmethod def default_formatter(cls, node, legend=None): def color(node, within): if within: return AnsiColor.B_GREEN + node + AnsiColor.END else: return AnsiColor.B_RED + node + AnsiColor.END if legend is None: legend = ['?', '*', '.', '#', '@', '-', '|', '+'] merge = node & Block.MERGE_MASK within = merge == Block.MERGE_MANUAL or (node & cls.FRONTIER_WITHIN) skip = [Block.MERGE_MANUAL, Block.MERGE_BLOCKED, Block.MERGE_UNBLOCKED] if merge not in skip: vertex = (cls.FRONTIER_BOTTOM_EDGE | cls.FRONTIER_RIGHT_EDGE) edge_status = node & vertex if edge_status == vertex: return color(legend[-1], within) elif edge_status == cls.FRONTIER_RIGHT_EDGE: return color(legend[-2], within) elif edge_status == cls.FRONTIER_BOTTOM_EDGE: return color(legend[-3], within) return color(legend[merge], within) def create_diagram(self): """Generate a diagram of this frontier. The returned diagram is a nested list of integers forming a 2D array, representing the merge frontier embedded in the diagram of commits returned from Block.create_diagram(). At each node in the returned diagram is an integer whose value is a bitwise-or of existing MERGE_* constant from Block.create_diagram() and possibly zero or more of the FRONTIER_* constants defined in this class. """ return self.block.create_diagram() def format_diagram(self, formatter=None, diagram=None): if formatter is None: formatter = self.default_formatter if diagram is None: diagram = self.create_diagram() return [ [formatter(diagram[i1][i2]) for i2 in range(self.block.len2)] for i1 in range(self.block.len1)] def write(self, f, tip1=None, tip2=None): """Write this frontier to file-like object f.""" write_diagram_with_axes(f, self.format_diagram(), tip1, tip2) def write_html(self, f, name, cssfile='imerge.css', abbrev_sha1=7): class_map = { Block.MERGE_UNKNOWN: 'merge_unknown', Block.MERGE_MANUAL: 'merge_manual', Block.MERGE_AUTOMATIC: 'merge_automatic', Block.MERGE_BLOCKED: 'merge_blocked', Block.MERGE_UNBLOCKED: 'merge_unblocked', self.FRONTIER_WITHIN: 'frontier_within', self.FRONTIER_RIGHT_EDGE: 'frontier_right_edge', self.FRONTIER_BOTTOM_EDGE: 'frontier_bottom_edge', } def map_to_classes(i1, i2, node): merge = node & Block.MERGE_MASK ret = [class_map[merge]] for bit in [self.FRONTIER_WITHIN, self.FRONTIER_RIGHT_EDGE, self.FRONTIER_BOTTOM_EDGE]: if node & bit: ret.append(class_map[bit]) if not (node & self.FRONTIER_WITHIN): ret.append('frontier_without') elif (node & Block.MERGE_MASK) == Block.MERGE_UNKNOWN: ret.append('merge_skipped') if i1 == 0 or i2 == 0: ret.append('merge_initial') if i1 == 0: ret.append('col_left') if i1 == self.block.len1 - 1: ret.append('col_right') if i2 == 0: ret.append('row_top') if i2 == self.block.len2 - 1: ret.append('row_bottom') return ret f.write("""\ <html> <head> <title>git-imerge: %s</title> <link rel="stylesheet" href="%s" type="text/css" /> </head> <body> <table id="imerge"> """ % (name, cssfile)) diagram = self.create_diagram() f.write(' <tr>\n') f.write(' <th class="indexes">&nbsp;</td>\n') for i1 in range(self.block.len1): f.write(' <th class="indexes">%d-*</td>\n' % (i1,)) f.write(' </tr>\n') for i2 in range(self.block.len2): f.write(' <tr>\n') f.write(' <th class="indexes">*-%d</td>\n' % (i2,)) for i1 in range(self.block.len1): classes = map_to_classes(i1, i2, diagram[i1][i2]) record = self.block.get_value(i1, i2) sha1 = record.sha1 or '' td_id = record.sha1 and ' id="%s"' % (record.sha1) or '' td_class = classes and ' class="' + ' '.join(classes) + '"' or '' f.write(' <td%s%s>%.*s</td>\n' % ( td_id, td_class, abbrev_sha1, sha1)) f.write(' </tr>\n') f.write('</table>\n</body>\n</html>\n') class FullMergeFrontier(MergeFrontier): """A MergeFrontier that is to be filled completely. """ @staticmethod def map_known_frontier(block): return FullMergeFrontier(block) def __bool__(self): """Return True iff this frontier contains any merges. """ return (1, 1) in self.block def is_complete(self): """Return True iff the frontier covers the whole block.""" return (self.block.len1 - 1, self.block.len2 - 1) in self.block def incorporate_merge(self, i1, i2): """Incorporate a successful merge at (i1, i2). Raise NotABlockingCommitError if that merge was not a blocker. """ if not self.block[i1, i2].is_blocked(): raise NotABlockingCommitError( 'Commit %d-%d was not on the frontier.' % self.block.get_original_indexes(i1, i2) ) else: self.block[i1, i2].record_blocked(False) def auto_expand(self): block = self.block len2 = block.len2 blocker = None for i1 in range(1, block.len1): for i2 in range(1, len2): if (i1, i2) in block: pass elif block.is_blocked(i1, i2): if blocker is None: blocker = (i1, i2) len2 = i2 # Done with this row: break elif block.auto_fill_micromerge(i1, i2): # Merge successful pass else: block[i1, i2].record_blocked(True) if blocker is None: blocker = (i1, i2) len2 = i2 # Done with this row: break if blocker: i1orig, i2orig = self.block.get_original_indexes(*blocker) raise FrontierBlockedError( 'Conflict; suggest manual merge of %d-%d' % (i1orig, i2orig), i1orig, i2orig, ) else: raise BlockCompleteError('The block is already complete') class ManualMergeFrontier(FullMergeFrontier): """A FullMergeFrontier that is to be filled completely by user merges. """ @staticmethod def map_known_frontier(block): return ManualMergeFrontier(block) def auto_expand(self): block = self.block for i1 in range(1, block.len1): for i2 in range(1, block.len2): if (i1, i2) not in block: i1orig, i2orig = block.get_original_indexes(i1, i2) raise FrontierBlockedError( 'Manual merges requested; please merge %d-%d' % (i1orig, i2orig), i1orig, i2orig ) raise BlockCompleteError('The block is already complete') class BlockwiseMergeFrontier(MergeFrontier): """A MergeFrontier that is filled blockwise, using outlining. A BlockwiseMergeFrontier is represented by a list of SubBlocks, each of which is thought to be completely mergeable. The list is kept in normalized form: * Only non-empty blocks are retained * Blocks are sorted from bottom left to upper right * No redundant blocks """ @staticmethod def map_known_frontier(block): """Return the object describing existing successful merges in block. The return value only includes the part that is fully outlined and whose outline consists of rectangles reaching back to (0,0). A blocked commit is *not* considered to be within the frontier, even if a merge is registered for it. Such merges must be explicitly unblocked.""" # FIXME: This algorithm can take combinatorial time, for # example if there is a big block of merges that is a dead # end: # # +++++++ # +?+++++ # +?+++++ # +?+++++ # +?*++++ # # The problem is that the algorithm will explore all of the # ways of getting to commit *, and the number of paths grows # like a binomial coefficient. The solution would be to # remember dead-ends and reject any curves that visit a point # to the right of a dead-end. # # For now we don't intend to allow a situation like this to be # created, so we ignore the problem. # A list (i1, i2, down) of points in the path so far. down is # True iff the attempted step following this one was # downwards. path = [] def create_frontier(path): blocks = [] for ((i1old, i2old, downold), (i1new, i2new, downnew)) in iter_neighbors(path): if downold is True and downnew is False: blocks.append(block[:i1new + 1, :i2new + 1]) return BlockwiseMergeFrontier(block, blocks) # Loop invariants: # # * path is a valid path # # * (i1, i2) is in block but it not yet added to path # # * down is True if a step downwards from (i1, i2) has not yet # been attempted (i1, i2) = (block.len1 - 1, 0) down = True while True: if down: if i2 == block.len2 - 1: # Hit edge of block; can't move down: down = False elif (i1, i2 + 1) in block and not block.is_blocked(i1, i2 + 1): # Can move down path.append((i1, i2, True)) i2 += 1 else: # Can't move down. down = False else: if i1 == 0: # Success! path.append((i1, i2, False)) return create_frontier(path) elif (i1 - 1, i2) in block and not block.is_blocked(i1 - 1, i2): # Can move left path.append((i1, i2, False)) down = True i1 -= 1 else: # There's no way to go forward; backtrack until we # find a place where we can still try going left: while True: try: (i1, i2, down) = path.pop() except IndexError: # This shouldn't happen because, in the # worst case, there is a valid path across # the top edge of the merge diagram. raise RuntimeError('Block is improperly formed!') if down: down = False break @staticmethod def initiate_merge(block): """Return a BlockwiseMergeFrontier instance for block. Compute the blocks making up the boundary using bisection (see find_frontier_blocks() for more information). Outline the blocks, then return a BlockwiseMergeFrontier reflecting the final result. """ top_level_frontier = BlockwiseMergeFrontier( block, list(find_frontier_blocks(block)), ) # Now outline the mergeable blocks, backtracking if there are # any unexpected merge failures: frontier = top_level_frontier while frontier: subblock = next(iter(frontier)) try: subblock.auto_outline() except UnexpectedMergeFailure as e: # One of the merges that we expected to succeed in # fact failed. frontier.remove_failure(e.i1, e.i2) if (e.i1, e.i2) == (1, 1): # The failed merge was the first micromerge that we'd # need for `best_block`, so record it as a blocker: subblock[1, 1].record_blocked(True) if frontier is not top_level_frontier: # Report that failure back to the top-level # frontier, too (but first we have to translate # the indexes): (i1orig, i2orig) = subblock.get_original_indexes(e.i1, e.i2) top_level_frontier.remove_failure( *block.convert_original_indexes(i1orig, i2orig)) # Restart loop for the same frontier... else: # We're only interested in subfrontiers that contain # mergeable subblocks: sub_frontiers = [f for f in frontier.partition(subblock) if f] if not sub_frontiers: break # Since we just outlined the first (i.e., leftmost) # mergeable block in `frontier`, # `frontier.partition()` can at most have returned a # single non-empty value, namely one to the right of # `subblock`. [frontier] = sub_frontiers return top_level_frontier def __init__(self, block, blocks=None): MergeFrontier.__init__(self, block) self.blocks = self._normalized_blocks(blocks or []) def __iter__(self): """Iterate over blocks from bottom left to upper right.""" return iter(self.blocks) def __bool__(self): """Return True iff this frontier contains any SubBlocks. Return True if this BlockwiseMergeFrontier contains any SubBlocks that are thought to be completely mergeable (whether they have been outlined or not). """ return bool(self.blocks) def is_complete(self): """Return True iff the frontier covers the whole block.""" return ( len(self.blocks) == 1 and self.blocks[0].len1 == self.block.len1 and self.blocks[0].len2 == self.block.len2 ) @staticmethod def _normalized_blocks(blocks): """Return a normalized list of blocks from the argument. * Remove empty blocks. * Remove redundant blocks. * Sort the blocks according to their len1 members. """ def contains(block1, block2): """Return true if block1 contains block2.""" return block1.len1 >= block2.len1 and block1.len2 >= block2.len2 blocks = sorted(blocks, key=lambda block: block.len1) ret = [] for block in blocks: if block.len1 == 0 or block.len2 == 0: continue while True: if not ret: ret.append(block) break last = ret[-1] if contains(last, block): break elif contains(block, last): ret.pop() else: ret.append(block) break return ret def remove_failure(self, i1, i2): """Refine the merge frontier given that the specified merge fails.""" newblocks = [] shrunk_block = False for block in self.blocks: if i1 < block.len1 and i2 < block.len2: if i1 > 1: newblocks.append(block[:i1, :]) if i2 > 1: newblocks.append(block[:, :i2]) shrunk_block = True else: newblocks.append(block) if shrunk_block: self.blocks = self._normalized_blocks(newblocks) def partition(self, block): """Iterate over the BlockwiseMergeFrontiers partitioned by block. Iterate over the zero, one, or two BlockwiseMergeFrontiers to the left and/or right of block. block must be contained in this frontier and already be outlined. """ # Remember that the new blocks have to include the outlined # edge of the partitioning block to satisfy the invariant that # the left and upper edge of a block has to be known. left = [] right = [] for b in self.blocks: if b.len1 == block.len1 and b.len2 == block.len2: # That's the block we're partitioning on; just skip it. pass elif b.len1 < block.len1 and b.len2 > block.len2: left.append(b[:, block.len2 - 1:]) elif b.len1 > block.len1 and b.len2 < block.len2: right.append(b[block.len1 - 1:, :]) else: raise ValueError( 'BlockwiseMergeFrontier partitioned with inappropriate block' ) if block.len2 < self.block.len2: yield BlockwiseMergeFrontier(self.block[:block.len1, block.len2 - 1:], left) if block.len1 < self.block.len1: yield BlockwiseMergeFrontier(self.block[block.len1 - 1:, :block.len2], right) def iter_boundary_blocks(self): """Iterate over the complete blocks that form this block's boundary. Iterate over them from bottom left to top right. This is like self.blocks, except that it also includes the implicit blocks at self.block[0, :] and self.blocks[:, 0] if they are needed to complete the boundary. """ if not self or self.blocks[0].len2 < self.block.len2: yield self.block[0, :] for block in self: yield block if not self or self.blocks[-1].len1 < self.block.len1: yield self.block[:, 0] def iter_blocker_blocks(self): """Iterate over the blocks on the far side of this frontier. This must only be called for an outlined frontier.""" for block1, block2 in iter_neighbors(self.iter_boundary_blocks()): yield self.block[block1.len1 - 1:block2.len1, block2.len2 - 1: block1.len2] def get_affected_blocker_block(self, i1, i2): """Return the blocker block that a successful merge (i1,i2) would unblock. If there is no such block, raise NotABlockingCommitError.""" for block in self.iter_blocker_blocks(): try: (block_i1, block_i2) = block.convert_original_indexes(i1, i2) except IndexError: pass else: if (block_i1, block_i2) == (1, 1): # That's the one we need to improve this block: return block else: # An index pair can only be in a single blocker # block, which we've already found: raise NotABlockingCommitError( 'Commit %d-%d was not blocking the frontier.' % self.block.get_original_indexes(i1, i2) ) else: raise NotABlockingCommitError( 'Commit %d-%d was not on the frontier.' % self.block.get_original_indexes(i1, i2) ) def incorporate_merge(self, i1, i2): """Incorporate a successful merge at (i1, i2). Raise NotABlockingCommitError if that merge was not a blocker. """ unblocked_block = self.get_affected_blocker_block(i1, i2) unblocked_block[1, 1].record_blocked(False) def auto_expand(self): """Try pushing out one of the blocks on this frontier. Raise BlockCompleteError if the whole block has already been solved. Raise FrontierBlockedError if the frontier is blocked everywhere. This method does *not* update self; if it returns successfully you should recompute the frontier from scratch.""" blocks = list(self.iter_blocker_blocks()) if not blocks: raise BlockCompleteError('The block is already complete') # Try blocks from left to right: blocks.sort(key=lambda block: block.get_original_indexes(0, 0)) for block in blocks: merge_frontier = BlockwiseMergeFrontier.initiate_merge(block) if bool(merge_frontier): return else: # None of the blocks could be expanded. Suggest that the # caller do a manual merge of the commit that is blocking # the leftmost blocker block. i1, i2 = blocks[0].get_original_indexes(1, 1) raise FrontierBlockedError( 'Conflict; suggest manual merge of %d-%d' % (i1, i2), i1, i2 ) def create_diagram(self): """Generate a diagram of this frontier. This method adds FRONTIER_* bits to the diagram generated by the super method. """ diagram = MergeFrontier.create_diagram(self) try: next_block = self.blocks[0] except IndexError: next_block = None diagram[0][-1] |= self.FRONTIER_BOTTOM_EDGE for i2 in range(1, self.block.len2): if next_block is None or i2 >= next_block.len2: diagram[0][i2] |= self.FRONTIER_RIGHT_EDGE prev_block = None for n in range(len(self.blocks)): block = self.blocks[n] try: next_block = self.blocks[n + 1] except IndexError: next_block = None for i1 in range(block.len1): for i2 in range(block.len2): v = self.FRONTIER_WITHIN if i1 == block.len1 - 1 and ( next_block is None or i2 >= next_block.len2 ): v |= self.FRONTIER_RIGHT_EDGE if i2 == block.len2 - 1 and ( prev_block is None or i1 >= prev_block.len1 ): v |= self.FRONTIER_BOTTOM_EDGE diagram[i1][i2] |= v prev_block = block try: prev_block = self.blocks[-1] except IndexError: prev_block = None for i1 in range(1, self.block.len1): if prev_block is None or i1 >= prev_block.len1: diagram[i1][0] |= self.FRONTIER_BOTTOM_EDGE diagram[-1][0] |= self.FRONTIER_RIGHT_EDGE return diagram class NoManualMergeError(Exception): pass class ManualMergeUnusableError(Exception): def __init__(self, msg, commit): Exception.__init__(self, 'Commit %s is not usable; %s' % (commit, msg)) self.commit = commit class CommitNotFoundError(Exception): def __init__(self, commit): Exception.__init__( self, 'Commit %s was not found among the known merge commits' % (commit,), ) self.commit = commit class Block(object): """A rectangular range of commits, indexed by (i1,i2). The commits block[0,1:] and block[1:,0] are always all known. block[0,0] may or may not be known; it is usually unneeded (except maybe implicitly). Members: name -- the name of the imerge of which this block is part. len1, len2 -- the dimensions of the block. """ def __init__(self, git, name, len1, len2): self.git = git self.name = name self.len1 = len1 self.len2 = len2 def get_merge_state(self): """Return the MergeState instance containing this Block.""" raise NotImplementedError() def get_area(self): """Return the area of this block, ignoring the known edges.""" return (self.len1 - 1) * (self.len2 - 1) def _check_indexes(self, i1, i2): if not (0 <= i1 < self.len1): raise IndexError('first index (%s) is out of range 0:%d' % (i1, self.len1,)) if not (0 <= i2 < self.len2): raise IndexError('second index (%s) is out of range 0:%d' % (i2, self.len2,)) def _normalize_indexes(self, index): """Return a pair of non-negative integers (i1, i2).""" try: (i1, i2) = index except TypeError: raise IndexError('Block indexing requires exactly two indexes') if i1 < 0: i1 += self.len1 if i2 < 0: i2 += self.len2 self._check_indexes(i1, i2) return (i1, i2) def get_original_indexes(self, i1, i2): """Return the original indexes corresponding to (i1,i2) in this block. This function supports negative indexes.""" return self._normalize_indexes((i1, i2)) def convert_original_indexes(self, i1, i2): """Return the indexes in this block corresponding to original indexes (i1,i2). raise IndexError if they are not within this block. This method does not support negative indices.""" return (i1, i2) def _set_value(self, i1, i2, value): """Set the MergeRecord for integer indexes (i1, i2). i1 and i2 must be non-negative.""" raise NotImplementedError() def get_value(self, i1, i2): """Return the MergeRecord for integer indexes (i1, i2). i1 and i2 must be non-negative.""" raise NotImplementedError() def __getitem__(self, index): """Return the MergeRecord at (i1, i2) (requires two indexes). If i1 and i2 are integers but the merge is unknown, return None. If either index is a slice, return a SubBlock.""" try: (i1, i2) = index except TypeError: raise IndexError('Block indexing requires exactly two indexes') if isinstance(i1, slice) or isinstance(i2, slice): return SubBlock(self, i1, i2) else: return self.get_value(*self._normalize_indexes((i1, i2))) def __contains__(self, index): return self[index].is_known() def is_blocked(self, i1, i2): """Return True iff the specified commit is blocked.""" (i1, i2) = self._normalize_indexes((i1, i2)) return self[i1, i2].is_blocked() def is_mergeable(self, i1, i2): """Determine whether (i1,i2) can be merged automatically. If we already have a merge record for (i1,i2), return True. Otherwise, attempt a merge (discarding the result).""" (i1, i2) = self._normalize_indexes((i1, i2)) if (i1, i2) in self: return True else: sys.stderr.write( 'Attempting automerge of %d-%d...' % self.get_original_indexes(i1, i2) ) try: self.git.automerge(self[i1, 0].sha1, self[0, i2].sha1) except AutomaticMergeFailed: sys.stderr.write('failure.\n') return False else: sys.stderr.write('success.\n') return True def auto_outline(self): """Complete the outline of this Block. raise UnexpectedMergeFailure if automerging fails.""" # Check that all of the merges go through before recording any # of them permanently. merges = [] def do_merge(i1, commit1, i2, commit2, msg='Autofilling %d-%d...', record=True): if (i1, i2) in self: return self[i1, i2].sha1 (i1orig, i2orig) = self.get_original_indexes(i1, i2) sys.stderr.write(msg % (i1orig, i2orig)) logmsg = 'imerge \'%s\': automatic merge %d-%d' % (self.name, i1orig, i2orig) try: merge = self.git.automerge(commit1, commit2, msg=logmsg) except AutomaticMergeFailed as e: sys.stderr.write('unexpected conflict. Backtracking...\n') raise UnexpectedMergeFailure(str(e), i1, i2) else: sys.stderr.write('success.\n') if record: merges.append((i1, i2, merge)) return merge i2 = self.len2 - 1 left = self[0, i2].sha1 for i1 in range(1, self.len1 - 1): left = do_merge(i1, self[i1, 0].sha1, i2, left) i1 = self.len1 - 1 above = self[i1, 0].sha1 for i2 in range(1, self.len2 - 1): above = do_merge(i1, above, i2, self[0, i2].sha1) i1, i2 = self.len1 - 1, self.len2 - 1 if i1 > 1 and i2 > 1: # We will compare two ways of doing the final "vertex" merge: # as a continuation of the bottom edge, or as a continuation # of the right edge. We only accept it if both approaches # succeed and give identical trees. vertex_v1 = do_merge( i1, self[i1, 0].sha1, i2, left, msg='Autofilling %d-%d (first way)...', record=False, ) vertex_v2 = do_merge( i1, above, i2, self[0, i2].sha1, msg='Autofilling %d-%d (second way)...', record=False, ) if self.git.get_tree(vertex_v1) == self.git.get_tree(vertex_v2): sys.stderr.write( 'The two ways of autofilling %d-%d agree.\n' % self.get_original_indexes(i1, i2) ) # Everything is OK. Now reparent the actual vertex merge to # have above and left as its parents: merges.append( (i1, i2, self.git.reparent(vertex_v1, [above, left])) ) else: sys.stderr.write( 'The two ways of autofilling %d-%d do not agree. Backtracking...\n' % self.get_original_indexes(i1, i2) ) raise UnexpectedMergeFailure('Inconsistent vertex merges', i1, i2) else: do_merge( i1, above, i2, left, msg='Autofilling %d-%d...', ) # Done! Now we can record the results: sys.stderr.write('Recording autofilled block %s.\n' % (self,)) for (i1, i2, merge) in merges: self[i1, i2].record_merge(merge, MergeRecord.NEW_AUTO) def auto_fill_micromerge(self, i1=1, i2=1): """Try to fill micromerge (i1, i2) in this block (default (1, 1)). Return True iff the attempt was successful.""" assert (i1, i2) not in self assert (i1 - 1, i2) in self assert (i1, i2 - 1) in self if self.len1 <= i1 or self.len2 <= i2 or self.is_blocked(i1, i2): return False (i1orig, i2orig) = self.get_original_indexes(i1, i2) sys.stderr.write('Attempting to merge %d-%d...' % (i1orig, i2orig)) logmsg = 'imerge \'%s\': automatic merge %d-%d' % (self.name, i1orig, i2orig) try: merge = self.git.automerge( self[i1, i2 - 1].sha1, self[i1 - 1, i2].sha1, msg=logmsg, ) except AutomaticMergeFailed: sys.stderr.write('conflict.\n') self[i1, i2].record_blocked(True) return False else: sys.stderr.write('success.\n') self[i1, i2].record_merge(merge, MergeRecord.NEW_AUTO) return True # The codes in the 2D array returned from create_diagram() MERGE_UNKNOWN = 0 MERGE_MANUAL = 1 MERGE_AUTOMATIC = 2 MERGE_BLOCKED = 3 MERGE_UNBLOCKED = 4 MERGE_MASK = 7 # A map {(is_known(), manual, is_blocked()) : integer constant} MergeState = { (False, False, False): MERGE_UNKNOWN, (False, False, True): MERGE_BLOCKED, (True, False, True): MERGE_UNBLOCKED, (True, True, True): MERGE_UNBLOCKED, (True, False, False): MERGE_AUTOMATIC, (True, True, False): MERGE_MANUAL, } def create_diagram(self): """Generate a diagram of this Block. The returned diagram, is a nested list of integers forming a 2D array, where the integer at diagram[i1][i2] is one of MERGE_UNKNOWN, MERGE_MANUAL, MERGE_AUTOMATIC, MERGE_BLOCKED, or MERGE_UNBLOCKED, representing the state of the commit at (i1, i2).""" diagram = [[None for i2 in range(self.len2)] for i1 in range(self.len1)] for i2 in range(self.len2): for i1 in range(self.len1): rec = self.get_value(i1, i2) c = self.MergeState[ rec.is_known(), rec.is_manual(), rec.is_blocked()] diagram[i1][i2] = c return diagram def format_diagram(self, legend=None, diagram=None): if legend is None: legend = [ AnsiColor.D_GRAY + '?' + AnsiColor.END, AnsiColor.B_GREEN + '*' + AnsiColor.END, AnsiColor.B_GREEN + '.' + AnsiColor.END, AnsiColor.B_RED + '#' + AnsiColor.END, AnsiColor.B_YELLOW + '@' + AnsiColor.END, ] if diagram is None: diagram = self.create_diagram() return [ [legend[diagram[i1][i2]] for i2 in range(self.len2)] for i1 in range(self.len1)] def write(self, f, tip1='', tip2=''): write_diagram_with_axes(f, self.format_diagram(), tip1, tip2) def writeppm(self, f): legend = ['127 127 0', '0 255 0', '0 127 0', '255 0 0', '127 0 0'] diagram = self.format_diagram(legend) f.write('P3\n') f.write('%d %d 255\n' % (self.len1, self.len2,)) for i2 in range(self.len2): f.write(' '.join(diagram[i1][i2] for i1 in range(self.len1)) + '\n') class SubBlock(Block): @staticmethod def _convert_to_slice(i, len): """Return (start, len) for the specified index. i may be an integer or a slice with step equal to 1.""" if isinstance(i, int): if i < 0: i += len i = slice(i, i + 1) elif isinstance(i, slice): if i.step is not None and i.step != 1: raise ValueError('Index has a non-zero step size') else: raise ValueError('Index cannot be converted to a slice') (start, stop, step) = i.indices(len) return (start, stop - start) def __init__(self, block, slice1, slice2): (start1, len1) = self._convert_to_slice(slice1, block.len1) (start2, len2) = self._convert_to_slice(slice2, block.len2) Block.__init__(self, block.git, block.name, len1, len2) if isinstance(block, SubBlock): # Peel away one level of indirection: self._merge_state = block._merge_state self._start1 = start1 + block._start1 self._start2 = start2 + block._start2 else: assert(isinstance(block, MergeState)) self._merge_state = block self._start1 = start1 self._start2 = start2 def get_merge_state(self): return self._merge_state def get_original_indexes(self, i1, i2): i1, i2 = self._normalize_indexes((i1, i2)) return self._merge_state.get_original_indexes( i1 + self._start1, i2 + self._start2, ) def convert_original_indexes(self, i1, i2): (i1, i2) = self._merge_state.convert_original_indexes(i1, i2) if not ( self._start1 <= i1 < self._start1 + self.len1 and self._start2 <= i2 < self._start2 + self.len2 ): raise IndexError('Indexes are not within block') return (i1 - self._start1, i2 - self._start2) def _set_value(self, i1, i2, sha1, flags): self._check_indexes(i1, i2) self._merge_state._set_value( i1 + self._start1, i2 + self._start2, sha1, flags, ) def get_value(self, i1, i2): self._check_indexes(i1, i2) return self._merge_state.get_value(i1 + self._start1, i2 + self._start2) def __str__(self): return '%s[%d:%d,%d:%d]' % ( self._merge_state, self._start1, self._start1 + self.len1, self._start2, self._start2 + self.len2, ) class MissingMergeFailure(Failure): def __init__(self, i1, i2): Failure.__init__(self, 'Merge %d-%d is not yet done' % (i1, i2)) self.i1 = i1 self.i2 = i2 class MergeState(Block): SOURCE_TABLE = { 'auto': MergeRecord.SAVED_AUTO, 'manual': MergeRecord.SAVED_MANUAL, } @staticmethod def get_scratch_refname(name): return 'refs/heads/imerge/%s' % (name,) @staticmethod def _check_no_merges(git, commits): multiparent_commits = [ commit for commit in commits if len(git.get_commit_parents(commit)) > 1 ] if multiparent_commits: raise Failure( 'The following commits on the to-be-rebased branch are merge commits:\n' ' %s\n' '--goal=\'rebase\' is not yet supported for branches that include merges.\n' % ('\n '.join(multiparent_commits),) ) @staticmethod def initialize( git, name, merge_base, tip1, commits1, tip2, commits2, goal=DEFAULT_GOAL, goalopts=None, manual=False, branch=None, ): """Create and return a new MergeState object.""" git.verify_imerge_name_available(name) if branch: git.check_branch_name_format(branch) else: branch = name if goal == 'rebase': MergeState._check_no_merges(git, commits2) return MergeState( git, name, merge_base, tip1, commits1, tip2, commits2, MergeRecord.NEW_MANUAL, goal=goal, goalopts=goalopts, manual=manual, branch=branch, ) @staticmethod def read(git, name): (state, merges) = git.read_imerge_state(name) # Translate sources from strings into MergeRecord constants # SAVED_AUTO or SAVED_MANUAL: merges = dict(( ((i1, i2), (sha1, MergeState.SOURCE_TABLE[source])) for ((i1, i2), (sha1, source)) in merges.items() )) blockers = state.get('blockers', []) # Find merge_base, commits1, and commits2: (merge_base, source) = merges.pop((0, 0)) if source != MergeRecord.SAVED_MANUAL: raise Failure('Merge base should be manual!') commits1 = [] for i1 in itertools.count(1): try: (sha1, source) = merges.pop((i1, 0)) if source != MergeRecord.SAVED_MANUAL: raise Failure('Merge %d-0 should be manual!' % (i1,)) commits1.append(sha1) except KeyError: break commits2 = [] for i2 in itertools.count(1): try: (sha1, source) = merges.pop((0, i2)) if source != MergeRecord.SAVED_MANUAL: raise Failure('Merge (0,%d) should be manual!' % (i2,)) commits2.append(sha1) except KeyError: break tip1 = state.get('tip1', commits1[-1]) tip2 = state.get('tip2', commits2[-1]) goal = state['goal'] if goal not in ALLOWED_GOALS: raise Failure('Goal %r, read from state, is not recognized.' % (goal,)) goalopts = state['goalopts'] manual = state['manual'] branch = state.get('branch', name) state = MergeState( git, name, merge_base, tip1, commits1, tip2, commits2, MergeRecord.SAVED_MANUAL, goal=goal, goalopts=goalopts, manual=manual, branch=branch, ) # Now write the rest of the merges to state: for ((i1, i2), (sha1, source)) in merges.items(): if i1 == 0 and i2 >= state.len2: raise Failure('Merge 0-%d is missing!' % (state.len2,)) if i1 >= state.len1 and i2 == 0: raise Failure('Merge %d-0 is missing!' % (state.len1,)) if i1 >= state.len1 or i2 >= state.len2: raise Failure( 'Merge %d-%d is out of range [0:%d,0:%d]' % (i1, i2, state.len1, state.len2) ) state[i1, i2].record_merge(sha1, source) # Record any blockers: for (i1, i2) in blockers: state[i1, i2].record_blocked(True) return state @staticmethod def remove(git, name): # If HEAD is the scratch refname, abort any in-progress # commits and detach HEAD: scratch_refname = MergeState.get_scratch_refname(name) if git.get_head_refname() == scratch_refname: try: git.abort_merge() except CalledProcessError: pass # Detach head so that we can delete scratch_refname: git.detach('Detach HEAD from %s' % (scratch_refname,)) # Delete the scratch refname: git.delete_ref( scratch_refname, 'imerge %s: remove scratch reference' % (name,), ) # Remove any references referring to intermediate merges: git.delete_imerge_refs(name) # If this merge was the default, unset the default: if git.get_default_imerge_name() == name: git.set_default_imerge_name(None) def __init__( self, git, name, merge_base, tip1, commits1, tip2, commits2, source, goal=DEFAULT_GOAL, goalopts=None, manual=False, branch=None, ): Block.__init__(self, git, name, len(commits1) + 1, len(commits2) + 1) self.tip1 = tip1 self.tip2 = tip2 self.goal = goal self.goalopts = goalopts self.manual = bool(manual) self.branch = branch or name # A simulated 2D array. Values are None or MergeRecord instances. self._data = [[None] * self.len2 for i1 in range(self.len1)] self.get_value(0, 0).record_merge(merge_base, source) for (i1, commit) in enumerate(commits1, 1): self.get_value(i1, 0).record_merge(commit, source) for (i2, commit) in enumerate(commits2, 1): self.get_value(0, i2).record_merge(commit, source) def get_merge_state(self): return self def set_goal(self, goal): if goal not in ALLOWED_GOALS: raise ValueError('%r is not an allowed goal' % (goal,)) if goal == 'rebase': self._check_no_merges( self.git, [self[0, i2].sha1 for i2 in range(1, self.len2)], ) self.goal = goal def _set_value(self, i1, i2, value): self._data[i1][i2] = value def get_value(self, i1, i2): value = self._data[i1][i2] # Missing values spring to life on first access: if value is None: value = MergeRecord() self._data[i1][i2] = value return value def __contains__(self, index): # Avoid creating new MergeRecord objects here. (i1, i2) = self._normalize_indexes(index) value = self._data[i1][i2] return (value is not None) and value.is_known() def map_frontier(self): """Return a MergeFrontier instance describing the current frontier. """ if self.manual: return ManualMergeFrontier.map_known_frontier(self) elif self.goal == 'full': return FullMergeFrontier.map_known_frontier(self) else: return BlockwiseMergeFrontier.map_known_frontier(self) def auto_complete_frontier(self): """Complete the frontier using automerges. If progress is blocked before the frontier is complete, raise a FrontierBlockedError. Save the state as progress is made.""" progress_made = False try: while True: frontier = self.map_frontier() try: frontier.auto_expand() finally: self.save() progress_made = True except BlockCompleteError: return except FrontierBlockedError as e: if not progress_made: # Adjust the error message: raise FrontierBlockedError( 'No progress was possible; suggest manual merge of %d-%d' % (e.i1, e.i2), e.i1, e.i2, ) else: raise def find_index(self, commit): """Return (i1,i2) for the specified commit. Raise CommitNotFoundError if it is not known.""" for i2 in range(0, self.len2): for i1 in range(0, self.len1): if (i1, i2) in self: record = self[i1, i2] if record.sha1 == commit: return (i1, i2) raise CommitNotFoundError(commit) def request_user_merge(self, i1, i2): """Prepare the working tree for the user to do a manual merge. It is assumed that the merges above and to the left of (i1, i2) are already done.""" above = self[i1, i2 - 1] left = self[i1 - 1, i2] if not above.is_known() or not left.is_known(): raise RuntimeError('The parents of merge %d-%d are not ready' % (i1, i2)) refname = MergeState.get_scratch_refname(self.name) self.git.update_ref( refname, above.sha1, 'imerge %r: Prepare merge %d-%d' % (self.name, i1, i2,), ) self.git.checkout(refname) logmsg = 'imerge \'%s\': manual merge %d-%d' % (self.name, i1, i2) try: self.git.manualmerge(left.sha1, logmsg) except CalledProcessError: # We expect an error (otherwise we would have automerged!) pass sys.stderr.write( '\n' 'Original first commit:\n' ) self.git.summarize_commit(self[i1, 0].sha1) sys.stderr.write( '\n' 'Original second commit:\n' ) self.git.summarize_commit(self[0, i2].sha1) sys.stderr.write( '\n' 'There was a conflict merging commit %d-%d, shown above.\n' 'Please resolve the conflict, commit the result, then type\n' '\n' ' git-imerge continue\n' % (i1, i2) ) def incorporate_manual_merge(self, commit): """Record commit as a manual merge of its parents. Return the indexes (i1,i2) where it was recorded. If the commit is not usable for some reason, raise ManualMergeUnusableError.""" parents = self.git.get_commit_parents(commit) if len(parents) < 2: raise ManualMergeUnusableError('it is not a merge', commit) if len(parents) > 2: raise ManualMergeUnusableError('it is an octopus merge', commit) # Find the parents among our contents... try: (i1first, i2first) = self.find_index(parents[0]) (i1second, i2second) = self.find_index(parents[1]) except CommitNotFoundError: raise ManualMergeUnusableError( 'its parents are not known merge commits', commit, ) swapped = False if i1first < i1second: # Swap parents to make the parent from above the first parent: (i1first, i2first, i1second, i2second) = (i1second, i2second, i1first, i2first) swapped = True if i1first != i1second + 1 or i2first != i2second - 1: raise ManualMergeUnusableError( 'it is not a pairwise merge of adjacent parents', commit, ) if swapped: # Create a new merge with the parents in the conventional order: commit = self.git.reparent(commit, [parents[1], parents[0]]) i1, i2 = i1first, i2second self[i1, i2].record_merge(commit, MergeRecord.NEW_MANUAL) return (i1, i2) def incorporate_user_merge(self, edit_log_msg=None): """If the user has done a merge for us, incorporate the results. If the scratch reference refs/heads/imerge/NAME exists and is checked out, first check if there are staged changes that can be committed. Then try to incorporate the current commit into this MergeState, delete the reference, and return (i1,i2) corresponding to the merge. If the scratch reference does not exist, raise NoManualMergeError(). If the scratch reference exists but cannot be used, raise a ManualMergeUnusableError. If there are unstaged changes in the working tree, emit an error message and raise UncleanWorkTreeError. """ refname = MergeState.get_scratch_refname(self.name) try: commit = self.git.get_commit_sha1(refname) except ValueError: raise NoManualMergeError('Reference %s does not exist.' % (refname,)) head_name = self.git.get_head_refname() if head_name is None: raise NoManualMergeError('HEAD is currently detached.') elif head_name != refname: # This should not usually happen. The scratch reference # exists, but it is not current. Perhaps the user gave up on # an attempted merge then switched to another branch. We want # to delete refname, but only if it doesn't contain any # content that we don't already know. try: self.find_index(commit) except CommitNotFoundError: # It points to a commit that we don't have in our records. raise Failure( 'The scratch reference, %(refname)s, already exists but is not\n' 'checked out. If it points to a merge commit that you would like\n' 'to use, please check it out using\n' '\n' ' git checkout %(refname)s\n' '\n' 'and then try to continue again. If it points to a commit that is\n' 'unneeded, then please delete the reference using\n' '\n' ' git update-ref -d %(refname)s\n' '\n' 'and then continue.' % dict(refname=refname) ) else: # It points to a commit that is already recorded. We can # delete it without losing any information. self.git.delete_ref( refname, 'imerge %r: Remove obsolete scratch reference' % (self.name,), ) sys.stderr.write( '%s did not point to a new merge; it has been deleted.\n' % (refname,) ) raise NoManualMergeError( 'Reference %s was not checked out.' % (refname,) ) # If we reach this point, then the scratch reference exists and is # checked out. Now check whether there is staged content that # can be committed: if self.git.commit_user_merge(edit_log_msg=edit_log_msg): commit = self.git.get_commit_sha1('HEAD') self.git.require_clean_work_tree('proceed') # This might throw ManualMergeUnusableError: (i1, i2) = self.incorporate_manual_merge(commit) # Now detach head so that we can delete refname. self.git.detach('Detach HEAD from %s' % (refname,)) self.git.delete_ref( refname, 'imerge %s: remove scratch reference' % (self.name,), ) merge_frontier = self.map_frontier() try: # This might throw NotABlockingCommitError: merge_frontier.incorporate_merge(i1, i2) sys.stderr.write( 'Merge has been recorded for merge %d-%d.\n' % self.get_original_indexes(i1, i2) ) finally: self.save() def _set_refname(self, refname, commit, force=False): try: ref_oldval = self.git.get_commit_sha1(refname) except ValueError: # refname doesn't already exist; simply point it at commit: self.git.update_ref(refname, commit, 'imerge: recording final merge') self.git.checkout(refname, quiet=True) else: # refname already exists. This has two ramifications: # 1. HEAD might point at it # 2. We may only fast-forward it (unless force is set) head_refname = self.git.get_head_refname() if not force and not self.git.is_ancestor(ref_oldval, commit): raise Failure( '%s cannot be fast-forwarded to %s!' % (refname, commit) ) if head_refname == refname: self.git.reset_hard(commit) else: self.git.update_ref( refname, commit, 'imerge: recording final merge', ) self.git.checkout(refname, quiet=True) def simplify_to_full(self, refname, force=False): for i1 in range(1, self.len1): for i2 in range(1, self.len2): if not (i1, i2) in self: raise Failure( 'Cannot simplify to "full" because ' 'merge %d-%d is not yet done' % (i1, i2) ) self._set_refname(refname, self[-1, -1].sha1, force=force) def simplify_to_rebase_with_history(self, refname, force=False): i1 = self.len1 - 1 for i2 in range(1, self.len2): if not (i1, i2) in self: raise Failure( 'Cannot simplify to rebase-with-history because ' 'merge %d-%d is not yet done' % (i1, i2) ) commit = self[i1, 0].sha1 for i2 in range(1, self.len2): orig = self[0, i2].sha1 tree = self.git.get_tree(self[i1, i2].sha1) # Create a commit, copying the old log message: msg = ( self.git.get_log_message(orig).rstrip('\n') + '\n\n(rebased-with-history from commit %s)\n' % orig ) commit = self.git.commit_tree( tree, [commit, orig], msg=msg, metadata=self.git.get_author_info(orig), ) self._set_refname(refname, commit, force=force) def simplify_to_border( self, refname, with_history1=False, with_history2=False, force=False, ): i1 = self.len1 - 1 for i2 in range(1, self.len2): if not (i1, i2) in self: raise Failure( 'Cannot simplify to border because ' 'merge %d-%d is not yet done' % (i1, i2) ) i2 = self.len2 - 1 for i1 in range(1, self.len1): if not (i1, i2) in self: raise Failure( 'Cannot simplify to border because ' 'merge %d-%d is not yet done' % (i1, i2) ) i1 = self.len1 - 1 commit = self[i1, 0].sha1 for i2 in range(1, self.len2 - 1): orig = self[0, i2].sha1 tree = self.git.get_tree(self[i1, i2].sha1) # Create a commit, copying the old log message: if with_history2: parents = [commit, orig] msg = ( self.git.get_log_message(orig).rstrip('\n') + '\n\n(rebased-with-history from commit %s)\n' % (orig,) ) else: parents = [commit] msg = ( self.git.get_log_message(orig).rstrip('\n') + '\n\n(rebased from commit %s)\n' % (orig,) ) commit = self.git.commit_tree( tree, parents, msg=msg, metadata=self.git.get_author_info(orig), ) commit1 = commit i2 = self.len2 - 1 commit = self[0, i2].sha1 for i1 in range(1, self.len1 - 1): orig = self[i1, 0].sha1 tree = self.git.get_tree(self[i1, i2].sha1) # Create a commit, copying the old log message: if with_history1: parents = [orig, commit] msg = ( self.git.get_log_message(orig).rstrip('\n') + '\n\n(rebased-with-history from commit %s)\n' % (orig,) ) else: parents = [commit] msg = ( self.git.get_log_message(orig).rstrip('\n') + '\n\n(rebased from commit %s)\n' % (orig,) ) commit = self.git.commit_tree( tree, parents, msg=msg, metadata=self.git.get_author_info(orig), ) commit2 = commit # Construct the apex commit: tree = self.git.get_tree(self[-1, -1].sha1) msg = ( 'Merge %s into %s (using imerge border)' % (self.tip2, self.tip1) ) commit = self.git.commit_tree(tree, [commit1, commit2], msg=msg) # Update the reference: self._set_refname(refname, commit, force=force) def _simplify_to_path(self, refname, base, path, force=False): """Simplify based on path and set refname to the result. The base and path arguments are defined similarly to create_commit_chain(), except that instead of SHA-1s they may optionally represent commits via (i1, i2) tuples. """ def to_sha1(arg): if type(arg) is tuple: commit_record = self[arg] if not commit_record.is_known(): raise MissingMergeFailure(*arg) return commit_record.sha1 else: return arg base_sha1 = to_sha1(base) path_sha1 = [] for (commit, metadata) in path: commit_sha1 = to_sha1(commit) metadata_sha1 = to_sha1(metadata) path_sha1.append((commit_sha1, metadata_sha1)) # A path simplification is allowed to discard history, as long # as the *pre-simplification* apex commit is a descendant of # the branch to be moved. if path: apex = path_sha1[-1][0] else: apex = base_sha1 if not force and not self.git.is_ff(refname, apex): raise Failure( '%s cannot be updated to %s without discarding history.\n' 'Use --force if you are sure, or choose a different reference' % (refname, apex,) ) # The update is OK, so here we can set force=True: self._set_refname( refname, self.git.create_commit_chain(base_sha1, path_sha1), force=True, ) def simplify_to_rebase(self, refname, force=False): i1 = self.len1 - 1 path = [ ((i1, i2), (0, i2)) for i2 in range(1, self.len2) ] try: self._simplify_to_path(refname, (i1, 0), path, force=force) except MissingMergeFailure as e: raise Failure( 'Cannot simplify to %s because merge %d-%d is not yet done' % (self.goal, e.i1, e.i2) ) def simplify_to_drop(self, refname, force=False): try: base = self.goalopts['base'] except KeyError: raise Failure('Goal "drop" was not initialized correctly') i2 = self.len2 - 1 path = [ ((i1, i2), (i1, 0)) for i1 in range(1, self.len1) ] try: self._simplify_to_path(refname, base, path, force=force) except MissingMergeFailure as e: raise Failure( 'Cannot simplify to rebase because merge %d-%d is not yet done' % (e.i1, e.i2) ) def simplify_to_revert(self, refname, force=False): self.simplify_to_rebase(refname, force=force) def simplify_to_merge(self, refname, force=False): if not (-1, -1) in self: raise Failure( 'Cannot simplify to merge because merge %d-%d is not yet done' % (self.len1 - 1, self.len2 - 1) ) tree = self.git.get_tree(self[-1, -1].sha1) parents = [self[-1, 0].sha1, self[0, -1].sha1] # Create a preliminary commit with a generic commit message: sha1 = self.git.commit_tree( tree, parents, msg='Merge %s into %s (using imerge)' % (self.tip2, self.tip1), ) self._set_refname(refname, sha1, force=force) # Now let the user edit the commit log message: self.git.amend() def simplify(self, refname, force=False): """Simplify this MergeState and save the result to refname. The merge must be complete before calling this method.""" if self.goal == 'full': self.simplify_to_full(refname, force=force) elif self.goal == 'rebase': self.simplify_to_rebase(refname, force=force) elif self.goal == 'rebase-with-history': self.simplify_to_rebase_with_history(refname, force=force) elif self.goal == 'border': self.simplify_to_border(refname, force=force) elif self.goal == 'border-with-history': self.simplify_to_border(refname, with_history2=True, force=force) elif self.goal == 'border-with-history2': self.simplify_to_border( refname, with_history1=True, with_history2=True, force=force, ) elif self.goal == 'drop': self.simplify_to_drop(refname, force=force) elif self.goal == 'revert': self.simplify_to_revert(refname, force=force) elif self.goal == 'merge': self.simplify_to_merge(refname, force=force) else: raise ValueError('Invalid value for goal (%r)' % (self.goal,)) def save(self): """Write the current MergeState to the repository.""" blockers = [] for i2 in range(0, self.len2): for i1 in range(0, self.len1): record = self[i1, i2] if record.is_known(): record.save(self.git, self.name, i1, i2) if record.is_blocked(): blockers.append((i1, i2)) state = dict( version='.'.join(str(i) for i in STATE_VERSION), blockers=blockers, tip1=self.tip1, tip2=self.tip2, goal=self.goal, goalopts=self.goalopts, manual=self.manual, branch=self.branch, ) self.git.write_imerge_state_dict(self.name, state) def __str__(self): return 'MergeState(\'%s\', tip1=\'%s\', tip2=\'%s\', goal=\'%s\')' % ( self.name, self.tip1, self.tip2, self.goal, ) def choose_merge_name(git, name): names = list(git.iter_existing_imerge_names()) # If a name was specified, try to use it and fail if not possible: if name is not None: if name not in names: raise Failure('There is no incremental merge called \'%s\'!' % (name,)) if len(names) > 1: # Record this as the new default: git.set_default_imerge_name(name) return name # A name was not specified. Try to use the default name: default_name = git.get_default_imerge_name() if default_name: if git.check_imerge_exists(default_name): return default_name else: # There's no reason to keep the invalid default around: git.set_default_imerge_name(None) raise Failure( 'Warning: The default incremental merge \'%s\' has disappeared.\n' '(The setting imerge.default has been cleared.)\n' 'Please try again.' % (default_name,) ) # If there is exactly one imerge, set it to be the default and use it. if len(names) == 1 and git.check_imerge_exists(names[0]): return names[0] raise Failure('Please select an incremental merge using --name') def read_merge_state(git, name=None): return MergeState.read(git, choose_merge_name(git, name)) def cmd_list(parser, options): git = GitRepository() names = list(git.iter_existing_imerge_names()) default_merge = git.get_default_imerge_name() if not default_merge and len(names) == 1: default_merge = names[0] for name in names: if name == default_merge: sys.stdout.write('* %s\n' % (name,)) else: sys.stdout.write(' %s\n' % (name,)) def cmd_init(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') if not options.name: parser.error( 'Please specify the --name to be used for this incremental merge' ) tip1 = git.get_head_refname(short=True) or 'HEAD' tip2 = options.tip2 try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) merge_state = MergeState.initialize( git, options.name, merge_base, tip1, commits1, tip2, commits2, goal=options.goal, manual=options.manual, branch=(options.branch or options.name), ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(options.name) def cmd_start(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') if not options.name: parser.error( 'Please specify the --name to be used for this incremental merge' ) tip1 = git.get_head_refname(short=True) or 'HEAD' tip2 = options.tip2 try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) merge_state = MergeState.initialize( git, options.name, merge_base, tip1, commits1, tip2, commits2, goal=options.goal, manual=options.manual, branch=(options.branch or options.name), ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(options.name) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_merge(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') tip2 = options.tip2 if options.name: name = options.name else: # By default, name the imerge after the branch being merged: name = tip2 git.check_imerge_name_format(name) tip1 = git.get_head_refname(short=True) if tip1: if not options.branch: # See if we can store the result to the checked-out branch: try: git.check_branch_name_format(tip1) except InvalidBranchNameError: pass else: options.branch = tip1 else: tip1 = 'HEAD' if not options.branch: if options.name: options.branch = options.name else: parser.error( 'HEAD is not a simple branch. ' 'Please specify --branch for storing results.' ) try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) except NothingToDoError as e: sys.stdout.write('Already up-to-date.\n') sys.exit(0) merge_state = MergeState.initialize( git, name, merge_base, tip1, commits1, tip2, commits2, goal=options.goal, manual=options.manual, branch=options.branch, ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(name) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_rebase(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') tip1 = options.tip1 tip2 = git.get_head_refname(short=True) if tip2: if not options.branch: # See if we can store the result to the current branch: try: git.check_branch_name_format(tip2) except InvalidBranchNameError: pass else: options.branch = tip2 if not options.name: # By default, name the imerge after the branch being rebased: options.name = tip2 else: tip2 = git.rev_parse('HEAD') if not options.name: parser.error( 'The checked-out branch could not be used as the imerge name.\n' 'Please use the --name option.' ) if not options.branch: if options.name: options.branch = options.name else: parser.error( 'HEAD is not a simple branch. ' 'Please specify --branch for storing results.' ) try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) except NothingToDoError as e: sys.stdout.write('Already up-to-date.\n') sys.exit(0) merge_state = MergeState.initialize( git, options.name, merge_base, tip1, commits1, tip2, commits2, goal=options.goal, manual=options.manual, branch=options.branch, ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(options.name) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_drop(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') m = re.match(r'^(?P<start>.*[^\.])(?P<sep>\.{2,})(?P<end>[^\.].*)$', options.range) if m: if m.group('sep') != '..': parser.error( 'Range must either be a single commit ' 'or in the form "commit..commit"' ) start = git.rev_parse(m.group('start')) end = git.rev_parse(m.group('end')) else: end = git.rev_parse(options.range) start = git.rev_parse('%s^' % (end,)) try: to_drop = git.linear_ancestry(start, end, options.first_parent) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) # Suppose we want to drop commits 2 and 3 in the branch below. # Then we set up an imerge as follows: # # o - 0 - 1 - 2 - 3 - 4 - 5 - 6 ← tip1 # | # 3⁻¹ # | # 2⁻¹ # # ↑ # tip2 # # We first use imerge to rebase tip1 onto tip2, then we simplify # by discarding the sequence (2, 3, 3⁻¹, 2⁻¹) (which together are # a NOOP). In this case, goalopts would have the following # contents: # # goalopts['base'] = rev_parse(commit1) tip1 = git.get_head_refname(short=True) if tip1: if not options.branch: # See if we can store the result to the current branch: try: git.check_branch_name_format(tip1) except InvalidBranchNameError: pass else: options.branch = tip1 if not options.name: # By default, name the imerge after the branch being rebased: options.name = tip1 else: tip1 = git.rev_parse('HEAD') if not options.name: parser.error( 'The checked-out branch could not be used as the imerge name.\n' 'Please use the --name option.' ) if not options.branch: if options.name: options.branch = options.name else: parser.error( 'HEAD is not a simple branch. ' 'Please specify --branch for storing results.' ) # Create a branch based on end that contains the inverse of the # commits that we want to drop. This will be tip2: git.checkout(end) for commit in reversed(to_drop): git.revert(commit) tip2 = git.rev_parse('HEAD') try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) except NothingToDoError as e: sys.stdout.write('Already up-to-date.\n') sys.exit(0) merge_state = MergeState.initialize( git, options.name, merge_base, tip1, commits1, tip2, commits2, goal='drop', goalopts={'base' : start}, manual=options.manual, branch=options.branch, ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(options.name) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_revert(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') m = re.match(r'^(?P<start>.*[^\.])(?P<sep>\.{2,})(?P<end>[^\.].*)$', options.range) if m: if m.group('sep') != '..': parser.error( 'Range must either be a single commit ' 'or in the form "commit..commit"' ) start = git.rev_parse(m.group('start')) end = git.rev_parse(m.group('end')) else: end = git.rev_parse(options.range) start = git.rev_parse('%s^' % (end,)) try: to_revert = git.linear_ancestry(start, end, options.first_parent) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) # Suppose we want to revert commits 2 and 3 in the branch below. # Then we set up an imerge as follows: # # o - 0 - 1 - 2 - 3 - 4 - 5 - 6 ← tip1 # | # 3⁻¹ # | # 2⁻¹ # # ↑ # tip2 # # Then we use imerge to rebase tip2 onto tip1. tip1 = git.get_head_refname(short=True) if tip1: if not options.branch: # See if we can store the result to the current branch: try: git.check_branch_name_format(tip1) except InvalidBranchNameError: pass else: options.branch = tip1 if not options.name: # By default, name the imerge after the branch being rebased: options.name = tip1 else: tip1 = git.rev_parse('HEAD') if not options.name: parser.error( 'The checked-out branch could not be used as the imerge name.\n' 'Please use the --name option.' ) if not options.branch: if options.name: options.branch = options.name else: parser.error( 'HEAD is not a simple branch. ' 'Please specify --branch for storing results.' ) # Create a branch based on end that contains the inverse of the # commits that we want to drop. This will be tip2: git.checkout(end) for commit in reversed(to_revert): git.revert(commit) tip2 = git.rev_parse('HEAD') try: (merge_base, commits1, commits2) = git.get_boundaries( tip1, tip2, options.first_parent, ) except NonlinearAncestryError as e: if options.first_parent: parser.error(str(e)) else: parser.error('%s\nPerhaps use "--first-parent"?' % (e,)) except NothingToDoError as e: sys.stdout.write('Already up-to-date.\n') sys.exit(0) merge_state = MergeState.initialize( git, options.name, merge_base, tip1, commits1, tip2, commits2, goal='revert', manual=options.manual, branch=options.branch, ) merge_state.save() if len(list(git.iter_existing_imerge_names())) > 1: git.set_default_imerge_name(options.name) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_remove(parser, options): git = GitRepository() MergeState.remove(git, choose_merge_name(git, options.name)) def cmd_continue(parser, options): git = GitRepository() merge_state = read_merge_state(git, options.name) try: merge_state.incorporate_user_merge(edit_log_msg=options.edit) except NoManualMergeError: pass except NotABlockingCommitError as e: raise Failure(str(e)) except ManualMergeUnusableError as e: raise Failure(str(e)) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: merge_state.request_user_merge(e.i1, e.i2) else: sys.stderr.write('Merge is complete!\n') def cmd_record(parser, options): git = GitRepository() merge_state = read_merge_state(git, options.name) try: merge_state.incorporate_user_merge(edit_log_msg=options.edit) except NoManualMergeError as e: raise Failure(str(e)) except NotABlockingCommitError: raise Failure(str(e)) except ManualMergeUnusableError as e: raise Failure(str(e)) try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: pass else: sys.stderr.write('Merge is complete!\n') def cmd_autofill(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') merge_state = read_merge_state(git, options.name) with git.temporary_head(message='imerge: restoring'): try: merge_state.auto_complete_frontier() except FrontierBlockedError as e: raise Failure(str(e)) def cmd_simplify(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') merge_state = read_merge_state(git, options.name) if not merge_state.map_frontier().is_complete(): raise Failure('Merge %s is not yet complete!' % (merge_state.name,)) refname = 'refs/heads/%s' % ((options.branch or merge_state.branch),) if options.goal is not None: merge_state.set_goal(options.goal) merge_state.save() merge_state.simplify(refname, force=options.force) def cmd_finish(parser, options): git = GitRepository() git.require_clean_work_tree('proceed') merge_state = read_merge_state(git, options.name) if not merge_state.map_frontier().is_complete(): raise Failure('Merge %s is not yet complete!' % (merge_state.name,)) refname = 'refs/heads/%s' % ((options.branch or merge_state.branch),) if options.goal is not None: merge_state.set_goal(options.goal) merge_state.save() merge_state.simplify(refname, force=options.force) MergeState.remove(git, merge_state.name) def cmd_diagram(parser, options): git = GitRepository() if not (options.commits or options.frontier): options.frontier = True if not (options.color or (options.color is None and sys.stdout.isatty())): AnsiColor.disable() merge_state = read_merge_state(git, options.name) if options.commits: merge_state.write(sys.stdout, merge_state.tip1, merge_state.tip2) sys.stdout.write('\n') if options.frontier: merge_frontier = merge_state.map_frontier() merge_frontier.write(sys.stdout, merge_state.tip1, merge_state.tip2) sys.stdout.write('\n') if options.html: merge_frontier = merge_state.map_frontier() html = open(options.html, 'w') merge_frontier.write_html(html, merge_state.name) html.close() sys.stdout.write( 'Key:\n' ) if options.frontier: sys.stdout.write( ' |,-,+ = rectangles forming current merge frontier\n' ) sys.stdout.write( ' * = merge done manually\n' ' . = merge done automatically\n' ' # = conflict that is currently blocking progress\n' ' @ = merge was blocked but has been resolved\n' ' ? = no merge recorded\n' '\n' ) def reparent_recursively(git, start_commit, parents, end_commit): """Change the parents of start_commit and its descendants. Change start_commit to have the specified parents, and reparent all commits on the ancestry path between start_commit and end_commit accordingly. Return the replacement end_commit. start_commit, parents, and end_commit must all be resolved OIDs. """ # A map {old_oid : new_oid} keeping track of which replacements # have to be made: replacements = {} # Reparent start_commit: replacements[start_commit] = git.reparent(start_commit, parents) for (commit, parents) in git.rev_list_with_parents( '--ancestry-path', '--topo-order', '--reverse', '%s..%s' % (start_commit, end_commit) ): parents = [replacements.get(p, p) for p in parents] replacements[commit] = git.reparent(commit, parents) try: return replacements[end_commit] except KeyError: raise ValueError( "%s is not an ancestor of %s" % (start_commit, end_commit), ) def cmd_reparent(parser, options): git = GitRepository() try: commit = git.get_commit_sha1(options.commit) except ValueError: sys.exit('%s is not a valid commit', options.commit) try: head = git.get_commit_sha1('HEAD') except ValueError: sys.exit('HEAD is not a valid commit') try: parents = [git.get_commit_sha1(p) for p in options.parents] except ValueError as e: sys.exit(e.message) sys.stderr.write('Reparenting %s..HEAD\n' % (options.commit,)) try: new_head = reparent_recursively(git, commit, parents, head) except ValueError as e: sys.exit(e.message) sys.stdout.write('%s\n' % (new_head,)) def main(args): NAME_INIT_HELP = 'name to use for this incremental merge' def add_name_argument(subparser, help=None): if help is None: subcommand = subparser.prog.split()[1] help = 'name of incremental merge to {0}'.format(subcommand) subparser.add_argument( '--name', action='store', default=None, help=help, ) def add_goal_argument(subparser, default=DEFAULT_GOAL): help = 'the goal of the incremental merge' if default is None: help = ( 'the type of simplification to be made ' '(default is the value provided to "init" or "start")' ) subparser.add_argument( '--goal', action='store', default=default, choices=ALLOWED_GOALS, help=help, ) def add_branch_argument(subparser): subcommand = subparser.prog.split()[1] help = 'the name of the branch to which the result will be stored' if subcommand in ['simplify', 'finish']: help = ( 'the name of the branch to which to store the result ' '(default is the value provided to "init" or "start" if any; ' 'otherwise the name of the merge). ' 'If BRANCH already exists then it must be able to be ' 'fast-forwarded to the result unless the --force option is ' 'specified.' ) subparser.add_argument( '--branch', action='store', default=None, help=help, ) def add_manual_argument(subparser): subparser.add_argument( '--manual', action='store_true', default=False, help=( 'ask the user to complete all merges manually, even when they ' 'appear conflict-free. This option disables the usual bisection ' 'algorithm and causes the full incremental merge diagram to be ' 'completed.' ), ) def add_first_parent_argument(subparser, default=None): subcommand = subparser.prog.split()[1] help = ( 'handle only the first parent commits ' '(this option is currently required if the history is nonlinear)' ) if subcommand in ['merge', 'rebase']: help = argparse.SUPPRESS subparser.add_argument( '--first-parent', action='store_true', default=default, help=help, ) def add_tip2_argument(subparser): subparser.add_argument( 'tip2', action='store', metavar='branch', help='the tip of the branch to be merged into HEAD', ) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) subparsers = parser.add_subparsers(dest='subcommand', help='sub-command') subparser = subparsers.add_parser( 'start', help=( 'start a new incremental merge ' '(equivalent to "init" followed by "continue")' ), ) add_name_argument(subparser, help=NAME_INIT_HELP) add_goal_argument(subparser) add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser) add_tip2_argument(subparser) subparser = subparsers.add_parser( 'merge', help='start a simple merge via incremental merge', ) add_name_argument(subparser, help=NAME_INIT_HELP) add_goal_argument(subparser, default='merge') add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser, default=True) add_tip2_argument(subparser) subparser = subparsers.add_parser( 'rebase', help='start a simple rebase via incremental merge', ) add_name_argument(subparser, help=NAME_INIT_HELP) add_goal_argument(subparser, default='rebase') add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser, default=True) subparser.add_argument( 'tip1', action='store', metavar='branch', help=( 'the tip of the branch onto which the current branch should ' 'be rebased' ), ) subparser = subparsers.add_parser( 'drop', help='drop one or more commits via incremental merge', ) add_name_argument(subparser, help=NAME_INIT_HELP) add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser, default=True) subparser.add_argument( 'range', action='store', metavar='[commit | commit..commit]', help=( 'the commit or range of commits that should be dropped' ), ) subparser = subparsers.add_parser( 'revert', help='revert one or more commits via incremental merge', ) add_name_argument(subparser, help=NAME_INIT_HELP) add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser, default=True) subparser.add_argument( 'range', action='store', metavar='[commit | commit..commit]', help=( 'the commit or range of commits that should be reverted' ), ) subparser = subparsers.add_parser( 'continue', help=( 'record the merge at branch imerge/NAME ' 'and start the next step of the merge ' '(equivalent to "record" followed by "autofill" ' 'and then sets up the working copy with the next ' 'conflict that has to be resolved manually)' ), ) add_name_argument(subparser) subparser.set_defaults(edit=None) subparser.add_argument( '--edit', '-e', dest='edit', action='store_true', help='commit staged changes with the --edit option', ) subparser.add_argument( '--no-edit', dest='edit', action='store_false', help='commit staged changes with the --no-edit option', ) subparser = subparsers.add_parser( 'finish', help=( 'simplify then remove a completed incremental merge ' '(equivalent to "simplify" followed by "remove")' ), ) add_name_argument(subparser) add_goal_argument(subparser, default=None) add_branch_argument(subparser) subparser.add_argument( '--force', action='store_true', default=False, help='allow the target branch to be updated in a non-fast-forward manner', ) subparser = subparsers.add_parser( 'diagram', help='display a diagram of the current state of a merge', ) add_name_argument(subparser) subparser.add_argument( '--commits', action='store_true', default=False, help='show the merges that have been made so far', ) subparser.add_argument( '--frontier', action='store_true', default=False, help='show the current merge frontier', ) subparser.add_argument( '--html', action='store', default=None, help='generate HTML diagram showing the current merge frontier', ) subparser.add_argument( '--color', dest='color', action='store_true', default=None, help='draw diagram with colors', ) subparser.add_argument( '--no-color', dest='color', action='store_false', help='draw diagram without colors', ) subparser = subparsers.add_parser( 'list', help=( 'list the names of incremental merges that are currently in progress. ' 'The active merge is shown with an asterisk next to it.' ), ) subparser = subparsers.add_parser( 'init', help='initialize a new incremental merge', ) add_name_argument(subparser, help=NAME_INIT_HELP) add_goal_argument(subparser) add_branch_argument(subparser) add_manual_argument(subparser) add_first_parent_argument(subparser) add_tip2_argument(subparser) subparser = subparsers.add_parser( 'record', help='record the merge at branch imerge/NAME', ) # record: add_name_argument( subparser, help='name of merge to which the merge should be added', ) subparser.set_defaults(edit=None) subparser.add_argument( '--edit', '-e', dest='edit', action='store_true', help='commit staged changes with the --edit option', ) subparser.add_argument( '--no-edit', dest='edit', action='store_false', help='commit staged changes with the --no-edit option', ) subparser = subparsers.add_parser( 'autofill', help='autofill non-conflicting merges', ) add_name_argument(subparser) subparser = subparsers.add_parser( 'simplify', help=( 'simplify a completed incremental merge by discarding unneeded ' 'intermediate merges and cleaning up the ancestry of the commits ' 'that are retained' ), ) add_name_argument(subparser) add_goal_argument(subparser, default=None) add_branch_argument(subparser) subparser.add_argument( '--force', action='store_true', default=False, help='allow the target branch to be updated in a non-fast-forward manner', ) subparser = subparsers.add_parser( 'remove', help='irrevocably remove an incremental merge', ) add_name_argument(subparser) subparser = subparsers.add_parser( 'reparent', help=( 'change the parents of the specified commit and propagate the ' 'change to HEAD' ), ) subparser.add_argument( '--commit', metavar='COMMIT', default='HEAD', help=( 'target commit to reparent. Create a new commit identical to ' 'this one, but having the specified parents. Then create ' 'new versions of all descendants of this commit all the way to ' 'HEAD, incorporating the modified commit. Output the SHA-1 of ' 'the replacement HEAD commit.' ), ) subparser.add_argument( 'parents', nargs='*', metavar='PARENT', help='a list of commits', ) options = parser.parse_args(args) # Set an environment variable GIT_IMERGE=1 while we are running. # This makes it possible for hook scripts etc. to know that they # are being run within git-imerge, and should perhaps behave # differently. In the future we might make the value more # informative, like GIT_IMERGE=[automerge|autofill|...]. os.environ[str('GIT_IMERGE')] = str('1') if options.subcommand == 'list': cmd_list(parser, options) elif options.subcommand == 'init': cmd_init(parser, options) elif options.subcommand == 'start': cmd_start(parser, options) elif options.subcommand == 'merge': cmd_merge(parser, options) elif options.subcommand == 'rebase': cmd_rebase(parser, options) elif options.subcommand == 'drop': cmd_drop(parser, options) elif options.subcommand == 'revert': cmd_revert(parser, options) elif options.subcommand == 'remove': cmd_remove(parser, options) elif options.subcommand == 'continue': cmd_continue(parser, options) elif options.subcommand == 'record': cmd_record(parser, options) elif options.subcommand == 'autofill': cmd_autofill(parser, options) elif options.subcommand == 'simplify': cmd_simplify(parser, options) elif options.subcommand == 'finish': cmd_finish(parser, options) elif options.subcommand == 'diagram': cmd_diagram(parser, options) elif options.subcommand == 'reparent': cmd_reparent(parser, options) else: parser.error('Unrecognized subcommand') def climain(): try: main(sys.argv[1:]) except Failure as e: sys.exit(str(e)) if __name__ == "__main__": climain() # vim: set expandtab ft=python:
145,733
Python
.py
3,587
30.036242
95
0.565752
mhagger/git-imerge
2,695
126
76
GPL-2.0
9/5/2024, 5:13:42 PM (Europe/Amsterdam)
26,338
setup.py
kovidgoyal_calibre/setup.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re import sys src_base = os.path.dirname(os.path.abspath(__file__)) def check_version_info(): with open(os.path.join(src_base, 'pyproject.toml')) as f: raw = f.read() m = re.search(r'''^requires-python\s*=\s*['"](.+?)['"]''', raw, flags=re.MULTILINE) assert m is not None minver = m.group(1) m = re.match(r'(>=?)(\d+)\.(\d+)', minver) q = int(m.group(2)), int(m.group(3)) if m.group(1) == '>=': is_ok = sys.version_info >= q else: is_ok = sys.version_info > q if not is_ok: exit(f'calibre requires Python {minver}. Current Python version: {".".join(map(str, sys.version_info[:3]))}') check_version_info() sys.path.insert(0, src_base) import setup.commands as commands from setup import get_warnings, prints def option_parser(): import optparse parser = optparse.OptionParser() parser.add_option( '-c', '--clean', default=False, action='store_true', help=('Instead of running the command delete all files generated ' 'by the command')) parser.add_option( '--clean-backups', default=False, action='store_true', help='Delete all backup files from the source tree') parser.add_option( '--clean-all', default=False, action='store_true', help='Delete all machine generated files from the source tree') return parser def clean_backups(): for root, _, files in os.walk('.'): for name in files: for t in ('.pyc', '.pyo', '~', '.swp', '.swo'): if name.endswith(t): os.remove(os.path.join(root, name)) def main(args=sys.argv): if len(args) == 1 or args[1] in ('-h', '--help'): print('Usage: python', args[0], 'command', '[options]') print('\nWhere command is one of:') print() for x in sorted(commands.__all__): print('{:20} -'.format(x), end=' ') c = getattr(commands, x) desc = getattr(c, 'short_description', c.description) print(desc) print('\nTo get help on a particular command, run:') print('\tpython', args[0], 'command -h') return 1 command = args[1] if command not in commands.__all__: print(command, 'is not a recognized command.') print('Valid commands:', ', '.join(commands.__all__)) return 1 command = getattr(commands, command) parser = option_parser() command.add_all_options(parser) parser.set_usage( 'Usage: python setup.py {} [options]\n\n'.format(args[1]) + command.description) opts, args = parser.parse_args(args) opts.cli_args = args[2:] if opts.clean_backups: clean_backups() if opts.clean: prints('Cleaning', args[1]) command.clean() return 0 if opts.clean_all: for cmd in commands.__all__: prints('Cleaning', cmd) getattr(commands, cmd).clean() return 0 command.run_all(opts) warnings = get_warnings() if warnings: print() prints('There were', len(warnings), 'warning(s):') print() for args, kwargs in warnings: prints('*', *args, **kwargs) print() return 0 if __name__ == '__main__': sys.exit(main())
3,559
Python
.py
102
27.696078
117
0.58185
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,339
publish.py
kovidgoyal_calibre/setup/publish.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import filecmp import json import os import shutil import subprocess import sys import tempfile import time from setup import Command, __version__, installer_names, require_clean_git, require_git_master from setup.parallel_build import create_job, parallel_build class Stage1(Command): description = 'Stage 1 of the publish process' sub_commands = [ 'cacerts', 'resources', 'iso639', 'iso3166', 'gui', 'recent_uas', ] class Stage2(Command): description = 'Stage 2 of the publish process, builds the binaries' def run(self, opts): base = os.path.join(self.d(self.SRC)) for x in ('dist', 'build'): x = os.path.join(base, x) if os.path.exists(x): shutil.rmtree(x) os.mkdir(x) self.info('Starting builds for all platforms, this will take a while...') session = ['layout vertical'] platforms = 'linux64', 'linuxarm64', 'osx', 'win' for x in platforms: cmd = ( '''{exe} -c "import subprocess; subprocess.Popen(['{exe}', './setup.py', '{x}']).wait() != 0 and''' ''' input('Build of {x} failed, press Enter to exit');"''' ).format(exe=sys.executable, x=x) session.append('title ' + x) session.append('launch ' + cmd) p = subprocess.Popen([ 'kitty', '-o', 'enabled_layouts=vertical,stack', '-o', 'scrollback_lines=20000', '-o', 'close_on_child_death=y', '--session=-' ], stdin=subprocess.PIPE) p.communicate('\n'.join(session).encode('utf-8')) p.wait() for installer in installer_names(include_source=False): installer = self.j(self.d(self.SRC), installer) if not os.path.exists(installer) or os.path.getsize(installer) < 10000: raise SystemExit( 'The installer %s does not exist' % os.path.basename(installer) ) class Stage3(Command): description = 'Stage 3 of the publish process' sub_commands = ['upload_user_manual', 'upload_demo', 'sdist', 'tag_release'] class Stage4(Command): description = 'Stage 4 of the publish process' sub_commands = ['upload_installers'] class Stage5(Command): description = 'Stage 5 of the publish process' sub_commands = ['upload_to_server'] def run(self, opts): subprocess.check_call('rm -rf build/* dist/*', shell=True) class Publish(Command): description = 'Publish a new calibre release' sub_commands = [ 'stage1', 'stage2', 'stage3', 'stage4', 'stage5', ] def pre_sub_commands(self, opts): require_git_master() require_clean_git() if 'PUBLISH_BUILD_DONE' not in os.environ: subprocess.check_call([sys.executable, 'setup.py', 'check']) subprocess.check_call([sys.executable, 'setup.py', 'build']) if 'SKIP_CALIBRE_TESTS' not in os.environ: subprocess.check_call([sys.executable, 'setup.py', 'test']) subprocess.check_call([sys.executable, 'setup.py', 'pot']) subprocess.check_call([sys.executable, 'setup.py', 'translations']) os.environ['PUBLISH_BUILD_DONE'] = '1' os.execl(os.path.abspath('setup.py'), './setup.py', 'publish') class PublishBetas(Command): sub_commands = ['stage1', 'stage2', 'sdist'] def pre_sub_commands(self, opts): require_clean_git() # require_git_master() def run(self, opts): dist = self.a(self.j(self.d(self.SRC), 'dist')) subprocess.check_call(( 'rsync --partial -rh --info=progress2 --delete-after %s/ download.calibre-ebook.com:/srv/download/betas/' % dist ).split()) class PublishPreview(Command): sub_commands = ['stage1', 'stage2', 'sdist'] def pre_sub_commands(self, opts): version = tuple(map(int, __version__.split('.'))) if version[2] < 100: raise SystemExit('Must set calibre version to have patch level greater than 100') require_clean_git() require_git_master() def run(self, opts): dist = self.a(self.j(self.d(self.SRC), 'dist')) with open(os.path.join(dist, 'README.txt'), 'w') as f: print('''\ These are preview releases of changes to calibre since the last normal release. Preview releases are typically released every Friday, they serve as a way for users to test upcoming features/fixes in the next calibre release. ''', file=f) subprocess.check_call(( f'rsync -rh --info=progress2 --delete-after --delete {dist}/ download.calibre-ebook.com:/srv/download/preview/' ).split()) class Manual(Command): description = '''Build the User Manual ''' def add_options(self, parser): parser.add_option( '-l', '--language', action='append', default=[], help=( 'Build translated versions for only the specified languages (can be specified multiple times)' ) ) parser.add_option( '--serve', action='store_true', default=False, help='Run a webserver on the built manual files' ) def run(self, opts): tdir = self.j(tempfile.gettempdir(), 'user-manual-build') if os.path.exists(tdir): shutil.rmtree(tdir) os.mkdir(tdir) st = time.time() base = self.j(self.d(self.SRC), 'manual') for d in ('generated', ): d = self.j(base, d) if os.path.exists(d): shutil.rmtree(d) os.makedirs(d) jobs = [] languages = opts.language or list( json.load(open(self.j(base, 'locale', 'completed.json'), 'rb')) ) languages = set(languages) - {'en'} languages.discard('ta') # Tamil translations break Sphinx languages = ['en'] + list(languages) os.environ['ALL_USER_MANUAL_LANGUAGES'] = ' '.join(languages) for language in languages: jobs.append(create_job([ sys.executable, self.j(self.d(self.SRC), 'manual', 'build.py'), language, self.j(tdir, language) ], '\n\n**************** Building translations for: %s' % language)) self.info('Building manual for %d languages' % len(jobs)) subprocess.check_call(jobs[0].cmd) if not parallel_build(jobs[1:], self.info): raise SystemExit(1) cwd = os.getcwd() with open('resources/localization/website-languages.txt') as wl: languages = frozenset(filter(None, (x.strip() for x in wl.read().split()))) try: os.chdir(self.j(tdir, 'en', 'html')) for x in os.listdir(tdir): if x != 'en': shutil.copytree(self.j(tdir, x, 'html'), x) self.replace_with_symlinks(x) else: os.symlink('.', 'en') for x in languages: if x and not os.path.exists(x): os.symlink('.', x) self.info( 'Built manual for %d languages in %s minutes' % (len(jobs), int((time.time() - st) / 60.)) ) finally: os.chdir(cwd) if opts.serve: self.serve_manual(self.j(tdir, 'en', 'html')) def serve_manual(self, root): os.chdir(root) from polyglot.http_server import HTTPServer, SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = HTTPServer Protocol = "HTTP/1.0" server_address = ('127.0.0.1', 8000) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) print("Serving User Manual on localhost:8000") from calibre.gui2 import open_url open_url('http://localhost:8000') httpd.serve_forever() def replace_with_symlinks(self, lang_dir): ' Replace all identical files with symlinks to save disk space/upload bandwidth ' from calibre import walk base = self.a(lang_dir) for f in walk(base): r = os.path.relpath(f, base) orig = self.j(self.d(base), r) try: sz = os.stat(orig).st_size except OSError: continue if sz == os.stat(f).st_size and filecmp._do_cmp(f, orig): os.remove(f) os.symlink(os.path.relpath(orig, self.d(f)), f) def clean(self): path = os.path.join(self.SRC, 'calibre', 'manual', '.build') if os.path.exists(path): shutil.rmtree(path) class ManPages(Command): description = '''Build the man pages ''' def add_options(self, parser): parser.add_option('--man-dir', help='Where to generate the man pages') parser.add_option('--compress-man-pages', default=False, action='store_true', help='Compress the generated man pages') def run(self, opts): self.build_man_pages(opts.man_dir or 'man-pages', opts.compress_man_pages) def build_man_pages(self, dest, compress=False): from calibre.utils.localization import available_translations dest = os.path.abspath(dest) if os.path.exists(dest): shutil.rmtree(dest) os.makedirs(dest) base = self.j(self.d(self.SRC), 'manual') languages = set(available_translations()) languages.discard('ta') # Tamil translatins are completely borked break sphinx languages = ['en'] + list(languages - {'en', 'en_GB'}) os.environ['ALL_USER_MANUAL_LANGUAGES'] = ' '.join(languages) try: os.makedirs(dest) except OSError: pass jobs = [] for l in languages: jobs.append(create_job( [sys.executable, self.j(base, 'build.py'), '--man-pages', l, dest], '\n\n**************** Building translations for: %s' % l) ) self.info(f'\tCreating man pages in {dest} for {len(jobs)} languages...') subprocess.check_call(jobs[0].cmd) if not parallel_build(jobs[1:], self.info, verbose=False): raise SystemExit(1) cwd = os.getcwd() os.chdir(dest) try: for x in tuple(os.listdir('.')): if x in languages: if x == 'en': os.rename(x, 'man1') else: os.mkdir(self.j(x, 'man1')) for y in os.listdir(x): if y != 'man1': os.rename(self.j(x, y), self.j(x, 'man1', y)) else: shutil.rmtree(x) if os.path.isdir(x) else os.remove(x) if compress: jobs = [] for dirpath, dirnames, filenames in os.walk('.'): for f in filenames: if f.endswith('.1'): jobs.append(create_job(['gzip', '--best', self.j(dirpath, f)], '')) if not parallel_build(jobs, self.info, verbose=False): raise SystemExit(1) finally: os.chdir(cwd) class TagRelease(Command): description = 'Tag a new release in git' def run(self, opts): self.info('Tagging release') subprocess.check_call( 'git tag -s v{0} -m "version-{0}"'.format(__version__).split() ) subprocess.check_call(f'git push origin v{__version__}'.split())
11,875
Python
.py
281
31.800712
126
0.56547
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,340
piper.py
kovidgoyal_calibre/setup/piper.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import json import os import re from contextlib import suppress from setup.revendor import ReVendor class PiperVoices(ReVendor): description = 'Download the list of Piper voices' NAME = 'piper_voices' TAR_NAME = 'piper voice list' VERSION = 'master' DOWNLOAD_URL = f'https://raw.githubusercontent.com/rhasspy/piper/{VERSION}/VOICES.md' CAN_USE_SYSTEM_VERSION = False @property def output_file_path(self) -> str: return os.path.join(self.RESOURCES, 'piper-voices.json') def run(self, opts): url = opts.path_to_piper_voices if url: with open(opts.path_to_piper_voices) as f: src = f.read() else: url = opts.piper_voices_url src = self.download_securely(url).decode('utf-8') lang_map = {} current_lang = current_voice = '' lang_pat = re.compile(r'\((.+?)\)') model_pat = re.compile(r'\[model\]\((.+?)\)') config_pat = re.compile(r'\[config\]\((.+?)\)') for line in src.splitlines(): if line.startswith('* '): if m := lang_pat.search(line): current_lang = m.group(1).partition(',')[0].replace('`', '') lang_map[current_lang] = {} current_voice = '' else: line = line.strip() if not line.startswith('*'): continue if '[model]' in line: if current_lang and current_voice: qual_map = lang_map[current_lang][current_voice] quality = line.partition('-')[0].strip().lstrip('*').strip() model = config = '' if m := model_pat.search(line): model = m.group(1) if m := config_pat.search(line): config = m.group(1) if not quality or not model or not config: raise SystemExit('Failed to parse piper voice model definition from:\n' + line) qual_map[quality] = {'model': model, 'config': config} else: current_voice = line.partition(' ')[-1].strip() lang_map[current_lang][current_voice] = {} if not lang_map: raise SystemExit(f'Failed to read any piper voices from: {url}') if 'en_US' not in lang_map: raise SystemExit(f'Failed to read en_US piper voices from: {url}') with open(self.output_file_path, 'w') as f: json.dump({'version': 1, 'lang_map': lang_map}, f, indent=2, sort_keys=False) def clean(self): with suppress(FileNotFoundError): os.remove(self.output_file_path)
2,908
Python
.py
64
32.625
107
0.531382
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,341
hosting.py
kovidgoyal_calibre/setup/hosting.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json import mimetypes import os import shutil import sys import time from argparse import ArgumentParser, FileType from collections import OrderedDict from pprint import pprint from subprocess import check_call class ReadFileWithProgressReporting: # {{{ def __init__(self, path, mode='rb'): self.fobj = open(path, mode) self.fobj.seek(0, os.SEEK_END) self._total = self.fobj.tell() self.fobj.seek(0) self.start_time = time.time() def tell(self, *a): return self.fobj.tell(*a) def __enter__(self): return self def __exit__(self, *a): self.fobj.close() del self.fobj def __len__(self): return self._total def read(self, size): data = self.fobj.read(size) if data: self.report_progress(len(data)) return data def report_progress(self, size): sys.stdout.write('\x1b[s') sys.stdout.write('\x1b[K') frac = float(self.tell()) / self._total mb_pos = self.tell() / float(1024**2) mb_tot = self._total / float(1024**2) kb_pos = self.tell() / 1024.0 kb_rate = kb_pos / (time.time() - self.start_time) bit_rate = kb_rate * 1024 eta = int((self._total - self.tell()) / bit_rate) + 1 eta_m, eta_s = eta / 60, eta % 60 sys.stdout.write( ' %.1f%% %.1f/%.1fMB %.1f KB/sec %d minutes, %d seconds left' % (frac * 100, mb_pos, mb_tot, kb_rate, eta_m, eta_s) ) sys.stdout.write('\x1b[u') if self.tell() >= self._total: sys.stdout.write('\n') t = int(time.time() - self.start_time) + 1 print( 'Upload took %d minutes and %d seconds at %.1f KB/sec' % (t / 60, t % 60, kb_rate) ) sys.stdout.flush() # }}} class Base: # {{{ def __init__(self): self.d = os.path.dirname self.j = os.path.join self.a = os.path.abspath self.b = os.path.basename self.s = os.path.splitext self.e = os.path.exists def info(self, *args, **kwargs): print(*args, **kwargs) sys.stdout.flush() def warn(self, *args, **kwargs): print('\n' + '_' * 20, 'WARNING', '_' * 20) print(*args, **kwargs) print('_' * 50) sys.stdout.flush() # }}} class SourceForge(Base): # {{{ # Note that you should manually ssh once to username,project@frs.sourceforge.net # on the staging server so that the host key is setup def __init__(self, files, project, version, username, replace=False): self.username, self.project, self.version = username, project, version self.base = '/home/frs/project/c/ca/' + project self.rdir = self.base + '/' + version self.files = files def __call__(self): for x in self.files: start = time.time() self.info('Uploading', x) for i in range(5): try: check_call([ 'rsync', '-h', '-zz', '--progress', '-e', 'ssh -x', x, '%s,%s@frs.sourceforge.net:%s' % (self.username, self.project, self.rdir + '/') ]) except KeyboardInterrupt: raise SystemExit(1) except: print('\nUpload failed, trying again in 30 seconds') time.sleep(30) else: break print('Uploaded in', int(time.time() - start), 'seconds\n\n') # }}} class GitHub(Base): # {{{ API = 'https://api.github.com/' def __init__(self, files, reponame, version, username, password, replace=False): self.files, self.reponame, self.version, self.username, self.password, self.replace = ( files, reponame, version, username, password, replace ) self.current_tag_name = 'v' + self.version import requests self.requests = s = requests.Session() s.auth = (self.username, self.password) s.headers.update({'Accept': 'application/vnd.github.v3+json'}) def __call__(self): releases = self.releases() self.clean_older_releases(releases) release = self.create_release(releases) upload_url = release['upload_url'].partition('{')[0] existing_assets = self.existing_assets(release['id']) for path, desc in self.files.items(): self.info('') url = self.API + 'repos/{}/{}/releases/assets/{{}}'.format( self.username, self.reponame ) fname = os.path.basename(path) if fname in existing_assets: self.info( 'Deleting %s from GitHub with id: %s' % (fname, existing_assets[fname]) ) r = self.requests.delete(url.format(existing_assets[fname])) if r.status_code != 204: self.fail(r, 'Failed to delete %s from GitHub' % fname) r = self.do_upload(upload_url, path, desc, fname) if r.status_code != 201: self.fail(r, 'Failed to upload file: %s' % fname) try: r = self.requests.patch( url.format(r.json()['id']), data=json.dumps({ 'name': fname, 'label': desc }) ) except Exception: time.sleep(15) r = self.requests.patch( url.format(r.json()['id']), data=json.dumps({ 'name': fname, 'label': desc }) ) if r.status_code != 200: self.fail(r, 'Failed to set label for %s' % fname) def clean_older_releases(self, releases): for release in releases: if release.get('assets', None) and release['tag_name'] != self.current_tag_name: self.info( '\nDeleting old released installers from: %s' % release['tag_name'] ) for asset in release['assets']: r = self.requests.delete( self.API + 'repos/%s/%s/releases/assets/%s' % (self.username, self.reponame, asset['id']) ) if r.status_code != 204: self.fail( r, 'Failed to delete obsolete asset: %s for release: %s' % (asset['name'], release['tag_name']) ) def do_upload(self, url, path, desc, fname): mime_type = mimetypes.guess_type(fname)[0] or 'application/octet-stream' self.info(f'Uploading to GitHub: {fname} ({mime_type})') with ReadFileWithProgressReporting(path) as f: return self.requests.post( url, headers={ 'Content-Type': mime_type, 'Content-Length': str(f._total) }, params={'name': fname}, data=f ) def fail(self, r, msg): print(msg, ' Status Code: %s' % r.status_code, file=sys.stderr) print("JSON from response:", file=sys.stderr) pprint(dict(r.json()), stream=sys.stderr) raise SystemExit(1) def already_exists(self, r): error_code = r.json().get('errors', [{}])[0].get('code', None) return error_code == 'already_exists' def existing_assets(self, release_id): url = self.API + 'repos/{}/{}/releases/{}/assets'.format( self.username, self.reponame, release_id ) r = self.requests.get(url) if r.status_code != 200: self.fail('Failed to get assets for release') return {asset['name']: asset['id'] for asset in r.json()} def releases(self): url = self.API + f'repos/{self.username}/{self.reponame}/releases' r = self.requests.get(url) if r.status_code != 200: self.fail(r, 'Failed to list releases') return r.json() def create_release(self, releases): ' Create a release on GitHub or if it already exists, return the existing release ' for release in releases: # Check for existing release if release['tag_name'] == self.current_tag_name: return release url = self.API + f'repos/{self.username}/{self.reponame}/releases' r = self.requests.post( url, data=json.dumps({ 'tag_name': self.current_tag_name, 'target_commitish': 'master', 'name': 'version %s' % self.version, 'body': 'Release version %s' % self.version, 'draft': False, 'prerelease': False }) ) if r.status_code != 201: self.fail(r, 'Failed to create release for version: %s' % self.version) return r.json() # }}} def generate_index(): # {{{ os.chdir('/srv/download') releases = set() for x in os.listdir('.'): if os.path.isdir(x) and '.' in x: releases.add(tuple(int(y) for y in x.split('.'))) rmap = OrderedDict() for rnum in sorted(releases, reverse=True): series = rnum[:2] if rnum[0] == 0 else rnum[:1] if series not in rmap: rmap[series] = [] rmap[series].append(rnum) template = '''<!DOCTYPE html>\n<html lang="en"> <head> <meta charset="utf-8"> <title>{title}</title><link rel="icon" type="image/png" href="//calibre-ebook.com/favicon.png" /> <style type="text/css"> {style} </style> </head> <body> <h1>{title}</h1> <p>{msg}</p> {body} </body> </html> ''' # noqa style = ''' body { font-family: sans-serif; background-color: #eee; } a { text-decoration: none; } a:visited { color: blue } a:hover { color: red } ul { list-style-type: none } li { padding-bottom: 1ex } dd li { text-indent: 0; margin: 0 } dd ul { padding: 0; margin: 0 } dt { font-weight: bold } dd { margin-bottom: 2ex } ''' body = [] for series in rmap: body.append( '<li><a href="{0}.html" title="Releases in the {0}.x series">{0}.x</a>\xa0\xa0\xa0<span style="font-size:smaller">[{1} releases]</span></li>' .format( # noqa '.'.join(map(str, series)), len(rmap[series]) ) ) body = '<ul>{}</ul>'.format(' '.join(body)) index = template.format( title='Previous calibre releases', style=style, msg='Choose a series of calibre releases', body=body ) with open('index.html', 'wb') as f: f.write(index.encode('utf-8')) for series, releases in rmap.items(): sname = '.'.join(map(str, series)) body = [ '<li><a href="{0}/" title="Release {0}">{0}</a></li>'.format( '.'.join(map(str, r)) ) for r in releases ] body = '<ul class="release-list">{}</ul>'.format(' '.join(body)) index = template.format( title='Previous calibre releases (%s.x)' % sname, style=style, msg='Choose a calibre release', body=body ) with open('%s.html' % sname, 'wb') as f: f.write(index.encode('utf-8')) for r in releases: rname = '.'.join(map(str, r)) os.chdir(rname) try: body = [] files = os.listdir('.') windows = [x for x in files if x.endswith('.msi')] if windows: def wdesc(x): return 'Windows ' + ('64-bit' if '-64bit-' in x else '32-bit') + ' Installer' windows = [ '<li><a href="{0}" title="{1}">{1}</a></li>'.format(x, wdesc(x)) for x in windows ] body.append( '<dt>Windows</dt><dd><ul>{}</ul></dd>'.format( ' '.join(windows) ) ) portable = [x for x in files if '-portable-' in x] if portable: body.append( '<dt>Calibre Portable</dt><dd><a href="{0}" title="{1}">{1}</a></dd>' .format(portable[0], 'Calibre Portable Installer') ) osx = [x for x in files if x.endswith('.dmg')] if osx: body.append( '<dt>Apple Mac</dt><dd><a href="{0}" title="{1}">{1}</a></dd>' .format(osx[0], 'OS X Disk Image (.dmg)') ) linux = [ x for x in files if x.endswith('.txz') or x.endswith('tar.bz2') ] if linux: def ldesc(x): if 'i686' in x: return 'Linux Intel 32-bit binary' if 'arm64' in x: return 'Linux ARM 64-bit binary' return 'Linux Intel 64-bit binary' linux = [ '<li><a href="{0}" title="{1}">{1}</a></li>'.format(x, ldesc(x)) for x in linux ] body.append( '<dt>Linux</dt><dd><ul>{}</ul></dd>'.format( ' '.join(linux) ) ) source = [x for x in files if x.endswith('.xz') or x.endswith('.gz')] if source: body.append( '<dt>Source Code</dt><dd><a href="{0}" title="{1}">{1}</a></dd>' .format(source[0], 'Source code (all platforms)') ) body = '<dl>{}</dl>'.format(''.join(body)) index = template.format( title='calibre release (%s)' % rname, style=style, msg='', body=body ) with open('index.html', 'wb') as f: f.write(index.encode('utf-8')) finally: os.chdir('..') # }}} SERVER_BASE = '/srv/download/' def upload_to_servers(files, version): # {{{ base = SERVER_BASE dest = os.path.join(base, version) if not os.path.exists(dest): os.mkdir(dest) for src in files: shutil.copyfile(src, os.path.join(dest, os.path.basename(src))) cwd = os.getcwd() try: generate_index() finally: os.chdir(cwd) # for server, rdir in {'files':'/srv/download/'}.items(): # print('Uploading to server:', server) # server = '%s.calibre-ebook.com' % server # # Copy the generated index files # print ('Copying generated index') # check_call(['rsync', '-hza', '-e', 'ssh -x', '--include', '*.html', # '--filter', '-! */', base, 'root@%s:%s' % (server, rdir)]) # # Copy the release files # rdir = '%s%s/' % (rdir, version) # for x in files: # start = time.time() # print ('Uploading', x) # for i in range(5): # try: # check_call(['rsync', '-h', '-z', '--progress', '-e', 'ssh -x', x, # 'root@%s:%s'%(server, rdir)]) # except KeyboardInterrupt: # raise SystemExit(1) # except: # print ('\nUpload failed, trying again in 30 seconds') # time.sleep(30) # else: # break # print ('Uploaded in', int(time.time() - start), 'seconds\n\n') # # }}} # CLI {{{ def cli_parser(): epilog = 'Copyright Kovid Goyal 2012' p = ArgumentParser( description='Upload project files to a hosting service automatically', epilog=epilog ) a = p.add_argument a( 'appname', help='The name of the application, all files to' ' upload should begin with this name' ) a( 'version', help='The version of the application, all files to' ' upload should contain this version' ) a( 'file_map', type=FileType('r'), help='A file containing a mapping of files to be uploaded to ' 'descriptions of the files. The descriptions will be visible ' 'to users trying to get the file from the hosting service. ' 'The format of the file is filename: description, with one per ' 'line. filename can be a path to the file relative to the current ' 'directory.' ) a( '--replace', action='store_true', default=False, help='If specified, existing files are replaced, otherwise ' 'they are skipped.' ) subparsers = p.add_subparsers( help='Where to upload to', dest='service', title='Service', description='Hosting service to upload to' ) sf = subparsers.add_parser( 'sourceforge', help='Upload to sourceforge', epilog=epilog ) gh = subparsers.add_parser('github', help='Upload to GitHub', epilog=epilog) subparsers.add_parser('calibre', help='Upload to calibre file servers') a = sf.add_argument a('project', help='The name of the project on sourceforge we are uploading to') a('username', help='Sourceforge username') a = gh.add_argument a('project', help='The name of the repository on GitHub we are uploading to') a('username', help='Username to log into your GitHub account') a('password', help='Password to log into your GitHub account') return p def main(args=None): cli = cli_parser() args = cli.parse_args(args) files = {} with args.file_map as f: for line in f: fname, _, desc = line.partition(':') fname, desc = fname.strip(), desc.strip() if fname and desc: files[fname] = desc ofiles = OrderedDict() for x in sorted(files, key=lambda x: os.stat(x).st_size, reverse=True): ofiles[x] = files[x] if args.service == 'sourceforge': sf = SourceForge( ofiles, args.project, args.version, args.username, replace=args.replace ) sf() elif args.service == 'github': gh = GitHub( ofiles, args.project, args.version, args.username, args.password, replace=args.replace ) gh() elif args.service == 'calibre': upload_to_servers(ofiles, args.version) if __name__ == '__main__': main() # }}}
19,191
Python
.py
483
28.424431
300
0.503916
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,342
resources.py
kovidgoyal_calibre/setup/resources.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import glob import json import os import re import shutil import zipfile from zlib import compress from polyglot.builtins import codepoint_to_chr, iteritems, itervalues, only_unicode_recursive from setup import Command, __appname__, basenames, download_securely, dump_json def get_opts_from_parser(parser): def do_opt(opt): yield from opt._long_opts yield from opt._short_opts for o in parser.option_list: yield from do_opt(o) for g in parser.option_groups: for o in g.option_list: yield from do_opt(o) class Kakasi(Command): # {{{ description = 'Compile resources for unihandecode' KAKASI_PATH = os.path.join(Command.SRC, __appname__, 'ebooks', 'unihandecode', 'pykakasi') def run(self, opts): self.records = {} src = self.j(self.KAKASI_PATH, 'kakasidict.utf8') dest = self.j(self.RESOURCES, 'localization', 'pykakasi','kanwadict2.calibre_msgpack') base = os.path.dirname(dest) if not os.path.exists(base): os.makedirs(base) if self.newer(dest, src): self.info('\tGenerating Kanwadict') for line in open(src, "rb"): self.parsekdict(line) self.kanwaout(dest) src = self.j(self.KAKASI_PATH, 'itaijidict.utf8') dest = self.j(self.RESOURCES, 'localization', 'pykakasi','itaijidict2.calibre_msgpack') if self.newer(dest, src): self.info('\tGenerating Itaijidict') self.mkitaiji(src, dest) src = self.j(self.KAKASI_PATH, 'kanadict.utf8') dest = self.j(self.RESOURCES, 'localization', 'pykakasi','kanadict2.calibre_msgpack') if self.newer(dest, src): self.info('\tGenerating kanadict') self.mkkanadict(src, dest) def mkitaiji(self, src, dst): dic = {} for line in open(src, "rb"): line = line.decode('utf-8').strip() if line.startswith(';;'): # skip comment continue if re.match(r"^$",line): continue pair = re.sub(r'\\u([0-9a-fA-F]{4})', lambda x:codepoint_to_chr(int(x.group(1),16)), line) dic[pair[0]] = pair[1] from calibre.utils.serialize import msgpack_dumps with open(dst, 'wb') as f: f.write(msgpack_dumps(dic)) def mkkanadict(self, src, dst): dic = {} for line in open(src, "rb"): line = line.decode('utf-8').strip() if line.startswith(';;'): # skip comment continue if re.match(r"^$",line): continue (alpha, kana) = line.split(' ') dic[kana] = alpha from calibre.utils.serialize import msgpack_dumps with open(dst, 'wb') as f: f.write(msgpack_dumps(dic)) def parsekdict(self, line): line = line.decode('utf-8').strip() if line.startswith(';;'): # skip comment return (yomi, kanji) = line.split(' ') if ord(yomi[-1:]) <= ord('z'): tail = yomi[-1:] yomi = yomi[:-1] else: tail = '' self.updaterec(kanji, yomi, tail) def updaterec(self, kanji, yomi, tail): key = "%04x"%ord(kanji[0]) if key in self.records: if kanji in self.records[key]: rec = self.records[key][kanji] rec.append((yomi,tail)) self.records[key].update({kanji: rec}) else: self.records[key][kanji]=[(yomi, tail)] else: self.records[key] = {} self.records[key][kanji]=[(yomi, tail)] def kanwaout(self, out): from calibre.utils.serialize import msgpack_dumps with open(out, 'wb') as f: dic = {} for k, v in iteritems(self.records): dic[k] = compress(msgpack_dumps(v)) f.write(msgpack_dumps(dic)) def clean(self): kakasi = self.j(self.RESOURCES, 'localization', 'pykakasi') if os.path.exists(kakasi): shutil.rmtree(kakasi) # }}} class CACerts(Command): # {{{ description = 'Get updated mozilla CA certificate bundle' CA_PATH = os.path.join(Command.RESOURCES, 'mozilla-ca-certs.pem') def add_options(self, parser): parser.add_option('--path-to-cacerts', help='Path to previously downloaded mozilla-ca-certs.pem') def run(self, opts): if opts.path_to_cacerts: shutil.copyfile(opts.path_to_cacerts, self.CA_PATH) os.chmod(self.CA_PATH, 0o644) else: try: with open(self.CA_PATH, 'rb') as f: raw = f.read() except OSError as err: if err.errno != errno.ENOENT: raise raw = b'' nraw = download_securely('https://curl.haxx.se/ca/cacert.pem') if not nraw: raise RuntimeError('Failed to download CA cert bundle') if nraw != raw: self.info('Updating Mozilla CA certificates') with open(self.CA_PATH, 'wb') as f: f.write(nraw) self.verify_ca_certs() def verify_ca_certs(self): from calibre.utils.https import get_https_resource_securely get_https_resource_securely('https://calibre-ebook.com', cacerts=self.b(self.CA_PATH)) # }}} class RecentUAs(Command): # {{{ description = 'Get updated list of common browser user agents' UA_PATH = os.path.join(Command.RESOURCES, 'user-agent-data.json') def add_options(self, parser): parser.add_option('--path-to-user-agent-data', help='Path to previously downloaded user-agent-data.json') def run(self, opts): from setup.browser_data import get_data if opts.path_to_user_agent_data: shutil.copyfile(opts.path_to_user_agent_data, self.UA_PATH) os.chmod(self.UA_PATH, 0o644) else: data = get_data() with open(self.UA_PATH, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False, sort_keys=True) # }}} class RapydScript(Command): # {{{ description = 'Compile RapydScript to JavaScript' def add_options(self, parser): parser.add_option('--only-module', default=None, help='Only compile the specified module') def run(self, opts): from calibre.utils.rapydscript import compile_editor, compile_srv, compile_viewer if opts.only_module: locals()['compile_' + opts.only_module]() else: compile_editor() compile_viewer() compile_srv() # }}} class Resources(Command): # {{{ description = 'Compile various needed calibre resources' sub_commands = ['kakasi', 'liberation_fonts', 'mathjax', 'rapydscript', 'hyphenation', 'piper_voices'] def run(self, opts): from calibre.utils.serialize import msgpack_dumps scripts = {} for x in ('console', 'gui'): for name in basenames[x]: if name in ('calibre-complete', 'calibre_postinstall'): continue scripts[name] = x dest = self.j(self.RESOURCES, 'scripts.calibre_msgpack') if self.newer(dest, self.j(self.SRC, 'calibre', 'linux.py')): self.info('\tCreating ' + self.b(dest)) with open(dest, 'wb') as f: f.write(msgpack_dumps(scripts)) from calibre.web.feeds.recipes.collection import iterate_over_builtin_recipe_files, serialize_builtin_recipes files = [x[1] for x in iterate_over_builtin_recipe_files()] dest = self.j(self.RESOURCES, 'builtin_recipes.xml') if self.newer(dest, files): self.info('\tCreating builtin_recipes.xml') xml = serialize_builtin_recipes() with open(dest, 'wb') as f: f.write(xml) recipe_icon_dir = self.a(self.j(self.RESOURCES, '..', 'recipes', 'icons')) dest = os.path.splitext(dest)[0] + '.zip' files += glob.glob(self.j(recipe_icon_dir, '*.png')) if self.newer(dest, files): self.info('\tCreating builtin_recipes.zip') with zipfile.ZipFile(dest, 'w', zipfile.ZIP_STORED) as zf: for n in sorted(files, key=self.b): with open(n, 'rb') as f: zf.writestr(self.b(n), f.read()) dest = self.j(self.RESOURCES, 'ebook-convert-complete.calibre_msgpack') files = [] for x in os.walk(self.j(self.SRC, 'calibre')): for f in x[-1]: if f.endswith('.py'): files.append(self.j(x[0], f)) if self.newer(dest, files): self.info('\tCreating ' + self.b(dest)) complete = {} from calibre.ebooks.conversion.plumber import supported_input_formats complete['input_fmts'] = set(supported_input_formats()) from calibre.web.feeds.recipes.collection import get_builtin_recipe_titles complete['input_recipes'] = [t+'.recipe ' for t in get_builtin_recipe_titles()] from calibre.customize.ui import available_output_formats complete['output'] = set(available_output_formats()) from calibre.ebooks.conversion.cli import create_option_parser from calibre.utils.logging import Log log = Log() # log.outputs = [] for inf in supported_input_formats(): if inf in ('zip', 'rar', 'oebzip'): continue for ouf in available_output_formats(): of = ouf if ouf == 'oeb' else 'dummy.'+ouf p = create_option_parser(('ec', 'dummy1.'+inf, of, '-h'), log)[0] complete[(inf, ouf)] = [x+' 'for x in get_opts_from_parser(p)] with open(dest, 'wb') as f: f.write(msgpack_dumps(only_unicode_recursive(complete))) self.info('\tCreating template-functions.json') dest = self.j(self.RESOURCES, 'template-functions.json') function_dict = {} import inspect from calibre.utils.formatter_functions import formatter_functions for obj in formatter_functions().get_builtins().values(): eval_func = inspect.getmembers(obj, lambda x: inspect.ismethod(x) and x.__name__ == 'evaluate') try: lines = [l[4:] for l in inspect.getsourcelines(eval_func[0][1])[0]] except: continue lines = ''.join(lines) function_dict[obj.name] = lines dump_json(function_dict, dest) self.info('\tCreating editor-functions.json') dest = self.j(self.RESOURCES, 'editor-functions.json') function_dict = {} from calibre.gui2.tweak_book.function_replace import builtin_functions for func in builtin_functions(): try: src = ''.join(inspect.getsourcelines(func)[0][1:]) except Exception: continue src = src.replace('def ' + func.__name__, 'def replace') imports = [f'from {x.__module__} import {x.__name__}' for x in func.imports] if imports: src = '\n'.join(imports) + '\n\n' + src function_dict[func.name] = src dump_json(function_dict, dest) self.info('\tCreating user-manual-translation-stats.json') d = {} for lc, stats in iteritems(json.load(open(self.j(self.d(self.SRC), 'manual', 'locale', 'completed.json')))): total = sum(itervalues(stats)) d[lc] = stats['translated'] / float(total) dump_json(d, self.j(self.RESOURCES, 'user-manual-translation-stats.json')) src = self.j(self.SRC, '..', 'Changelog.txt') dest = self.j(self.RESOURCES, 'changelog.json') if self.newer(dest, [src]): self.info('\tCreating changelog.json') from setup.changelog import parse with open(src, encoding='utf-8') as f: dump_json(parse(f.read(), parse_dates=False), dest) def clean(self): for x in ('scripts', 'ebook-convert-complete'): x = self.j(self.RESOURCES, x+'.pickle') if os.path.exists(x): os.remove(x) from setup.commands import kakasi kakasi.clean() for x in ('builtin_recipes.xml', 'builtin_recipes.zip', 'template-functions.json', 'user-manual-translation-stats.json'): x = self.j(self.RESOURCES, x) if os.path.exists(x): os.remove(x) # }}}
13,044
Python
.py
292
33.496575
117
0.569426
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,343
file-hosting-bw.py
kovidgoyal_calibre/setup/file-hosting-bw.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import socket import subprocess BASE = '/srv/download/bw' def main(): if not os.path.exists(BASE): os.makedirs(BASE) os.chdir(BASE) for name in 'hours days months top10 summary'.split(): subprocess.check_call(['vnstati', '--' + name, '-o', name + '.png']) html = '''\ <!DOCTYPE html> <html> <head><title>Bandwidth usage for {host}</title></head> <body> <style> .float {{ float: left; margin-right:30px; margin-left:30px; text-align:center; width: 500px; }}</style> <h1>Bandwidth usage for {host}</h1> <div class="float"> <h2>Summary</h2> <img src="summary.png"/> </div> <div class="float"> <h2>Hours</h2> <img src="hours.png"/> </div> <div class="float"> <h2>Days</h2> <img src="days.png"/> </div> <div class="float"> <h2>Months</h2> <img src="months.png"/> </div> <div class="float"> <h2>Top10</h2> <img src="top10.png"/> </div> </body> </html> '''.format(host=socket.gethostname()) with open('index.html', 'wb') as f: f.write(html.encode('utf-8')) if __name__ == '__main__': main()
1,274
Python
.py
47
22.425532
115
0.582923
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,344
linux-installer.py
kovidgoyal_calibre/setup/linux-installer.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2009, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import errno import hashlib import os import platform import re import shutil import signal import socket import ssl import stat import subprocess import sys import tempfile from contextlib import closing is64bit = platform.architecture()[0] == '64bit' py3 = sys.version_info[0] > 2 enc = getattr(sys.stdout, 'encoding', 'utf-8') or 'utf-8' if enc.lower() == 'ascii': enc = 'utf-8' dl_url = calibre_version = signature = None has_ssl_verify = hasattr(ssl, 'create_default_context') is_linux_arm = is_linux_arm64 = False machine = (os.uname()[4] or '').lower() arch = 'x86_64' if machine.startswith('arm') or machine.startswith('aarch64'): is_linux_arm = True is_linux_arm64 = machine.startswith('arm64') or machine.startswith('aarch64') arch = 'arm64' if py3: unicode = str raw_input = input import http.client as httplib from urllib.parse import urlparse from urllib.request import BaseHandler, Request, addinfourl, build_opener, getproxies, urlopen def encode_for_subprocess(x): return x else: from urllib import addinfourl, getproxies, urlopen import httplib from future_builtins import map from urllib2 import BaseHandler, Request, build_opener from urlparse import urlparse def encode_for_subprocess(x): if isinstance(x, unicode): x = x.encode(enc) return x class TerminalController: # {{{ BOL = '' #: Move the cursor to the beginning of the line UP = '' #: Move the cursor up one line DOWN = '' #: Move the cursor down one line LEFT = '' #: Move the cursor left one char RIGHT = '' #: Move the cursor right one char # Deletion: CLEAR_SCREEN = '' #: Clear the screen and move to home position CLEAR_EOL = '' #: Clear to the end of the line. CLEAR_BOL = '' #: Clear to the beginning of the line. CLEAR_EOS = '' #: Clear to the end of the screen # Output modes: BOLD = '' #: Turn on bold mode BLINK = '' #: Turn on blink mode DIM = '' #: Turn on half-bright mode REVERSE = '' #: Turn on reverse-video mode NORMAL = '' #: Turn off all modes # Cursor display: HIDE_CURSOR = '' #: Make the cursor invisible SHOW_CURSOR = '' #: Make the cursor visible # Terminal size: COLS = None #: Width of the terminal (None for unknown) LINES = None #: Height of the terminal (None for unknown) # Foreground colors: BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = '' # Background colors: BG_BLACK = BG_BLUE = BG_GREEN = BG_CYAN = '' BG_RED = BG_MAGENTA = BG_YELLOW = BG_WHITE = '' _STRING_CAPABILITIES = """ BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1 CLEAR_SCREEN=clear CLEAR_EOL=el CLEAR_BOL=el1 CLEAR_EOS=ed BOLD=bold BLINK=blink DIM=dim REVERSE=rev UNDERLINE=smul NORMAL=sgr0 HIDE_CURSOR=cinvis SHOW_CURSOR=cnorm""".split() _COLORS = """BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE""".split() _ANSICOLORS = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".split() def __init__(self, term_stream=sys.stdout): # Curses isn't available on all platforms try: import curses except: return # If the stream isn't a tty, then assume it has no capabilities. if not hasattr(term_stream, 'isatty') or not term_stream.isatty(): return # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return # Look up numeric capabilities. self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') # Look up string capabilities. for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._escape_code(self._tigetstr(cap_name))) # Colors set_fg = self._tigetstr('setf') if set_fg: if not isinstance(set_fg, bytes): set_fg = set_fg.encode('utf-8') for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, self._escape_code(curses.tparm((set_fg), i))) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: if not isinstance(set_fg_ansi, bytes): set_fg_ansi = set_fg_ansi.encode('utf-8') for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, self._escape_code(curses.tparm((set_fg_ansi), i))) set_bg = self._tigetstr('setb') if set_bg: if not isinstance(set_bg, bytes): set_bg = set_bg.encode('utf-8') for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, self._escape_code(curses.tparm((set_bg), i))) set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: if not isinstance(set_bg_ansi, bytes): set_bg_ansi = set_bg_ansi.encode('utf-8') for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, self._escape_code(curses.tparm((set_bg_ansi), i))) def _escape_code(self, raw): if not raw: raw = '' if not isinstance(raw, unicode): raw = raw.decode('ascii') return raw def _tigetstr(self, cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. import curses if isinstance(cap_name, bytes): cap_name = cap_name.decode('utf-8') cap = self._escape_code(curses.tigetstr(cap_name)) return re.sub(r'\$<\d+>[/*]?', '', cap) def render(self, template): return re.sub(r'\$\$|\${\w+}', self._render_sub, template) def _render_sub(self, match): s = match.group() if s == '$$': return s else: return getattr(self, s[2:-1]) class ProgressBar: BAR = '%3d%% ${GREEN}[${BOLD}%s%s${NORMAL}${GREEN}]${NORMAL}\n' HEADER = '${BOLD}${CYAN}%s${NORMAL}\n\n' def __init__(self, term, header): self.term = term if not (self.term.CLEAR_EOL and self.term.UP and self.term.BOL): raise ValueError("Terminal isn't capable enough -- you " "should use a simpler progress display.") self.width = self.term.COLS or 75 self.bar = term.render(self.BAR) self.header = self.term.render(self.HEADER % header.center(self.width)) self.cleared = 1 # : true if we haven't drawn the bar yet. def update(self, percent, message=''): out = (sys.stdout.buffer if py3 else sys.stdout) if self.cleared: out.write(self.header.encode(enc)) self.cleared = 0 n = int((self.width-10)*percent) msg = message.center(self.width) msg = (self.term.BOL + self.term.UP + self.term.CLEAR_EOL + ( self.bar % (100*percent, '='*n, '-'*(self.width-10-n))) + self.term.CLEAR_EOL + msg).encode(enc) out.write(msg) out.flush() def clear(self): out = (sys.stdout.buffer if py3 else sys.stdout) if not self.cleared: out.write((self.term.BOL + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL).encode(enc)) self.cleared = 1 out.flush() # }}} def prints(*args, **kwargs): # {{{ f = kwargs.get('file', sys.stdout.buffer if py3 else sys.stdout) end = kwargs.get('end', b'\n') enc = getattr(f, 'encoding', 'utf-8') or 'utf-8' if isinstance(end, unicode): end = end.encode(enc) for x in args: if isinstance(x, unicode): x = x.encode(enc) f.write(x) f.write(b' ') f.write(end) if py3 and f is sys.stdout.buffer: f.flush() # }}} class Reporter: # {{{ def __init__(self, fname): try: self.pb = ProgressBar(TerminalController(), 'Downloading '+fname) except ValueError: prints('Downloading', fname) self.pb = None self.last_percent = 0 def __call__(self, blocks, block_size, total_size): percent = (blocks*block_size)/float(total_size) if self.pb is None: if percent - self.last_percent > 0.05: self.last_percent = percent prints('Downloaded {0:%}'.format(percent)) else: try: self.pb.update(percent) except: import traceback traceback.print_exc() # }}} # Downloading {{{ def clean_cache(cache, fname): for x in os.listdir(cache): if fname not in x: os.remove(os.path.join(cache, x)) def check_signature(dest, signature): if not os.path.exists(dest): return None m = hashlib.sha512() with open(dest, 'rb') as f: raw = f.read() m.update(raw) if m.hexdigest().encode('ascii') == signature: return raw class RangeHandler(BaseHandler): def http_error_206(self, req, fp, code, msg, hdrs): # 206 Partial Content Response r = addinfourl(fp, hdrs, req.get_full_url()) r.code = code r.msg = msg return r https_error_206 = http_error_206 def do_download(dest): prints('Will download and install', os.path.basename(dest)) reporter = Reporter(os.path.basename(dest)) offset = 0 if os.path.exists(dest): offset = os.path.getsize(dest) # Get content length and check if range is supported rq = urlopen(dl_url) headers = rq.info() size = int(headers['content-length']) accepts_ranges = headers.get('accept-ranges', None) == 'bytes' mode = 'wb' if accepts_ranges and offset > 0: req = Request(rq.geturl()) req.add_header('Range', 'bytes=%s-'%offset) mode = 'ab' rq.close() handler = RangeHandler() opener = build_opener(handler) rq = opener.open(req) with open(dest, mode) as f: while f.tell() < size: raw = rq.read(8192) if not raw: break f.write(raw) reporter(f.tell(), 1, size) rq.close() if os.path.getsize(dest) < size: print('Download failed, try again later') raise SystemExit(1) prints('Downloaded %s bytes'%os.path.getsize(dest)) def download_tarball(): fname = 'calibre-%s-%s.%s'%(calibre_version, arch, 'txz') tdir = tempfile.gettempdir() cache = os.path.join(tdir, 'calibre-installer-cache') if not os.path.exists(cache): os.makedirs(cache) clean_cache(cache, fname) dest = os.path.join(cache, fname) raw = check_signature(dest, signature) if raw is not None: print('Using previously downloaded', fname) return raw cached_sigf = dest +'.signature' cached_sig = None if os.path.exists(cached_sigf): with open(cached_sigf, 'rb') as sigf: cached_sig = sigf.read() if cached_sig != signature and os.path.exists(dest): os.remove(dest) try: with open(cached_sigf, 'wb') as f: f.write(signature) except IOError as e: if e.errno != errno.EACCES: raise print('The installer cache directory has incorrect permissions.' ' Delete %s and try again.'%cache) raise SystemExit(1) do_download(dest) prints('Checking downloaded file integrity...') raw = check_signature(dest, signature) if raw is None: os.remove(dest) print('The downloaded files\' signature does not match. ' 'Try the download again later.') raise SystemExit(1) return raw # }}} # Get tarball signature securely {{{ def get_proxies(debug=True): proxies = getproxies() for key, proxy in list(proxies.items()): if not proxy or '..' in proxy: del proxies[key] continue if proxy.startswith(key+'://'): proxy = proxy[len(key)+3:] if key == 'https' and proxy.startswith('http://'): proxy = proxy[7:] if proxy.endswith('/'): proxy = proxy[:-1] if len(proxy) > 4: proxies[key] = proxy else: prints('Removing invalid', key, 'proxy:', proxy) del proxies[key] if proxies and debug: prints('Using proxies:', repr(proxies)) return proxies class HTTPError(ValueError): def __init__(self, url, code): msg = '%s returned an unsupported http response code: %d (%s)' % ( url, code, httplib.responses.get(code, None)) ValueError.__init__(self, msg) self.code = code self.url = url class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False parts = dn.split(r'.') leftmost, remainder = parts[0], parts[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survery of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname) def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_match(value, hostname): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: # python 2.7.2 does not read subject alt names thanks to this # bug: http://bugs.python.org/issue13034 # And the utter lunacy that is the linux landscape could have # any old version of python whatsoever with or without a hot fix for # this bug. Not to mention that python 2.6 may or may not # read alt names depending on its patchlevel. So we just bail on full # verification if the python version is less than 2.7.3. # Linux distros are one enormous, honking disaster. if sys.version_info[:3] < (2, 7, 3) and dnsnames[0] == 'calibre-ebook.com': return raise CertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or " "subjectAltName fields were found") if has_ssl_verify: class HTTPSConnection(httplib.HTTPSConnection): def __init__(self, ssl_version, *args, **kwargs): kwargs['context'] = ssl.create_default_context(cafile=kwargs.pop('cert_file')) if hasattr(ssl, 'VERIFY_X509_STRICT'): kwargs['context'].verify_flags &= ~ssl.VERIFY_X509_STRICT httplib.HTTPSConnection.__init__(self, *args, **kwargs) else: class HTTPSConnection(httplib.HTTPSConnection): def __init__(self, ssl_version, *args, **kwargs): httplib.HTTPSConnection.__init__(self, *args, **kwargs) self.calibre_ssl_version = ssl_version def connect(self): """Connect to a host on a given (SSL) port, properly verifying the SSL certificate, both that it is valid and that its declared hostnames match the hostname we are connecting to.""" if hasattr(self, 'source_address'): sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) else: # python 2.6 has no source_address sock = socket.create_connection((self.host, self.port), self.timeout) if self._tunnel_host: self.sock = sock self._tunnel() self.sock = ssl.wrap_socket(sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.cert_file, ssl_version=self.calibre_ssl_version) getattr(ssl, 'match_hostname', match_hostname)(self.sock.getpeercert(), self.host) CACERT = b'''\ -----BEGIN CERTIFICATE----- MIIFzjCCA7agAwIBAgIJAKfuFL6Cvpn4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV BAYTAklOMRQwEgYDVQQIDAtNYWhhcmFzaHRyYTEPMA0GA1UEBwwGTXVtYmFpMRAw DgYDVQQKDAdjYWxpYnJlMRowGAYDVQQDDBFjYWxpYnJlLWVib29rLmNvbTAgFw0x NTEyMjMwNTQ2NTlaGA8yMTE1MTEyOTA1NDY1OVowYjELMAkGA1UEBhMCSU4xFDAS BgNVBAgMC01haGFyYXNodHJhMQ8wDQYDVQQHDAZNdW1iYWkxEDAOBgNVBAoMB2Nh bGlicmUxGjAYBgNVBAMMEWNhbGlicmUtZWJvb2suY29tMIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEAtlbeAxQKyWhoxwaGqMh5ktRhqsLR6uzjuqWmB+Mm fC0Ni45mOSo2R/usFQTZesrYUoo2yBhMN58CsLeuaaQfsPeDss7zJ9jX0v/GYUS3 vM7qE55ruRWu0g11NpuWLZkqvcw5gVi3ZJYx/yqTEGlCDGxjXVs9iEg+L75Bcm9y 87olbcZA6H/CbR5lP1/tXcyyb1TBINuTcg408SnieY/HpnA1r3NQB9MwfScdX08H TB0Bc8e0qz+r1BNi3wZZcrNpqWhw6X9QkHigGaDNppmWqc1Q5nxxk2rC21GRg56n p6t3ENQMctE3KTJfR8TwM33N/dfcgobDZ/ZTnogqdFQycFOgvT4mIZsXdsJv6smy hlkUqye2PV8XcTNJr+wRzIN/+u23jC+CaT0U0A57D8PUZVhT+ZshXjB91Ko8hLE1 SmJkdv2bxFV42bsemhSxZWCtsc2Nv8/Ds+WVV00xfADym+LokzEqqfcK9vkkMGzF h7wzd7YqPOrMGOCe9vH1CoL3VO5srPV+0Mp1fjIGgm5SIhklyRfaeIjFeyoDRA6e 8EXrI3xOsrkXXMJDvhndEJOYYqplY+4kLhW0XeTZjK7CmD59xRtFYWaV3dcMlaWb VxuY7dgsiO7iUztYY0To5ZDExcHem7PEPUTyFii9LhbcSJeXDaqPFMxih+X0iqKv ni8CAwEAAaOBhDCBgTAxBgNVHREEKjAoghFjYWxpYnJlLWVib29rLmNvbYITKi5j YWxpYnJlLWVib29rLmNvbTAdBgNVHQ4EFgQURWqz5EOg5K1OrSKpleR+louVxsQw HwYDVR0jBBgwFoAURWqz5EOg5K1OrSKpleR+louVxsQwDAYDVR0TBAUwAwEB/zAN BgkqhkiG9w0BAQsFAAOCAgEAS1+Jx0VyTrEFUQ5jEIx/7WrL4GDnzxjeXWJTyKSk YqcOvXZpwwrTHJSGHj7MpCqWIzQnHxICBFlUEVcb1g1UPvNB5OY69eLjlYdwfOK9 bfp/KnLCsn7Pf4UCATRslX9J1LV6r17X2ONWWmSutDeGP1azXVxwFsogvvqwPHCs nlfvQycUcd4HWIZWBJ1n4Ry6OwdpFuHktRVtNtTlD34KUjzcN2GCA08Ur+1eiA9D /Oru1X4hfA3gbiAlGJ/+3AQw0oYS0IEW1HENurkIDNs98CXTiau9OXRECgGjE3hC viECb4beyhEOH5y1dQJZEynwvSepFG8wDJWmkVN7hMrfbZF4Ec0BmsJpbuq5GrdV cXUXJbLrnADFV9vkciLb3pl7gAmHi1T19i/maWMiYqIAh7Ezi/h6ufGbPiG+vfLt f4ywTKQeQKAamBW4P2oFgcmlPDlDeVFWdkF1aC0WFct5/R7Fea0D2bOVt52zm3v3 Ghni3NYEZzXHf08c8tzXZmM1Q39sSS1vn2B9PgiYj87Xg9Fxn1trKFdsiry1F2Qx qDq1u+xTdjPKwVVB1zd5g3MM/YYTVRhuH2AZU/Z4qX8DAf9ESqLqUpEOpyvLkX3r gENtRgsmhjlf/Qwymuz8nnzJD5c4TgCicVjPNArprVtmyfOXLVXJLC+KpkzTxvdr nR0= -----END CERTIFICATE----- ''' def get_https_resource_securely(url, timeout=60, max_redirects=5, ssl_version=None): ''' Download the resource pointed to by url using https securely (verify server certificate). Ensures that redirects, if any, are also downloaded securely. Needs a CA certificates bundle (in PEM format) to verify the server's certificates. ''' if ssl_version is None: try: ssl_version = ssl.PROTOCOL_TLSv1_2 except AttributeError: ssl_version = ssl.PROTOCOL_TLSv1 # old python with tempfile.NamedTemporaryFile(prefix='calibre-ca-cert-') as f: f.write(CACERT) f.flush() p = urlparse(url) if p.scheme != 'https': raise ValueError('URL %s scheme must be https, not %r' % (url, p.scheme)) hostname, port = p.hostname, p.port proxies = get_proxies() has_proxy = False for q in ('https', 'http'): if q in proxies: try: h, po = proxies[q].rpartition(':')[::2] po = int(po) if h: hostname, port, has_proxy = h, po, True break except Exception: # Invalid proxy, ignore pass c = HTTPSConnection(ssl_version, hostname, port, cert_file=f.name, timeout=timeout) if has_proxy: c.set_tunnel(p.hostname, p.port) with closing(c): c.connect() # This is needed for proxy connections path = p.path or '/' if p.query: path += '?' + p.query c.request('GET', path) response = c.getresponse() if response.status in (httplib.MOVED_PERMANENTLY, httplib.FOUND, httplib.SEE_OTHER): if max_redirects <= 0: raise ValueError('Too many redirects, giving up') newurl = response.getheader('Location', None) if newurl is None: raise ValueError('%s returned a redirect response with no Location header' % url) return get_https_resource_securely( newurl, timeout=timeout, max_redirects=max_redirects-1, ssl_version=ssl_version) if response.status != httplib.OK: raise HTTPError(url, response.status) return response.read() # }}} def extract_tarball(raw, destdir): prints('Extracting application files...') with open('/dev/null', 'w') as null: p = subprocess.Popen( list(map(encode_for_subprocess, ['tar', 'xJof', '-', '-C', destdir])), stdout=null, stdin=subprocess.PIPE, close_fds=True, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)) p.stdin.write(raw) p.stdin.close() if p.wait() != 0: prints('Extracting of application files failed with error code: %s' % p.returncode) raise SystemExit(1) def get_tarball_info(version): global dl_url, signature, calibre_version print('Downloading tarball signature securely...') if version: sigfname = 'calibre-' + version + '-' + arch + '.txz.sha512' try: signature = get_https_resource_securely('https://code.calibre-ebook.com/signatures/' + sigfname) except HTTPError as err: if err.code != 404: raise signature = get_https_resource_securely('https://code.calibre-ebook.com/signatures/old/' + sigfname) calibre_version = version dl_url = 'https://download.calibre-ebook.com/' + version + '/calibre-' + version + '-' + arch + '.txz' else: raw = get_https_resource_securely( 'https://code.calibre-ebook.com/tarball-info/' + arch) signature, calibre_version = raw.rpartition(b'@')[::2] dl_url = 'https://calibre-ebook.com/dist/linux-' + arch if not signature or not calibre_version: raise ValueError('Failed to get install file signature, invalid signature returned') dl_url = os.environ.get('CALIBRE_INSTALLER_LOCAL_URL', dl_url) if isinstance(calibre_version, bytes): calibre_version = calibre_version.decode('utf-8') def download_and_extract(destdir, version): get_tarball_info(version) raw = download_tarball() if os.path.exists(destdir): shutil.rmtree(destdir) os.makedirs(destdir) print('Extracting files to %s ...'%destdir) extract_tarball(raw, destdir) def run_installer(install_dir, isolated, bin_dir, share_dir, version): destdir = os.path.abspath(os.path.expanduser(install_dir or '/opt')) if destdir == '/usr/bin': prints(destdir, 'is not a valid install location. Choose', end='') prints('a location like /opt or /usr/local') return 1 destdir = os.path.realpath(os.path.join(destdir, 'calibre')) if os.path.exists(destdir): if not os.path.isdir(destdir): prints(destdir, 'exists and is not a directory. Choose a location like /opt or /usr/local') return 1 print('Installing to', destdir) download_and_extract(destdir, version) if not isolated: pi = [os.path.join(destdir, 'calibre_postinstall')] if bin_dir is not None: pi.extend(['--bindir', bin_dir]) if share_dir is not None: pi.extend(['--sharedir', share_dir]) subprocess.call(pi) prints('Run "calibre" to start calibre') else: prints('Run "%s/calibre" to start calibre' % destdir) return 0 def check_umask(): # A bad umask can cause system breakage because of bugs in xdg-mime # See https://www.mobileread.com/forums/showthread.php?t=277803 mask = os.umask(18) # 18 = 022 os.umask(mask) forbid_user_read = mask & stat.S_IRUSR forbid_user_exec = mask & stat.S_IXUSR forbid_group_read = mask & stat.S_IRGRP forbid_group_exec = mask & stat.S_IXGRP forbid_other_read = mask & stat.S_IROTH forbid_other_exec = mask & stat.S_IXOTH if forbid_user_read or forbid_user_exec or forbid_group_read or forbid_group_exec or forbid_other_read or forbid_other_exec: prints( 'WARNING: Your current umask disallows reading of files by some users,' ' this can cause system breakage when running the installer because' ' of bugs in common system utilities.' ) sys.stdin = open('/dev/tty') # stdin is a pipe from wget while True: q = raw_input('Should the installer (f)ix the umask, (i)gnore it or (a)bort [f/i/a Default is abort]: ') or 'a' if q in 'f i a'.split(): break prints('Response', q, 'not understood') if q == 'f': mask = mask & ~stat.S_IRUSR & ~stat.S_IXUSR & ~stat.S_IRGRP & ~stat.S_IXGRP & ~stat.S_IROTH & ~stat.S_IXOTH os.umask(mask) prints('umask changed to: {:03o}'.format(mask)) elif q == 'i': prints('Ignoring bad umask and proceeding anyway, you have been warned!') else: raise SystemExit('The system umask is unsuitable, aborting') def check_for_libEGL(): import ctypes try: ctypes.CDLL('libEGL.so.1') return except Exception: pass raise SystemExit('You are missing the system library libEGL.so.1. Try installing packages such as libegl1 and libopengl0') def check_for_libOpenGl(): import ctypes try: ctypes.CDLL('libOpenGL.so.0') return except Exception: pass raise SystemExit('You are missing the system library libOpenGL.so.0. Try installing packages such as libopengl0') def check_for_libxcb_cursor(): import ctypes try: ctypes.CDLL('libxcb-cursor.so.0') return except Exception: pass raise SystemExit('You are missing the system library libxcb-cursor.so.0. Try installing packages such as libxcb-cursor0 or xcb-cursor') def check_glibc_version(min_required=(2, 31), release_date='2020-02-01'): # See https://sourceware.org/glibc/wiki/Glibc%20Timeline import ctypes libc = ctypes.CDLL(None) try: f = libc.gnu_get_libc_version except AttributeError: raise SystemExit('Your system is not based on GNU libc. The calibre binaries require GNU libc') f.restype = ctypes.c_char_p ver = f().decode('ascii') q = tuple(map(int, ver.split('.'))) if q < min_required: raise SystemExit( ('Your system has GNU libc version {}. The calibre binaries require at least' ' version: {} (released on {}). Update your system.' ).format(ver, '.'.join(map(str, min_required)), release_date)) def check_for_recent_freetype(): import ctypes f = None try: f = ctypes.CDLL('libfreetype.so.6') except OSError: raise SystemExit('Your system is missing the FreeType library libfreetype.so. Try installing the freetype package.') try: f.FT_Get_Color_Glyph_Paint except AttributeError: raise SystemExit('Your system has too old a version of the FreeType library.' ' freetype >= 2.11 is needed for the FT_Get_Color_Glyph_Paint function which is required by Qt WebEngine') def main(install_dir=None, isolated=False, bin_dir=None, share_dir=None, ignore_umask=False, version=None): if not ignore_umask and not isolated: check_umask() if (is_linux_arm and not is_linux_arm64) or not is64bit: raise SystemExit( 'You are running on a 32-bit system. The calibre binaries are only' ' available for 64-bit systems. You will have to compile from' ' source.') glibc_versions = { (6, 0, 0) : {'min_required': (2, 31), 'release_date': '2020-02-01'}, (7, 17, 0) : {'min_required': (2, 35), 'release_date': '2022-02-03'} } if is_linux_arm64: glibc_versions.update({ (6, 8, 0) : {'min_required': (2, 34), 'release_date': '2021-08-02'} }) q = tuple(map(int, version.split('.'))) if version else (sys.maxsize, 999, 999) for key in sorted(glibc_versions, reverse=True): if q >= key: check_glibc_version(**glibc_versions[key]) break if q[0] >= 6: check_for_libEGL() check_for_libOpenGl() if q[0] >= 7: check_for_libxcb_cursor() if q >= (7, 16, 0): check_for_recent_freetype() run_installer(install_dir, isolated, bin_dir, share_dir, version) try: __file__ from_file = True except NameError: from_file = False def update_installer_wrapper(): # To update: python3 -c "import runpy; runpy.run_path('setup/linux-installer.py', run_name='update_wrapper')" with open(__file__, 'rb') as f: src = f.read().decode('utf-8') wrapper = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'linux-installer.sh') with open(wrapper, 'r+b') as f: raw = f.read().decode('utf-8') nraw = re.sub(r'^# HEREDOC_START.+^# HEREDOC_END', lambda m: '# HEREDOC_START\n{}\n# HEREDOC_END'.format(src), raw, flags=re.MULTILINE | re.DOTALL) if 'update_installer_wrapper()' not in nraw: raise SystemExit('regex substitute of HEREDOC failed') f.seek(0), f.truncate() f.write(nraw.encode('utf-8')) def script_launch(): def path(x): return os.path.expanduser(x) def to_bool(x): return x.lower() in ('y', 'yes', '1', 'true') type_map = {x: path for x in 'install_dir isolated bin_dir share_dir ignore_umask version'.split()} type_map['isolated'] = type_map['ignore_umask'] = to_bool kwargs = {} for arg in sys.argv[1:]: if arg: m = re.match('([a-z_]+)=(.+)', arg) if m is None: raise SystemExit('Unrecognized command line argument: ' + arg) k = m.group(1) if k not in type_map: raise SystemExit('Unrecognized command line argument: ' + arg) kwargs[k] = type_map[k](m.group(2)) main(**kwargs) if __name__ == '__main__' and from_file: main() elif __name__ == 'update_wrapper': update_installer_wrapper()
33,426
Python
.py
773
35.010349
155
0.627198
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,345
iso_codes.py
kovidgoyal_calibre/setup/iso_codes.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> import fnmatch import optparse import os import shutil import time import zipfile from contextlib import suppress from functools import lru_cache from io import BytesIO from setup import Command, download_securely @lru_cache(2) def iso_codes_data(): URL = 'https://download.calibre-ebook.com/iso-codes.zip' return download_securely(URL) class ISOData(Command): description = 'Get ISO codes name localization data' top_level_filename = 'iso-codes-main' _zip_data = None def add_options(self, parser): with suppress(optparse.OptionConflictError): # ignore if option already added parser.add_option('--path-to-isocodes', help='Path to previously downloaded iso-codes-main.zip') def run(self, opts): if self._zip_data is None and opts.path_to_isocodes: with open(opts.path_to_isocodes, 'rb') as f: self._zip_data = f.read() # get top level directory top = {item.split('/')[0] for item in zipfile.ZipFile(self.zip_data).namelist()} assert len(top) == 1 self.top_level_filename = top.pop() @property def zip_data(self): return self._zip_data or iso_codes_data() def db_data(self, name: str) -> bytes: with zipfile.ZipFile(BytesIO(self.zip_data)) as zf: with zf.open(f'{self.top_level_filename}/data/{name}') as f: return f.read() def extract_po_files(self, name: str, output_dir: str) -> None: name = name.split('.', 1)[0] pat = f'{self.top_level_filename}/{name}/*.po' with zipfile.ZipFile(BytesIO(self.zip_data)) as zf: for name in fnmatch.filter(zf.namelist(), pat): dest = os.path.join(output_dir, name.split('/')[-1]) zi = zf.getinfo(name) with zf.open(zi) as src, open(dest, 'wb') as d: shutil.copyfileobj(src, d) date_time = time.mktime(zi.date_time + (0, 0, -1)) os.utime(dest, (date_time, date_time)) iso_data = ISOData()
2,162
Python
.py
50
35.42
108
0.631729
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,346
revendor.py
kovidgoyal_calibre/setup/revendor.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> import os import shutil import tarfile import time from io import BytesIO from setup import Command, download_securely, is_ci class ReVendor(Command): # NAME = TAR_NAME = VERSION = DOWNLOAD_URL = '' CAN_USE_SYSTEM_VERSION = True def add_options(self, parser): parser.add_option('--path-to-%s' % self.NAME, help='Path to the extracted %s source' % self.TAR_NAME) parser.add_option('--%s-url' % self.NAME, default=self.DOWNLOAD_URL, help='URL to %s source archive in tar.gz format' % self.TAR_NAME) if self.CAN_USE_SYSTEM_VERSION: parser.add_option('--system-%s' % self.NAME, default=False, action='store_true', help='Treat %s as system copy and symlink instead of copy' % self.TAR_NAME) def download_securely(self, url: str) -> bytes: num = 5 if is_ci else 1 for i in range(num): try: return download_securely(url) except Exception as err: if i == num - 1: raise self.info(f'Download failed with error "{err}" sleeping and retrying...') time.sleep(2) def download_vendor_release(self, tdir, url): self.info('Downloading %s:' % self.TAR_NAME, url) raw = self.download_securely(url) with tarfile.open(fileobj=BytesIO(raw)) as tf: tf.extractall(tdir) if len(os.listdir(tdir)) == 1: return self.j(tdir, os.listdir(tdir)[0]) else: return tdir def add_file_pre(self, name, raw): pass def add_file(self, path, name): with open(path, 'rb') as f: raw = f.read() self.add_file_pre(name, raw) dest = self.j(self.vendored_dir, *name.split('/')) base = os.path.dirname(dest) if not os.path.exists(base): os.makedirs(base) if self.use_symlinks: os.symlink(path, dest) else: with open(dest, 'wb') as f: f.write(raw) def add_tree(self, base, prefix, ignore=lambda n:False): for dirpath, dirnames, filenames in os.walk(base): for fname in filenames: f = os.path.join(dirpath, fname) name = prefix + '/' + os.path.relpath(f, base).replace(os.sep, '/') if not ignore(name): self.add_file(f, name) @property def vendored_dir(self): return self.j(self.RESOURCES, self.NAME) def clean(self): if os.path.exists(self.vendored_dir): shutil.rmtree(self.vendored_dir)
2,725
Python
.py
65
31.861538
109
0.581791
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,347
browser_data.py
kovidgoyal_calibre/setup/browser_data.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import bz2 import os import ssl import sys from datetime import datetime, timezone from urllib.request import urlopen def download_from_calibre_server(url): ca = os.path.join(sys.resources_location, 'calibre-ebook-root-CA.crt') ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_verify_locations(ca) return urlopen(url, context=ssl_context).read() def filter_ans(ans): return list(filter(None, (x.strip() for x in ans))) def common_user_agents(): print('Getting recent UAs...') raw = download_from_calibre_server('https://code.calibre-ebook.com/ua-popularity') ans = {} for line in bz2.decompress(raw).decode('utf-8').splitlines(): count, ua = line.partition(':')[::2] count = int(count.strip()) ua = ua.strip() if len(ua) > 25 and 'python' not in ua: ans[ua] = count return ans, list(sorted(ans, reverse=True, key=ans.__getitem__)) def all_desktop_platforms(user_agents): ans = set() for ua in user_agents: if ' Mobile ' not in ua and 'Mobile/' not in ua and ('Firefox/' in ua or 'Chrome/' in ua): plat = ua.partition('(')[2].partition(')')[0] parts = plat.split(';') if 'Firefox/' in ua: del parts[-1] ans.add(';'.join(parts)) return ans def get_data(): ua_freq_map, common = common_user_agents() ans = { 'common_user_agents': common, 'user_agents_popularity': ua_freq_map, 'timestamp': datetime.now(timezone.utc).isoformat(), } ans['desktop_platforms'] = list(all_desktop_platforms(ans['common_user_agents'])) return ans
1,762
Python
.py
45
33.177778
98
0.643988
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,348
unix-ci.py
kovidgoyal_calibre/setup/unix-ci.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import glob import io import os import shlex import subprocess import sys import tarfile import time from tempfile import NamedTemporaryFile from urllib.request import urlopen _plat = sys.platform.lower() ismacos = 'darwin' in _plat iswindows = 'win32' in _plat or 'win64' in _plat def setenv(key, val): os.environ[key] = os.path.expandvars(val) if ismacos: SWBASE = '/Users/Shared/calibre-build/sw' SW = SWBASE + '/sw' def install_env(): setenv('SWBASE', SWBASE) setenv('SW', SW) setenv( 'PATH', '$SW/bin:$SW/qt/bin:$SW/python/Python.framework/Versions/2.7/bin:$PWD/node_modules/.bin:$PATH' ) setenv('CFLAGS', '-I$SW/include') setenv('LDFLAGS', '-L$SW/lib') setenv('QMAKE', '$SW/qt/bin/qmake') setenv('QTWEBENGINE_DISABLE_SANDBOX', '1') setenv('QT_PLUGIN_PATH', '$SW/qt/plugins') old = os.environ.get('DYLD_FALLBACK_LIBRARY_PATH', '') if old: old += ':' setenv('DYLD_FALLBACK_LIBRARY_PATH', old + '$SW/lib') else: SWBASE = '/sw' SW = SWBASE + '/sw' def install_env(): setenv('SW', SW) setenv('PATH', '$SW/bin:$PATH') setenv('CFLAGS', '-I$SW/include') setenv('LDFLAGS', '-L$SW/lib') setenv('LD_LIBRARY_PATH', '$SW/qt/lib:$SW/ffmpeg/lib:$SW/lib') setenv('PKG_CONFIG_PATH', '$SW/lib/pkgconfig') setenv('QMAKE', '$SW/qt/bin/qmake') setenv('CALIBRE_QT_PREFIX', '$SW/qt') def run(*args, timeout=600): if len(args) == 1: args = shlex.split(args[0]) print(' '.join(args), flush=True) p = subprocess.Popen(args) try: ret = p.wait(timeout=timeout) except subprocess.TimeoutExpired as err: ret = 1 print(err, file=sys.stderr, flush=True) print('Timed out running:', ' '.join(args), flush=True, file=sys.stderr) p.kill() if ret != 0: raise SystemExit(ret) def decompress(path, dest, compression): run('tar', 'x' + compression + 'f', path, '-C', dest) def download_and_decompress(url, dest, compression=None): if compression is None: compression = 'j' if url.endswith('.bz2') else 'J' for i in range(5): print('Downloading', url, '...') with NamedTemporaryFile() as f: ret = subprocess.Popen(['curl', '-fSL', url], stdout=f).wait() if ret == 0: decompress(f.name, dest, compression) sys.stdout.flush(), sys.stderr.flush() return time.sleep(1) raise SystemExit('Failed to download ' + url) def install_qt_source_code(): dest = os.path.expanduser('~/qt-base') os.mkdir(dest) download_and_decompress('https://download.calibre-ebook.com/qtbase-everywhere-src-6.4.2.tar.xz', dest, 'J') qdir = glob.glob(dest + '/*')[0] os.environ['QT_SRC'] = qdir def run_python(*args): python = os.path.expandvars('$SW/bin/python') if len(args) == 1: args = shlex.split(args[0]) args = [python] + list(args) return run(*args) def install_linux_deps(): run('sudo', 'apt-get', 'update', '-y') # run('sudo', 'apt-get', 'upgrade', '-y') run('sudo', 'apt-get', 'install', '-y', 'gettext', 'libgl1-mesa-dev', 'libxkbcommon-dev', 'libxkbcommon-x11-dev', 'pulseaudio', 'libasound2', 'libflite1', 'libspeechd2') def get_tx(): url = 'https://github.com/transifex/cli/releases/latest/download/tx-linux-amd64.tar.gz' print('Downloading:', url) with urlopen(url) as f: raw = f.read() with tarfile.open(fileobj=io.BytesIO(raw), mode='r') as tf: tf.extract('tx') def main(): if iswindows: import runpy m = runpy.run_path('setup/win-ci.py') return m['main']() action = sys.argv[1] if action == 'install': run('sudo', 'mkdir', '-p', SW) run('sudo', 'chown', '-R', os.environ['USER'], SWBASE) tball = 'macos-64' if ismacos else 'linux-64' download_and_decompress( f'https://download.calibre-ebook.com/ci/calibre7/{tball}.tar.xz', SW ) if not ismacos: install_linux_deps() elif action == 'bootstrap': install_env() run_python('setup.py bootstrap --ephemeral') elif action == 'pot': transifexrc = '''\ [https://www.transifex.com] api_hostname = https://api.transifex.com rest_hostname = https://rest.api.transifex.com hostname = https://www.transifex.com password = PASSWORD token = PASSWORD username = api '''.replace('PASSWORD', os.environ['tx']) with open(os.path.expanduser('~/.transifexrc'), 'w') as f: f.write(transifexrc) install_qt_source_code() install_env() get_tx() os.environ['TX'] = os.path.abspath('tx') run(sys.executable, 'setup.py', 'pot', timeout=30 * 60) elif action == 'test': os.environ['CI'] = 'true' os.environ['OPENSSL_MODULES'] = os.path.join(SW, 'lib', 'ossl-modules') os.environ['PIPER_TTS_DIR'] = os.path.join(SW, 'piper') if ismacos: os.environ['SSL_CERT_FILE'] = os.path.abspath( 'resources/mozilla-ca-certs.pem') # needed to ensure correct libxml2 is loaded os.environ['DYLD_INSERT_LIBRARIES'] = ':'.join(os.path.join(SW, 'lib', x) for x in 'libxml2.dylib libxslt.dylib libexslt.dylib'.split()) os.environ['OPENSSL_ENGINES'] = os.path.join(SW, 'lib', 'engines-3') install_env() run_python('setup.py test') run_python('setup.py test_rs') else: raise SystemExit(f'Unknown action: {action}') if __name__ == '__main__': main()
5,794
Python
.py
153
31
148
0.600678
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,349
test.py
kovidgoyal_calibre/setup/test.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import os import subprocess import sys from setup import Command, is_ci, ismacos, iswindows TEST_MODULES = frozenset('srv db polish opf css docx cfi matcher icu smartypants build misc dbcli ebooks'.split()) class BaseTest(Command): def run(self, opts): if opts.under_sanitize and 'CALIBRE_EXECED_UNDER_SANITIZE' not in os.environ: if 'libasan' not in os.environ.get('LD_PRELOAD', ''): os.environ['LD_PRELOAD'] = os.path.abspath(subprocess.check_output('gcc -print-file-name=libasan.so'.split()).decode('utf-8').strip()) os.environ['CALIBRE_EXECED_UNDER_SANITIZE'] = '1' os.environ['ASAN_OPTIONS'] = 'detect_leaks=0' os.environ['PYCRYPTODOME_DISABLE_DEEPBIND'] = '1' # https://github.com/Legrandin/pycryptodome/issues/558 self.info(f'Re-execing with LD_PRELOAD={os.environ["LD_PRELOAD"]}') sys.stdout.flush() os.execl('setup.py', *sys.argv) def add_options(self, parser): parser.add_option('--under-sanitize', default=False, action='store_true', help='Run the test suite with the sanitizer preloaded') class Test(BaseTest): description = 'Run the calibre test suite' def add_options(self, parser): super().add_options(parser) parser.add_option('--test-verbosity', type=int, default=4, help='Test verbosity (0-4)') parser.add_option('--test-module', '--test-group', default=[], action='append', type='choice', choices=sorted(map(str, TEST_MODULES)), help='The test module to run (can be specified more than once for multiple modules). Choices: %s' % ', '.join(sorted(TEST_MODULES))) parser.add_option('--test-name', '-n', default=[], action='append', help='The name of an individual test to run. Can be specified more than once for multiple tests. The name of the' ' test is the name of the test function without the leading test_. For example, the function test_something()' ' can be run by specifying the name "something".') parser.add_option('--exclude-test-module', default=[], action='append', type='choice', choices=sorted(map(str, TEST_MODULES)), help='A test module to be excluded from the test run (can be specified more than once for multiple modules).' ' Choices: %s' % ', '.join(sorted(TEST_MODULES))) parser.add_option('--exclude-test-name', default=[], action='append', help='The name of an individual test to be excluded from the test run. Can be specified more than once for multiple tests.') def run(self, opts): super().run(opts) # cgi is used by feedparser and possibly other dependencies import warnings warnings.filterwarnings('ignore', message="'cgi' is deprecated and slated for removal in Python 3.13") if is_ci and (SW := os.environ.get('SW')): if ismacos: import ctypes sys.libxml2_dylib = ctypes.CDLL(os.path.join(SW, 'lib', 'libxml2.dylib')) sys.libxslt_dylib = ctypes.CDLL(os.path.join(SW, 'lib', 'libxslt.dylib')) sys.libexslt_dylib = ctypes.CDLL(os.path.join(SW, 'lib', 'libexslt.dylib')) print(sys.libxml2_dylib, sys.libxslt_dylib, sys.libexslt_dylib, file=sys.stderr, flush=True) elif iswindows: ffmpeg_dll_dir = os.path.join(SW, 'ffmpeg', 'bin') os.add_dll_directory(ffmpeg_dll_dir) from calibre.utils.run_tests import filter_tests_by_name, find_tests, remove_tests_by_name, run_cli tests = find_tests(which_tests=frozenset(opts.test_module), exclude_tests=frozenset(opts.exclude_test_module)) if opts.test_name: tests = filter_tests_by_name(tests, *opts.test_name) if opts.exclude_test_name: tests = remove_tests_by_name(tests, *opts.exclude_test_name) run_cli(tests, verbosity=opts.test_verbosity, buffer=not opts.test_name) if is_ci: print('run_cli returned', flush=True) raise SystemExit(0) class TestRS(BaseTest): description = 'Run tests for RapydScript code' def add_options(self, parser): super().add_options(parser) def run(self, opts): super().run(opts) from calibre.utils.rapydscript import run_rapydscript_tests run_rapydscript_tests()
4,604
Python
.py
70
54.357143
158
0.637935
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,350
upload.py
kovidgoyal_calibre/setup/upload.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import glob import hashlib import json import os import shutil import stat import subprocess import sys import time from subprocess import check_call from tempfile import NamedTemporaryFile, gettempdir, mkdtemp from zipfile import ZipFile from polyglot.builtins import iteritems from polyglot.urllib import Request, urlopen if __name__ == '__main__': d = os.path.dirname sys.path.insert(0, d(d(os.path.abspath(__file__)))) from setup import Command, __appname__, __version__, installer_names DOWNLOADS = '/srv/main/downloads' HTML2LRF = "calibre/ebooks/lrf/html/demo" TXT2LRF = "src/calibre/ebooks/lrf/txt/demo" STAGING_HOST = 'download.calibre-ebook.com' BACKUP_HOST = 'code.calibre-ebook.com' STAGING_USER = BACKUP_USER = 'root' STAGING_DIR = '/root/staging' BACKUP_DIR = '/binaries' def installer_description(fname): if fname.endswith('.tar.xz'): return 'Source code' if fname.endswith('.txz'): return ('ARM' if 'arm64' in fname else 'AMD') + ' 64-bit Linux binary' if fname.endswith('.msi'): return 'Windows installer' if fname.endswith('.dmg'): return 'macOS dmg' if fname.endswith('.exe'): return 'Calibre Portable' return 'Unknown file' def upload_signatures(): tdir = mkdtemp() scp = ['scp'] try: for installer in installer_names(): if not os.path.exists(installer): continue sig = os.path.join(tdir, os.path.basename(installer + '.sig')) scp.append(sig) check_call([ os.environ['PENV'] + '/gpg-as-kovid', '--output', sig, '--detach-sig', installer ]) with open(installer, 'rb') as f: raw = f.read() fingerprint = hashlib.sha512(raw).hexdigest() sha512 = os.path.join(tdir, os.path.basename(installer + '.sha512')) with open(sha512, 'w') as f: f.write(fingerprint) scp.append(sha512) for srv in 'code main'.split(): check_call(scp + ['{0}:/srv/{0}/signatures/'.format(srv)]) check_call( ['ssh', srv, 'chown', '-R', 'http:http', '/srv/%s/signatures' % srv] ) finally: shutil.rmtree(tdir) class ReUpload(Command): # {{{ description = 'Re-upload any installers present in dist/' sub_commands = ['upload_installers'] def pre_sub_commands(self, opts): opts.replace = True exists = {x for x in installer_names() if os.path.exists(x)} if not exists: print('There appear to be no installers!') raise SystemExit(1) def run(self, opts): for x in installer_names(): if os.path.exists(x): os.remove(x) # }}} # Data {{{ def get_github_data(): with open(os.environ['PENV'] + '/github-token', 'rb') as f: un, pw = f.read().decode('utf-8').strip().split(':') return {'username': un, 'password': pw} def get_sourceforge_data(): return {'username': 'kovidgoyal', 'project': 'calibre'} def get_fosshub_data(): with open(os.environ['PENV'] + '/fosshub', 'rb') as f: return f.read().decode('utf-8').strip() def send_data(loc): subprocess.check_call([ 'rsync', '--inplace', '--delete', '-r', '-zz', '-h', '--info=progress2', '-e', 'ssh -x', loc + '/', f'{STAGING_USER}@{STAGING_HOST}:{STAGING_DIR}' ]) def send_to_backup(loc): host = f'{BACKUP_USER}@{BACKUP_HOST}' dest = f'{BACKUP_DIR}/{__version__}' subprocess.check_call(['ssh', '-x', host, 'mkdir', '-p', dest]) subprocess.check_call([ 'rsync', '--inplace', '--delete', '-r', '-zz', '-h', '--info=progress2', '-e', 'ssh -x', loc + '/', f'{host}:{dest}/' ]) def gh_cmdline(ver, data): return [ __appname__, ver, 'fmap', 'github', __appname__, data['username'], data['password'] ] def sf_cmdline(ver, sdata): return [ __appname__, ver, 'fmap', 'sourceforge', sdata['project'], sdata['username'] ] def calibre_cmdline(ver): return [__appname__, ver, 'fmap', 'calibre'] def run_remote_upload(args): print('Running remotely:', ' '.join(args)) subprocess.check_call([ 'ssh', '-x', f'{STAGING_USER}@{STAGING_HOST}', 'cd', STAGING_DIR, '&&', 'python', 'hosting.py' ] + args) # }}} def upload_to_fosshub(): # https://devzone.fosshub.com/dashboard/restApi # fosshub has no API to do partial uploads, so we always upload all files. api_key = get_fosshub_data() def request(path, data=None): r = Request('https://api.fosshub.com/rest/' + path.lstrip('/'), headers={ 'Content-Type': 'application/json', 'X-auth-key': api_key, 'User-Agent': 'calibre' }) res = urlopen(r, data=data) ans = json.loads(res.read()) if ans.get('error'): raise SystemExit(ans['error']) if res.getcode() != 200: raise SystemExit(f'Request to {path} failed with response code: {res.getcode()}') # from pprint import pprint # pprint(ans) return ans['status'] if 'status' in ans else ans['data'] print('Sending upload request to fosshub...') project_id = None for project in request('projects'): if project['name'].lower() == 'calibre': project_id = project['id'] break else: raise SystemExit('No calibre project found') files = set(installer_names()) entries = [] for fname in files: desc = installer_description(fname) url = 'https://download.calibre-ebook.com/{}/{}'.format( __version__, os.path.basename(fname) ) entries.append({ 'fileUrl': url, 'type': desc, 'version': __version__, }) jq = { 'version': __version__, 'files': entries, 'publish': True, 'isOldRelease': False, } data = json.dumps(jq) # print(data) data = data.encode('utf-8') if not request(f'projects/{project_id}/releases/', data=data): raise SystemExit('Failed to queue publish job with fosshub') class UploadInstallers(Command): # {{{ def add_options(self, parser): parser.add_option( '--replace', default=False, action='store_true', help='Replace existing installers' ) def run(self, opts): # return upload_to_fosshub() all_possible = set(installer_names()) available = set(glob.glob('dist/*')) files = { x: installer_description(x) for x in all_possible.intersection(available) } for x in files: os.chmod(x, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) sizes = {os.path.basename(x): os.path.getsize(x) for x in files} self.record_sizes(sizes) tdir = mkdtemp() try: self.upload_to_staging(tdir, files) self.upload_to_calibre() if opts.replace: upload_signatures() check_call('ssh code /apps/update-calibre-version.py'.split()) # self.upload_to_sourceforge() # upload_to_fosshub() self.upload_to_github(opts.replace) finally: shutil.rmtree(tdir, ignore_errors=True) def record_sizes(self, sizes): print('\nRecording dist sizes') args = [ f'{__version__}:{fname}:{size}' for fname, size in iteritems(sizes) ] check_call(['ssh', 'code', '/usr/local/bin/dist_sizes'] + args) def upload_to_staging(self, tdir, files): os.mkdir(tdir + '/dist') hosting = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'hosting.py' ) shutil.copyfile(hosting, os.path.join(tdir, 'hosting.py')) for f in files: for x in (tdir + '/dist',): dest = os.path.join(x, os.path.basename(f)) shutil.copy2(f, x) os.chmod( dest, stat.S_IREAD | stat.S_IWRITE | stat.S_IRGRP | stat.S_IROTH ) with open(os.path.join(tdir, 'fmap'), 'wb') as fo: for f, desc in iteritems(files): fo.write((f'{f}: {desc}\n').encode()) while True: try: send_data(tdir) except: print('\nUpload to staging failed, retrying in a minute') time.sleep(60) else: break while True: try: send_to_backup(tdir) except: print('\nUpload to backup failed, retrying in a minute') time.sleep(60) else: break def upload_to_github(self, replace): data = get_github_data() args = gh_cmdline(__version__, data) if replace: args = ['--replace'] + args run_remote_upload(args) def upload_to_sourceforge(self): sdata = get_sourceforge_data() args = sf_cmdline(__version__, sdata) run_remote_upload(args) def upload_to_calibre(self): run_remote_upload(calibre_cmdline(__version__)) # }}} class UploadUserManual(Command): # {{{ description = 'Build and upload the User Manual' sub_commands = ['manual'] def build_plugin_example(self, path): from calibre import CurrentDir with NamedTemporaryFile(suffix='.zip') as f: os.fchmod( f.fileno(), stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWRITE ) with CurrentDir(path): with ZipFile(f, 'w') as zf: for x in os.listdir('.'): if x.endswith('.swp'): continue zf.write(x) if os.path.isdir(x): for y in os.listdir(x): zf.write(os.path.join(x, y)) bname = self.b(path) + '_plugin.zip' dest = f'{DOWNLOADS}/{bname}' subprocess.check_call(['scp', f.name, 'main:' + dest]) def run(self, opts): path = self.j(self.SRC, '..', 'manual', 'plugin_examples') for x in glob.glob(self.j(path, '*')): self.build_plugin_example(x) srcdir = self.j(gettempdir(), 'user-manual-build', 'en', 'html') + '/' check_call( ' '.join( ['rsync', '-zz', '-rl', '--info=progress2', srcdir, 'main:/srv/manual/'] ), shell=True ) check_call('ssh main chown -R http:http /srv/manual'.split()) # }}} class UploadDemo(Command): # {{{ description = 'Rebuild and upload various demos' def run(self, opts): check_call( '''ebook-convert %s/demo.html /tmp/html2lrf.lrf ''' '''--title='Demonstration of html2lrf' --authors='Kovid Goyal' ''' '''--header ''' '''--serif-family "/usr/share/fonts/corefonts, Times New Roman" ''' '''--mono-family "/usr/share/fonts/corefonts, Andale Mono" ''' '''''' % self.j(self.SRC, HTML2LRF), shell=True ) lrf = self.j(self.SRC, 'calibre', 'ebooks', 'lrf', 'html', 'demo') check_call( 'cd %s && zip -j /tmp/html-demo.zip * /tmp/html2lrf.lrf' % lrf, shell=True ) check_call(f'scp /tmp/html-demo.zip main:{DOWNLOADS}/', shell=True) # }}} class UploadToServer(Command): # {{{ description = 'Upload miscellaneous data to calibre server' def run(self, opts): check_call('scp translations/website/locales.zip main:/srv/main/'.split()) check_call('scp translations/changelog/locales.zip main:/srv/main/changelog-locales.zip'.split()) check_call('ssh main /apps/static/generate.py'.split()) src_file = glob.glob('dist/calibre-*.tar.xz')[0] upload_signatures() check_call(['git', 'push']) check_call([ os.environ['PENV'] + '/gpg-as-kovid', '--armor', '--yes', '--detach-sign', src_file ]) check_call(['scp', src_file + '.asc', 'code:/srv/code/signatures/']) check_call('ssh code /usr/local/bin/update-calibre-code.py'.split()) check_call( ('ssh code /apps/update-calibre-version.py ' + __version__).split() ) check_call(( 'ssh main /usr/local/bin/update-calibre-version.py %s && /usr/local/bin/update-calibre-code.py && /apps/static/generate.py' % __version__ ).split()) # }}}
12,941
Python
.py
336
29.27381
135
0.555174
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,351
plugins_mirror.py
kovidgoyal_calibre/setup/plugins_mirror.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net> # Imports {{{ import argparse import ast import atexit import bz2 import errno import glob import gzip import io import json import os import random import re import socket import stat import subprocess import sys import tempfile import time import zipfile import zlib from collections import namedtuple from contextlib import closing from datetime import datetime from email.utils import parsedate from functools import partial from multiprocessing.pool import ThreadPool from xml.sax.saxutils import escape, quoteattr try: from html import unescape as u except ImportError: from HTMLParser import HTMLParser u = HTMLParser().unescape try: from urllib.parse import parse_qs, urlparse except ImportError: from urlparse import parse_qs, urlparse try: from urllib.error import URLError from urllib.request import Request, build_opener, urlopen except Exception: from urllib2 import Request, URLError, build_opener, urlopen # }}} USER_AGENT = 'calibre mirror' MR_URL = 'https://www.mobileread.com/forums/' IS_PRODUCTION = os.path.exists('/srv/plugins') PLUGINS = 'plugins.json.bz2' INDEX = MR_URL + 'showpost.php?p=1362767&postcount=1' # INDEX = 'file:///t/raw.html' IndexEntry = namedtuple('IndexEntry', 'name url donate history uninstall deprecated thread_id') socket.setdefaulttimeout(30) def read(url, get_info=False): # {{{ if url.startswith("file://"): return urlopen(url).read() opener = build_opener() opener.addheaders = [ ('User-Agent', USER_AGENT), ('Accept-Encoding', 'gzip,deflate'), ] # Sporadic network failures in rackspace, so retry with random sleeps for i in range(10): try: res = opener.open(url) break except URLError as e: if not isinstance(e.reason, socket.timeout) or i == 9: raise time.sleep(random.randint(10, 45)) info = res.info() encoding = info.get('Content-Encoding') raw = res.read() res.close() if encoding and encoding.lower() in {'gzip', 'x-gzip', 'deflate'}: if encoding.lower() == 'deflate': raw = zlib.decompress(raw) else: raw = gzip.GzipFile(fileobj=io.BytesIO(raw)).read() if get_info: return raw, info return raw # }}} def url_to_plugin_id(url, deprecated): query = parse_qs(urlparse(url).query) ans = (query['t'] if 't' in query else query['p'])[0] if deprecated: ans += '-deprecated' return ans def parse_index(raw=None): # {{{ raw = raw or read(INDEX).decode('utf-8', 'replace') dep_start = raw.index('>Deprecated/Renamed/Retired Plugins:<') dpat = re.compile(r'''(?is)Donate\s*:\s*<a\s+href=['"](.+?)['"]''') key_pat = re.compile(r'''(?is)(History|Uninstall)\s*:\s*([^<;]+)[<;]''') seen = {} for match in re.finditer(r'''(?is)<li.+?<a\s+href=['"](https://www.mobileread.com/forums/showthread.php\?[pt]=\d+).+?>(.+?)<(.+?)</li>''', raw): deprecated = match.start() > dep_start donate = uninstall = None history = False name, url, rest = u(match.group(2)), u(match.group(1)), match.group(3) m = dpat.search(rest) if m is not None: donate = u(m.group(1)) for m in key_pat.finditer(rest): k = m.group(1).lower() if k == 'history' and m.group(2).strip().lower() in {'yes', 'true'}: history = True elif k == 'uninstall': uninstall = tuple(x.strip() for x in m.group(2).strip().split(',')) thread_id = url_to_plugin_id(url, deprecated) if thread_id in seen: raise ValueError(f'thread_id for {seen[thread_id]} and {name} is the same: {thread_id}') seen[thread_id] = name entry = IndexEntry(name, url, donate, history, uninstall, deprecated, thread_id) yield entry # }}} def parse_plugin_zip_url(raw): for m in re.finditer(r'''(?is)<a\s+href=['"](attachment.php\?[^'"]+?)['"][^>]*>([^<>]+?\.zip)\s*<''', raw): url, name = u(m.group(1)), u(m.group(2).strip()) if name.lower().endswith('.zip'): return MR_URL + url, name return None, None def load_plugins_index(): try: with open(PLUGINS, 'rb') as f: raw = f.read() except OSError as err: if err.errno == errno.ENOENT: return {} raise return json.loads(bz2.decompress(raw)) # Get metadata from plugin zip file {{{ def convert_node(fields, x, names={}, import_data=None): name = x.__class__.__name__ def conv(x): return convert_node(fields, x, names=names, import_data=import_data) if name == 'Str': return x.s.decode('utf-8') if isinstance(x.s, bytes) else x.s elif name == 'Num': return x.n elif name == 'Constant': return x.value elif name in {'Set', 'List', 'Tuple'}: func = {'Set':set, 'List':list, 'Tuple':tuple}[name] return func(list(map(conv, x.elts))) elif name == 'Dict': keys, values = list(map(conv, x.keys)), list(map(conv, x.values)) return dict(zip(keys, values)) elif name == 'Call': if len(x.args) != 1 and len(x.keywords) != 0: raise TypeError(f'Unsupported function call for fields: {fields}') return tuple(map(conv, x.args))[0] elif name == 'Name': if x.id not in names: if import_data is not None and x.id in import_data[0]: return get_import_data(x.id, import_data[0][x.id], *import_data[1:]) raise ValueError(f'Could not find name {x.id} for fields: {fields}') return names[x.id] elif name == 'BinOp': if x.right.__class__.__name__ == 'Str': return x.right.s.decode('utf-8') if isinstance(x.right.s, bytes) else x.right.s if x.right.__class__.__name__ == 'Constant' and isinstance(x.right.value, str): return x.right.value elif name == 'Attribute': return conv(getattr(conv(x.value), x.attr)) raise TypeError(f'Unknown datatype {x} for fields: {fields}') Alias = namedtuple('Alias', 'name asname') class Module: pass def get_import_data(name, mod, zf, names): mod = mod.split('.') if mod[0] == 'calibre_plugins': mod = mod[2:] is_module_import = not mod if is_module_import: mod = [name] mod = '/'.join(mod) + '.py' if mod in names: raw = zf.open(names[mod]).read() module = ast.parse(raw, filename='__init__.py') top_level_assigments = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'Assign'] module = Module() for node in top_level_assigments: targets = {getattr(t, 'id', None) for t in node.targets} targets.discard(None) for x in targets: if is_module_import: setattr(module, x, node.value) elif x == name: return convert_node({x}, node.value) if is_module_import: return module raise ValueError(f'Failed to find name: {name!r} in module: {mod!r}') else: raise ValueError('Failed to find module: %r' % mod) def parse_metadata(raw, namelist, zf): module = ast.parse(raw, filename='__init__.py') top_level_imports = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'ImportFrom'] top_level_classes = tuple(x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'ClassDef') top_level_assigments = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'Assign'] defaults = { 'name':'', 'description':'', 'supported_platforms':['windows', 'osx', 'linux'], 'version':(1, 0, 0), 'author':'Unknown', 'minimum_calibre_version':(0, 9, 42) } field_names = set(defaults) imported_names = {} plugin_import_found = set() all_imports = [] for node in top_level_imports: names = getattr(node, 'names', []) mod = getattr(node, 'module', None) if names and mod: names = [Alias(n.name, getattr(n, 'asname', None)) for n in names] if mod in { 'calibre.customize', 'calibre.customize.conversion', 'calibre.ebooks.metadata.sources.base', 'calibre.ebooks.metadata.sources.amazon', 'calibre.ebooks.metadata.covers', 'calibre.devices.interface', 'calibre.ebooks.metadata.fetch', 'calibre.customize.builtins', } or re.match(r'calibre\.devices\.[a-z0-9]+\.driver', mod) is not None: inames = {n.asname or n.name for n in names} inames = {x for x in inames if x.lower() != x} plugin_import_found |= inames else: all_imports.append((mod, [n.name for n in names])) imported_names[names[-1].asname or names[-1].name] = mod if not plugin_import_found: return all_imports import_data = (imported_names, zf, namelist) names = {} for node in top_level_assigments: targets = {getattr(t, 'id', None) for t in node.targets} targets.discard(None) for x in targets - field_names: try: val = convert_node({x}, node.value, import_data=import_data) except Exception: pass else: names[x] = val def parse_class(node): class_assigments = [x for x in ast.iter_child_nodes(node) if x.__class__.__name__ == 'Assign'] found = {} for node in class_assigments: targets = {getattr(t, 'id', None) for t in node.targets} targets.discard(None) fields = field_names.intersection(targets) if fields: val = convert_node(fields, node.value, names=names, import_data=import_data) for field in fields: found[field] = val return found if top_level_classes: for node in top_level_classes: bases = {getattr(x, 'id', None) for x in node.bases} if not bases.intersection(plugin_import_found): continue found = parse_class(node) if 'name' in found and 'author' in found: defaults.update(found) return defaults for node in top_level_classes: found = parse_class(node) if 'name' in found and 'author' in found and 'version' in found: defaults.update(found) return defaults raise ValueError('Could not find plugin class') def parse_plugin(raw, names, zf): ans = parse_metadata(raw, names, zf) if isinstance(ans, dict): return ans # The plugin is importing its base class from somewhere else, le sigh for mod, _ in ans: mod = mod.split('.') if mod[0] == 'calibre_plugins': mod = mod[2:] mod = '/'.join(mod) + '.py' if mod in names: raw = zf.open(names[mod]).read() ans = parse_metadata(raw, names, zf) if isinstance(ans, dict): return ans raise ValueError('Failed to find plugin class') def get_plugin_init(zf): metadata = None names = {x.decode('utf-8') if isinstance(x, bytes) else x : x for x in zf.namelist()} inits = [x for x in names if x.rpartition('/')[-1] == '__init__.py'] inits.sort(key=lambda x:x.count('/')) if inits and inits[0] == '__init__.py': metadata = names[inits[0]] else: # Legacy plugin for name, val in names.items(): if name.endswith('plugin.py'): metadata = val break if metadata is None: raise ValueError('No __init__.py found in plugin') return zf.open(metadata).read(), names def get_plugin_info(raw_zip): with zipfile.ZipFile(io.BytesIO(raw_zip)) as zf: raw, names = get_plugin_init(zf) try: return parse_plugin(raw, names, zf) except (SyntaxError, TabError, IndentationError): with tempfile.NamedTemporaryFile(suffix='.zip') as f: f.write(raw_zip) f.flush() res = subprocess.run(['python2', __file__, f.name], stdout=subprocess.PIPE) if res.returncode == 0: return json.loads(res.stdout) raise # }}} def update_plugin_from_entry(plugin, entry): plugin['index_name'] = entry.name plugin['thread_url'] = entry.url for x in ('donate', 'history', 'deprecated', 'uninstall', 'thread_id'): plugin[x] = getattr(entry, x) def fetch_plugin(old_index, entry): lm_map = {plugin['thread_id']:plugin for plugin in old_index.values()} raw = read(entry.url).decode('utf-8', 'replace') url, name = parse_plugin_zip_url(raw) if url is None: raise ValueError('Failed to find zip file URL for entry: %s' % repr(entry)) plugin = lm_map.get(entry.thread_id, None) if plugin is not None: # Previously downloaded plugin lm = datetime(*tuple(map(int, re.split(r'\D', plugin['last_modified'])))[:6]) request = Request(url) request.get_method = lambda : 'HEAD' with closing(urlopen(request)) as response: info = response.info() slm = datetime(*parsedate(info.get('Last-Modified'))[:6]) if lm >= slm: # The previously downloaded plugin zip file is up-to-date update_plugin_from_entry(plugin, entry) return plugin raw, info = read(url, get_info=True) slm = datetime(*parsedate(info.get('Last-Modified'))[:6]) plugin = get_plugin_info(raw) plugin['last_modified'] = slm.isoformat() plugin['file'] = 'staging_%s.zip' % entry.thread_id plugin['size'] = len(raw) plugin['original_url'] = url update_plugin_from_entry(plugin, entry) with open(plugin['file'], 'wb') as f: f.write(raw) return plugin def parallel_fetch(old_index, entry): try: return fetch_plugin(old_index, entry) except Exception: import traceback return traceback.format_exc() def log(*args, **kwargs): print(*args, **kwargs) with open('log', 'a') as f: kwargs['file'] = f print(*args, **kwargs) def atomic_write(raw, name): with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f: f.write(raw) os.fchmod(f.fileno(), stat.S_IREAD|stat.S_IWRITE|stat.S_IRGRP|stat.S_IROTH) os.rename(f.name, name) def fetch_plugins(old_index): ans = {} pool = ThreadPool(processes=10) entries = tuple(parse_index()) if not entries: raise SystemExit('Could not find any plugins, probably the markup on the MR index page has changed') with closing(pool): result = pool.map(partial(parallel_fetch, old_index), entries) for entry, plugin in zip(entries, result): if isinstance(plugin, dict): ans[entry.name] = plugin else: if entry.name in old_index: ans[entry.name] = old_index[entry.name] log('Failed to get plugin', entry.name, 'at', datetime.now().isoformat(), 'with error:') log(plugin) # Move staged files for plugin in ans.values(): if plugin['file'].startswith('staging_'): src = plugin['file'] plugin['file'] = src.partition('_')[-1] os.rename(src, plugin['file']) raw = bz2.compress(json.dumps(ans, sort_keys=True, indent=4, separators=(',', ': ')).encode('utf-8')) atomic_write(raw, PLUGINS) # Cleanup any extra .zip files all_plugin_files = {p['file'] for p in ans.values()} extra = set(glob.glob('*.zip')) - all_plugin_files for x in extra: os.unlink(x) return ans def plugin_to_index(plugin, count): title = '<h3><img src="plugin-icon.png"><a href={} title="Plugin forum thread">{}</a></h3>'.format( # noqa quoteattr(plugin['thread_url']), escape(plugin['name'])) released = datetime(*tuple(map(int, re.split(r'\D', plugin['last_modified'])))[:6]).strftime('%e %b, %Y').lstrip() details = [ 'Version: <b>%s</b>' % escape('.'.join(map(str, plugin['version']))), 'Released: <b>%s</b>' % escape(released), 'Author: %s' % escape(plugin['author']), 'calibre: %s' % escape('.'.join(map(str, plugin['minimum_calibre_version']))), 'Platforms: %s' % escape(', '.join(sorted(plugin['supported_platforms']) or ['all'])), ] if plugin['uninstall']: details.append('Uninstall: %s' % escape(', '.join(plugin['uninstall']))) if plugin['donate']: details.append('<a href=%s title="Donate">Donate</a>' % quoteattr(plugin['donate'])) block = [] for li in details: if li.startswith('calibre:'): block.append('<br>') block.append('<li>%s</li>' % li) block = '<ul>%s</ul>' % ('\n'.join(block)) downloads = ('\xa0<span class="download-count">[%d total downloads]</span>' % count) if count else '' zipfile = '<div class="end"><a href={} title="Download plugin" download={}>Download plugin \u2193</a>{}</div>'.format( quoteattr(plugin['file']), quoteattr(plugin['name'] + '.zip'), downloads) desc = plugin['description'] or '' if desc: desc = '<p>%s</p>' % desc return f'{title}\n{desc}\n{block}\n{zipfile}\n\n' def create_index(index, raw_stats): plugins = [] stats = {} for name in sorted(index): plugin = index[name] if not plugin['deprecated']: count = raw_stats.get(plugin['file'].rpartition('.')[0], 0) if count > 0: stats[plugin['name']] = count plugins.append( plugin_to_index(plugin, count)) index = '''\ <!DOCTYPE html> <html> <head><meta charset="utf-8"><title>Index of calibre plugins</title> <link rel="icon" type="image/x-icon" href="//calibre-ebook.com/favicon.ico" /> <style type="text/css"> body { background-color: #eee; } a { text-decoration: none } a:hover, h3:hover { color: red } a:visited { color: blue } ul { list-style-type: none; font-size: smaller } li { display: inline } li+li:before { content: " - " } .end { border-bottom: solid 1pt black; padding-bottom: 0.5ex; margin-bottom: 4ex; } h1 img, h3 img { vertical-align: middle; margin-right: 0.5em; } h1 { text-align: center } .download-count { color: gray; font-size: smaller } </style> </head> <body> <h1><img src="//manual.calibre-ebook.com/_static/logo.png">Index of calibre plugins</h1> <div style="text-align:center"><a href="stats.html">Download counts for all plugins</a></div> %s </body> </html>''' % ('\n'.join(plugins)) raw = index.encode('utf-8') try: with open('index.html', 'rb') as f: oraw = f.read() except OSError: oraw = None if raw != oraw: atomic_write(raw, 'index.html') def plugin_stats(x): name, count = x return f'<tr><td>{escape(name)}</td><td>{count}</td></tr>\n' pstats = list(map(plugin_stats, sorted(stats.items(), reverse=True, key=lambda x:x[1]))) stats = '''\ <!DOCTYPE html> <html> <head><meta charset="utf-8"><title>Stats for calibre plugins</title> <link rel="icon" type="image/x-icon" href="//calibre-ebook.com/favicon.ico" /> <style type="text/css"> body { background-color: #eee; } h1 img, h3 img { vertical-align: middle; margin-right: 0.5em; } h1 { text-align: center } </style> </head> <body> <h1><img src="//manual.calibre-ebook.com/_static/logo.png">Stats for calibre plugins</h1> <table> <tr><th>Plugin</th><th>Total downloads</th></tr> %s </table> </body> </html> ''' % ('\n'.join(pstats)) raw = stats.encode('utf-8') try: with open('stats.html', 'rb') as f: oraw = f.read() except OSError: oraw = None if raw != oraw: atomic_write(raw, 'stats.html') _singleinstance = None def singleinstance(): global _singleinstance s = _singleinstance = socket.socket(socket.AF_UNIX) try: s.bind(b'\0calibre-plugins-mirror-singleinstance') except OSError as err: if getattr(err, 'errno', None) == errno.EADDRINUSE: return False raise return True def update_stats(): log = olog = 'stats.log' if not os.path.exists(log): return {} stats = {} if IS_PRODUCTION: try: with open('stats.json', 'rb') as f: stats = json.load(f) except OSError as err: if err.errno != errno.ENOENT: raise if os.geteuid() != 0: return stats log = 'rotated-' + log os.rename(olog, log) subprocess.check_call(['/usr/sbin/nginx', '-s', 'reopen']) atexit.register(os.remove, log) pat = re.compile(br'GET /(\d+)(?:-deprecated){0,1}\.zip') for line in open(log, 'rb'): m = pat.search(line) if m is not None: plugin = m.group(1).decode('utf-8') stats[plugin] = stats.get(plugin, 0) + 1 data = json.dumps(stats, indent=2) if not isinstance(data, bytes): data = data.encode('utf-8') with open('stats.json', 'wb') as f: f.write(data) return stats def parse_single_plugin(zipfile_path): with zipfile.ZipFile(zipfile_path) as zf: raw, names = get_plugin_init(zf) ans = parse_plugin(raw, names, zf) sys.stdout.write(json.dumps(ans, ensure_ascii=True)) def main(): p = argparse.ArgumentParser( description='Mirror calibre plugins from the forums. Or parse a single plugin zip file' ' if specified on the command line' ) p.add_argument('plugin_path', nargs='?', default='', help='Path to plugin zip file to parse') WORKDIR = '/srv/plugins' if IS_PRODUCTION else '/t/plugins' p.add_argument('-o', '--output-dir', default=WORKDIR, help='Where to place the mirrored plugins. Default is: ' + WORKDIR) args = p.parse_args() if args.plugin_path: return parse_single_plugin(args.plugin_path) os.makedirs(args.output_dir, exist_ok=True) os.chdir(args.output_dir) if os.geteuid() == 0 and not singleinstance(): print('Another instance of plugins-mirror is running', file=sys.stderr) raise SystemExit(1) open('log', 'w').close() stats = update_stats() try: plugins_index = load_plugins_index() plugins_index = fetch_plugins(plugins_index) create_index(plugins_index, stats) except KeyboardInterrupt: raise SystemExit('Exiting on user interrupt') except Exception: import traceback log('Failed to run at:', datetime.now().isoformat()) log(traceback.format_exc()) raise SystemExit(1) def test_parse(): # {{{ raw = read(INDEX).decode('utf-8', 'replace') old_entries = [] from lxml import html root = html.fromstring(raw) list_nodes = root.xpath('//div[@id="post_message_1362767"]/ul/li') # Add our deprecated plugins which are nested in a grey span list_nodes.extend(root.xpath('//div[@id="post_message_1362767"]/span/ul/li')) for list_node in list_nodes: name = list_node.xpath('a')[0].text_content().strip() url = list_node.xpath('a/@href')[0].strip() description_text = list_node.xpath('i')[0].text_content() description_parts = description_text.partition('Version:') details_text = description_parts[1] + description_parts[2].replace('\r\n','') details_pairs = details_text.split(';') details = {} for details_pair in details_pairs: pair = details_pair.split(':') if len(pair) == 2: key = pair[0].strip().lower() value = pair[1].strip() details[key] = value donation_node = list_node.xpath('i/span/a/@href') donate = donation_node[0] if donation_node else None uninstall = tuple(x.strip() for x in details.get('uninstall', '').strip().split(',') if x.strip()) or None history = details.get('history', 'No').lower() in ['yes', 'true'] deprecated = details.get('deprecated', 'No').lower() in ['yes', 'true'] old_entries.append(IndexEntry(name, url, donate, history, uninstall, deprecated, url_to_plugin_id(url, deprecated))) new_entries = tuple(parse_index(raw)) for i, entry in enumerate(old_entries): if entry != new_entries[i]: print(f'The new entry: {new_entries[i]} != {entry}') raise SystemExit(1) pool = ThreadPool(processes=20) urls = [e.url for e in new_entries] data = pool.map(read, urls) for url, raw in zip(urls, data): sys.stdout.flush() root = html.fromstring(raw) attachment_nodes = root.xpath('//fieldset/table/tr/td/a') full_url = None for attachment_node in attachment_nodes: filename = attachment_node.text_content().lower() if filename.find('.zip') != -1: full_url = MR_URL + attachment_node.attrib['href'] break new_url, aname = parse_plugin_zip_url(raw) if new_url != full_url: print(f'new url ({aname}): {new_url} != {full_url} for plugin at: {url}') raise SystemExit(1) # }}} def test_parse_metadata(): # {{{ raw = b'''\ import os from calibre.customize import FileTypePlugin MV = (0, 7, 53) class HelloWorld(FileTypePlugin): name = _('name') # Name of the plugin description = {1, 2} supported_platforms = ['windows', 'osx', 'linux'] # Platforms this plugin will run on author = u'Acme Inc.' # The author of this plugin version = {1:'a', 'b':2} file_types = set(['epub', 'mobi']) # The file types that this plugin will be applied to on_postprocess = True # Run this plugin after conversion is complete minimum_calibre_version = MV ''' vals = { 'name':'name', 'description':{1, 2}, 'supported_platforms':['windows', 'osx', 'linux'], 'author':'Acme Inc.', 'version':{1:'a', 'b':2}, 'minimum_calibre_version':(0, 7, 53)} assert parse_metadata(raw, None, None) == vals buf = io.BytesIO() with zipfile.ZipFile(buf, 'w') as zf: zf.writestr('very/lovely.py', raw.replace(b'MV = (0, 7, 53)', b'from very.ver import MV')) zf.writestr('very/ver.py', b'MV = (0, 7, 53)') zf.writestr('__init__.py', b'from xxx import yyy\nfrom very.lovely import HelloWorld') assert get_plugin_info(buf.getvalue()) == vals # }}} if __name__ == '__main__': # test_parse_metadata() # import pprint # pprint.pprint(get_plugin_info(open(sys.argv[-1], 'rb').read())) main()
26,900
Python
.py
658
33.545593
148
0.600658
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,352
gui.py
kovidgoyal_calibre/setup/gui.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from contextlib import suppress from setup import Command, __appname__ class GUI(Command): description = 'Compile all GUI forms' PATH = os.path.join(Command.SRC, __appname__, 'gui2') QRC = os.path.join(Command.RESOURCES, 'images.qrc') RCC = os.path.join(Command.RESOURCES, 'icons.rcc') def add_options(self, parser): parser.add_option('--summary', default=False, action='store_true', help='Only display a summary about how many files were compiled') def find_forms(self): # We do not use the calibre function find_forms as # importing calibre.gui2 may not work forms = [] for root, _, files in os.walk(self.PATH): for name in files: path = os.path.abspath(os.path.join(root, name)) if name.endswith('.ui'): forms.append(path) elif name.endswith('_ui.py') or name.endswith('_ui.pyc'): fname = path.rpartition('_')[0] + '.ui' if not os.path.exists(fname): os.remove(path) return forms @classmethod def form_to_compiled_form(cls, form): # We do not use the calibre function form_to_compiled_form as # importing calibre.gui2 may not work return form.rpartition('.')[0]+'_ui.py' def run(self, opts): self.build_forms(summary=opts.summary) self.build_images() def build_images(self): cwd = os.getcwd() try: os.chdir(self.RESOURCES) sources, files = [], [] for root, _, files2 in os.walk('images'): for name in files2: sources.append(os.path.join(root, name)) if self.newer(self.RCC, sources): self.info('Creating icon theme resource file') from calibre.utils.rcc import compile_icon_dir_as_themes compile_icon_dir_as_themes('images', self.RCC) if self.newer(self.QRC, sources): self.info('Creating images.qrc') for s in sources: files.append('<file>%s</file>'%s) manifest = '<RCC>\n<qresource prefix="/">\n%s\n</qresource>\n</RCC>'%'\n'.join(sorted(files)) if not isinstance(manifest, bytes): manifest = manifest.encode('utf-8') with open('images.qrc', 'wb') as f: f.write(manifest) finally: os.chdir(cwd) def build_forms(self, summary=False): from calibre.build_forms import build_forms build_forms(self.SRC, info=self.info, summary=summary, check_icons=False) def clean(self): forms = self.find_forms() for form in forms: c = self.form_to_compiled_form(form) if os.path.exists(c): os.remove(c) for x in (self.QRC, self.RCC): with suppress(FileNotFoundError): os.remove(x)
3,160
Python
.py
72
32.652778
109
0.570081
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,353
polib.py
kovidgoyal_calibre/setup/polib.py
# -* coding: utf-8 -*- # # License: MIT (see LICENSE file provided) # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: """ **polib** allows you to manipulate, create, modify gettext files (pot, po and mo files). You can load existing files, iterate through it's entries, add, modify entries, comments or metadata, etc. or create new po files from scratch. **polib** provides a simple and pythonic API via the :func:`~polib.pofile` and :func:`~polib.mofile` convenience functions. """ import array import codecs import os import re import struct import sys import textwrap import io __author__ = 'David Jean Louis <izimobil@gmail.com>' __version__ = '1.2.0' __all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry', 'default_encoding', 'escape', 'unescape', 'detect_encoding', ] # the default encoding to use when encoding cannot be detected default_encoding = 'utf-8' # python 2/3 compatibility helpers {{{ if sys.version_info < (3,): PY3 = False text_type = unicode def b(s): return s def u(s): return unicode(s, "unicode_escape") else: PY3 = True text_type = str def b(s): return s.encode("latin-1") def u(s): return s # }}} # _pofile_or_mofile {{{ def _pofile_or_mofile(f, type, **kwargs): """ Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to honor the DRY concept. """ # get the file encoding enc = kwargs.get('encoding') if enc is None: enc = detect_encoding(f, type == 'mofile') # parse the file kls = type == 'pofile' and _POFileParser or _MOFileParser parser = kls( f, encoding=enc, check_for_duplicates=kwargs.get('check_for_duplicates', False), klass=kwargs.get('klass') ) instance = parser.parse() instance.wrapwidth = kwargs.get('wrapwidth', 78) return instance # }}} # _is_file {{{ def _is_file(filename_or_contents): """ Safely returns the value of os.path.exists(filename_or_contents). Arguments: ``filename_or_contents`` either a filename, or a string holding the contents of some file. In the latter case, this function will always return False. """ try: return os.path.isfile(filename_or_contents) except (TypeError, ValueError, UnicodeEncodeError): return False # }}} # function pofile() {{{ def pofile(pofile, **kwargs): """ Convenience function that parses the po or pot file ``pofile`` and returns a :class:`~polib.POFile` instance. Arguments: ``pofile`` string, full or relative path to the po/pot file or its content (data). ``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext (optional, default: ``78``). ``encoding`` string, the encoding to use (e.g. "utf-8") (default: ``None``, the encoding will be auto-detected). ``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). ``klass`` class which is used to instantiate the return value (optional, default: ``None``, the return value with be a :class:`~polib.POFile` instance). """ return _pofile_or_mofile(pofile, 'pofile', **kwargs) # }}} # function mofile() {{{ def mofile(mofile, **kwargs): """ Convenience function that parses the mo file ``mofile`` and returns a :class:`~polib.MOFile` instance. Arguments: ``mofile`` string, full or relative path to the mo file or its content (string or bytes). ``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext to generate the po file that was used to format the mo file (optional, default: ``78``). ``encoding`` string, the encoding to use (e.g. "utf-8") (default: ``None``, the encoding will be auto-detected). ``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). ``klass`` class which is used to instantiate the return value (optional, default: ``None``, the return value with be a :class:`~polib.POFile` instance). """ return _pofile_or_mofile(mofile, 'mofile', **kwargs) # }}} # function detect_encoding() {{{ def detect_encoding(file, binary_mode=False): """ Try to detect the encoding used by the ``file``. The ``file`` argument can be a PO or MO file path or a string containing the contents of the file. If the encoding cannot be detected, the function will return the value of ``default_encoding``. Arguments: ``file`` string, full or relative path to the po/mo file or its content. ``binary_mode`` boolean, set this to True if ``file`` is a mo file. """ PATTERN = r'"?Content-Type:.+? charset=([\w_\-:\.]+)' rxt = re.compile(u(PATTERN)) rxb = re.compile(b(PATTERN)) def charset_exists(charset): """Check whether ``charset`` is valid or not.""" try: codecs.lookup(charset) except LookupError: return False return True if not _is_file(file): try: match = rxt.search(file) except TypeError: match = rxb.search(file) if match: enc = match.group(1).strip() if not isinstance(enc, text_type): enc = enc.decode('utf-8') if charset_exists(enc): return enc else: # For PY3, always treat as binary if binary_mode or PY3: mode = 'rb' rx = rxb else: mode = 'r' rx = rxt with open(file, mode) as f: for line in f.readlines(): match = rx.search(line) if match: f.close() enc = match.group(1).strip() if not isinstance(enc, text_type): enc = enc.decode('utf-8') if charset_exists(enc): return enc return default_encoding # }}} # function escape() {{{ def escape(st): """ Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r``, ``\\v``, ``\\b``, ``\\f`` and ``"`` in the given string ``st`` and returns it. """ return st.replace('\\', r'\\')\ .replace('\t', r'\t')\ .replace('\r', r'\r')\ .replace('\n', r'\n')\ .replace('\v', r'\v')\ .replace('\b', r'\b')\ .replace('\f', r'\f')\ .replace('\"', r'\"') # }}} # function unescape() {{{ def unescape(st): """ Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r``, ``\\v``, ``\\b``, ``\\f`` and ``"`` in the given string ``st`` and returns it. """ def unescape_repl(m): m = m.group(1) if m == 'n': return '\n' if m == 't': return '\t' if m == 'r': return '\r' if m == 'v': return '\v' if m == 'b': return '\b' if m == 'f': return '\f' if m == '\\': return '\\' return m # handles escaped double quote return re.sub(r'\\(\\|n|t|r|v|b|f|")', unescape_repl, st) # }}} # function natural_sort() {{{ def natural_sort(lst): """ Sort naturally the given list. Credits: http://stackoverflow.com/a/4836734 """ def convert(text): return int(text) if text.isdigit() else text.lower() def alphanum_key(key): return [convert(c) for c in re.split('([0-9]+)', key)] return sorted(lst, key=alphanum_key) # }}} # class _BaseFile {{{ class _BaseFile(list): """ Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile` classes. This class should **not** be instantiated directly. """ def __init__(self, *args, **kwargs): """ Constructor, accepts the following keyword arguments: ``pofile`` string, the path to the po or mo file, or its content as a string. ``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext (optional, default: ``78``). ``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional). ``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file, (optional, default: ``False``). """ list.__init__(self) # the opened file handle pofile = kwargs.get('pofile', None) if pofile and _is_file(pofile): self.fpath = pofile else: self.fpath = kwargs.get('fpath') # the width at which lines should be wrapped self.wrapwidth = kwargs.get('wrapwidth', 78) # the file encoding self.encoding = kwargs.get('encoding', default_encoding) # whether to check for duplicate entries or not self.check_for_duplicates = kwargs.get('check_for_duplicates', False) # header self.header = '' # both po and mo files have metadata self.metadata = {} self.metadata_is_fuzzy = 0 def __unicode__(self): """ Returns the unicode representation of the file. """ ret = [] entries = [self.metadata_as_entry()] + \ [e for e in self if not e.obsolete] for entry in entries: ret.append(entry.__unicode__(self.wrapwidth)) for entry in self.obsolete_entries(): ret.append(entry.__unicode__(self.wrapwidth)) ret = u('\n').join(ret) return ret if PY3: def __str__(self): return self.__unicode__() else: def __str__(self): """ Returns the string representation of the file. """ return unicode(self).encode(self.encoding) def __contains__(self, entry): """ Overridden ``list`` method to implement the membership test (in and not in). The method considers that an entry is in the file if it finds an entry that has the same msgid (the test is **case sensitive**) and the same msgctxt (or none for both entries). Argument: ``entry`` an instance of :class:`~polib._BaseEntry`. """ return self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt) \ is not None def __eq__(self, other): return str(self) == str(other) def append(self, entry): """ Overridden method to check for duplicates entries, if a user tries to add an entry that is already in the file, the method will raise a ``ValueError`` exception. Argument: ``entry`` an instance of :class:`~polib._BaseEntry`. """ # check_for_duplicates may not be defined (yet) when unpickling. # But if pickling, we never want to check for duplicates anyway. if getattr(self, 'check_for_duplicates', False) and entry in self: raise ValueError('Entry "%s" already exists' % entry.msgid) super(_BaseFile, self).append(entry) def insert(self, index, entry): """ Overridden method to check for duplicates entries, if a user tries to add an entry that is already in the file, the method will raise a ``ValueError`` exception. Arguments: ``index`` index at which the entry should be inserted. ``entry`` an instance of :class:`~polib._BaseEntry`. """ if self.check_for_duplicates and entry in self: raise ValueError('Entry "%s" already exists' % entry.msgid) super(_BaseFile, self).insert(index, entry) def metadata_as_entry(self): """ Returns the file metadata as a :class:`~polib.POFile` instance. """ e = POEntry(msgid='') mdata = self.ordered_metadata() if mdata: strs = [] for name, value in mdata: # Strip whitespace off each line in a multi-line entry strs.append('%s: %s' % (name, value)) e.msgstr = '\n'.join(strs) + '\n' if self.metadata_is_fuzzy: e.flags.append('fuzzy') return e def save(self, fpath=None, repr_method='__unicode__', newline=None): """ Saves the po file to ``fpath``. If it is an existing file and no ``fpath`` is provided, then the existing file is rewritten with the modified data. Keyword arguments: ``fpath`` string, full or relative path to the file. ``repr_method`` string, the method to use for output. ``newline`` string, controls how universal newlines works """ if self.fpath is None and fpath is None: raise IOError('You must provide a file path to save() method') contents = getattr(self, repr_method)() if fpath is None: fpath = self.fpath if repr_method == 'to_binary': with open(fpath, 'wb') as fhandle: fhandle.write(contents) else: with io.open( fpath, 'w', encoding=self.encoding, newline=newline ) as fhandle: if not isinstance(contents, text_type): contents = contents.decode(self.encoding) fhandle.write(contents) # set the file path if not set if self.fpath is None and fpath: self.fpath = fpath def find(self, st, by='msgid', include_obsolete_entries=False, msgctxt=False): """ Find the entry which msgid (or property identified by the ``by`` argument) matches the string ``st``. Keyword arguments: ``st`` string, the string to search for. ``by`` string, the property to use for comparison (default: ``msgid``). ``include_obsolete_entries`` boolean, whether to also search in entries that are obsolete. ``msgctxt`` string, allows specifying a specific message context for the search. """ if include_obsolete_entries: entries = self[:] else: entries = [e for e in self if not e.obsolete] matches = [] for e in entries: if getattr(e, by) == st: if msgctxt is not False and e.msgctxt != msgctxt: continue matches.append(e) if len(matches) == 1: return matches[0] elif len(matches) > 1: if not msgctxt: # find the entry with no msgctx e = None for m in matches: if not m.msgctxt: e = m if e: return e # fallback to the first entry found return matches[0] return None def ordered_metadata(self): """ Convenience method that returns an ordered version of the metadata dictionary. The return value is list of tuples (metadata name, metadata_value). """ # copy the dict first metadata = self.metadata.copy() data_order = [ 'Project-Id-Version', 'Report-Msgid-Bugs-To', 'POT-Creation-Date', 'PO-Revision-Date', 'Last-Translator', 'Language-Team', 'Language', 'MIME-Version', 'Content-Type', 'Content-Transfer-Encoding', 'Plural-Forms' ] ordered_data = [] for data in data_order: try: value = metadata.pop(data) ordered_data.append((data, value)) except KeyError: pass # the rest of the metadata will be alphabetically ordered since there # are no specs for this AFAIK for data in natural_sort(metadata.keys()): value = metadata[data] ordered_data.append((data, value)) return ordered_data def to_binary(self): """ Return the binary representation of the file. """ offsets = [] entries = self.translated_entries() # the keys are sorted in the .mo file def cmp(_self, other): # msgfmt compares entries with msgctxt if it exists self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid other_msgid = other.msgctxt and other.msgctxt or other.msgid if self_msgid > other_msgid: return 1 elif self_msgid < other_msgid: return -1 else: return 0 # add metadata entry entries.sort(key=lambda o: o.msgid_with_context.encode('utf-8')) mentry = self.metadata_as_entry() entries = [mentry] + entries entries_len = len(entries) ids, strs = b(''), b('') for e in entries: # For each string, we need size and file offset. Each string is # NUL terminated; the NUL does not count into the size. msgid = b('') if e.msgctxt: # Contexts are stored by storing the concatenation of the # context, a <EOT> byte, and the original string msgid = self._encode(e.msgctxt + '\4') if e.msgid_plural: msgstr = [] for index in sorted(e.msgstr_plural.keys()): msgstr.append(e.msgstr_plural[index]) msgid += self._encode(e.msgid + '\0' + e.msgid_plural) msgstr = self._encode('\0'.join(msgstr)) else: msgid += self._encode(e.msgid) msgstr = self._encode(e.msgstr) offsets.append((len(ids), len(msgid), len(strs), len(msgstr))) ids += msgid + b('\0') strs += msgstr + b('\0') # The header is 7 32-bit unsigned integers. keystart = 7 * 4 + 16 * entries_len # and the values start after the keys valuestart = keystart + len(ids) koffsets = [] voffsets = [] # The string table first has the list of keys, then the list of values. # Each entry has first the size of the string, then the file offset. for o1, l1, o2, l2 in offsets: koffsets += [l1, o1 + keystart] voffsets += [l2, o2 + valuestart] offsets = koffsets + voffsets output = struct.pack( "Iiiiiii", # Magic number MOFile.MAGIC, # Version 0, # number of entries entries_len, # start of key index 7 * 4, # start of value index 7 * 4 + entries_len * 8, # size and offset of hash table, we don't use hash tables 0, keystart ) if PY3 and sys.version_info.minor > 1: # python 3.2 or superior output += array.array("i", offsets).tobytes() else: output += array.array("i", offsets).tostring() output += ids output += strs return output def _encode(self, mixed): """ Encodes the given ``mixed`` argument with the file encoding if and only if it's an unicode string and returns the encoded string. """ if isinstance(mixed, text_type): mixed = mixed.encode(self.encoding) return mixed # }}} # class POFile {{{ class POFile(_BaseFile): """ Po (or Pot) file reader/writer. This class inherits the :class:`~polib._BaseFile` class and, by extension, the python ``list`` type. """ def __unicode__(self): """ Returns the unicode representation of the po file. """ ret, headers = '', self.header.split('\n') for header in headers: if not len(header): ret += "#\n" elif header[:1] in [',', ':']: ret += '#%s\n' % header else: ret += '# %s\n' % header if not isinstance(ret, text_type): ret = ret.decode(self.encoding) return ret + _BaseFile.__unicode__(self) def save_as_mofile(self, fpath): """ Saves the binary representation of the file to given ``fpath``. Keyword argument: ``fpath`` string, full or relative path to the mo file. """ _BaseFile.save(self, fpath, 'to_binary') def percent_translated(self): """ Convenience method that returns the percentage of translated messages. """ total = len([e for e in self if not e.obsolete]) if total == 0: return 100 translated = len(self.translated_entries()) return int(translated * 100 / float(total)) def translated_entries(self): """ Convenience method that returns the list of translated entries. """ return [e for e in self if e.translated()] def untranslated_entries(self): """ Convenience method that returns the list of untranslated entries. """ return [e for e in self if not e.translated() and not e.obsolete and not e.fuzzy] def fuzzy_entries(self): """ Convenience method that returns the list of fuzzy entries. """ return [e for e in self if e.fuzzy and not e.obsolete] def obsolete_entries(self): """ Convenience method that returns the list of obsolete entries. """ return [e for e in self if e.obsolete] def merge(self, refpot): """ Convenience method that merges the current pofile with the pot file provided. It behaves exactly as the gettext msgmerge utility: * comments of this file will be preserved, but extracted comments and occurrences will be discarded; * any translations or comments in the file will be discarded, however, dot comments and file positions will be preserved; * the fuzzy flags are preserved. Keyword argument: ``refpot`` object POFile, the reference catalog. """ # Store entries in dict/set for faster access self_entries = dict( (entry.msgid_with_context, entry) for entry in self ) refpot_msgids = set(entry.msgid_with_context for entry in refpot) # Merge entries that are in the refpot for entry in refpot: e = self_entries.get(entry.msgid_with_context) if e is None: e = POEntry() self.append(e) e.merge(entry) # ok, now we must "obsolete" entries that are not in the refpot anymore for entry in self: if entry.msgid_with_context not in refpot_msgids: entry.obsolete = True # }}} # class MOFile {{{ class MOFile(_BaseFile): """ Mo file reader/writer. This class inherits the :class:`~polib._BaseFile` class and, by extension, the python ``list`` type. """ MAGIC = 0x950412de MAGIC_SWAPPED = 0xde120495 def __init__(self, *args, **kwargs): """ Constructor, accepts all keywords arguments accepted by :class:`~polib._BaseFile` class. """ _BaseFile.__init__(self, *args, **kwargs) self.magic_number = None self.version = 0 def save_as_pofile(self, fpath): """ Saves the mofile as a pofile to ``fpath``. Keyword argument: ``fpath`` string, full or relative path to the file. """ _BaseFile.save(self, fpath) def save(self, fpath=None): """ Saves the mofile to ``fpath``. Keyword argument: ``fpath`` string, full or relative path to the file. """ _BaseFile.save(self, fpath, 'to_binary') def percent_translated(self): """ Convenience method to keep the same interface with POFile instances. """ return 100 def translated_entries(self): """ Convenience method to keep the same interface with POFile instances. """ return self def untranslated_entries(self): """ Convenience method to keep the same interface with POFile instances. """ return [] def fuzzy_entries(self): """ Convenience method to keep the same interface with POFile instances. """ return [] def obsolete_entries(self): """ Convenience method to keep the same interface with POFile instances. """ return [] # }}} # class _BaseEntry {{{ class _BaseEntry(object): """ Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes. This class should **not** be instantiated directly. """ def __init__(self, *args, **kwargs): """ Constructor, accepts the following keyword arguments: ``msgid`` string, the entry msgid. ``msgstr`` string, the entry msgstr. ``msgid_plural`` string, the entry msgid_plural. ``msgstr_plural`` dict, the entry msgstr_plural lines. ``msgctxt`` string, the entry context (msgctxt). ``obsolete`` bool, whether the entry is "obsolete" or not. ``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional). """ self.msgid = kwargs.get('msgid', '') self.msgstr = kwargs.get('msgstr', '') self.msgid_plural = kwargs.get('msgid_plural', '') self.msgstr_plural = kwargs.get('msgstr_plural', {}) self.msgctxt = kwargs.get('msgctxt', None) self.obsolete = kwargs.get('obsolete', False) self.encoding = kwargs.get('encoding', default_encoding) def __unicode__(self, wrapwidth=78): """ Returns the unicode representation of the entry. """ if self.obsolete: delflag = '#~ ' else: delflag = '' ret = [] # write the msgctxt if any if self.msgctxt is not None: ret += self._str_field("msgctxt", delflag, "", self.msgctxt, wrapwidth) # write the msgid ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth) # write the msgid_plural if any if self.msgid_plural: ret += self._str_field("msgid_plural", delflag, "", self.msgid_plural, wrapwidth) if self.msgstr_plural: # write the msgstr_plural if any msgstrs = self.msgstr_plural keys = list(msgstrs) keys.sort() for index in keys: msgstr = msgstrs[index] plural_index = '[%s]' % index ret += self._str_field("msgstr", delflag, plural_index, msgstr, wrapwidth) else: # otherwise write the msgstr ret += self._str_field("msgstr", delflag, "", self.msgstr, wrapwidth) ret.append('') ret = u('\n').join(ret) return ret if PY3: def __str__(self): return self.__unicode__() else: def __str__(self): """ Returns the string representation of the entry. """ return unicode(self).encode(self.encoding) def __eq__(self, other): return str(self) == str(other) def _str_field(self, fieldname, delflag, plural_index, field, wrapwidth=78): lines = field.splitlines(True) if len(lines) > 1: lines = [''] + lines # start with initial empty line else: escaped_field = escape(field) specialchars_count = 0 for c in ['\\', '\n', '\r', '\t', '\v', '\b', '\f', '"']: specialchars_count += field.count(c) # comparison must take into account fieldname length + one space # + 2 quotes (eg. msgid "<string>") flength = len(fieldname) + 3 if plural_index: flength += len(plural_index) real_wrapwidth = wrapwidth - flength + specialchars_count if wrapwidth > 0 and len(field) > real_wrapwidth: # Wrap the line but take field name into account lines = [''] + [unescape(item) for item in textwrap.wrap( escaped_field, wrapwidth - 2, # 2 for quotes "" drop_whitespace=False, break_long_words=False )] else: lines = [field] if fieldname.startswith('previous_'): # quick and dirty trick to get the real field name fieldname = fieldname[9:] ret = ['%s%s%s "%s"' % (delflag, fieldname, plural_index, escape(lines.pop(0)))] for line in lines: ret.append('%s"%s"' % (delflag, escape(line))) return ret @property def msgid_with_context(self): if self.msgctxt: return '%s%s%s' % (self.msgctxt, "\x04", self.msgid) return self.msgid # }}} # class POEntry {{{ class POEntry(_BaseEntry): """ Represents a po file entry. """ def __init__(self, *args, **kwargs): """ Constructor, accepts the following keyword arguments: ``comment`` string, the entry comment. ``tcomment`` string, the entry translator comment. ``occurrences`` list, the entry occurrences. ``flags`` list, the entry flags. ``previous_msgctxt`` string, the entry previous context. ``previous_msgid`` string, the entry previous msgid. ``previous_msgid_plural`` string, the entry previous msgid_plural. ``linenum`` integer, the line number of the entry """ _BaseEntry.__init__(self, *args, **kwargs) self.comment = kwargs.get('comment', '') self.tcomment = kwargs.get('tcomment', '') self.occurrences = kwargs.get('occurrences', []) self.flags = kwargs.get('flags', []) self.previous_msgctxt = kwargs.get('previous_msgctxt', None) self.previous_msgid = kwargs.get('previous_msgid', None) self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None) self.linenum = kwargs.get('linenum', None) def __unicode__(self, wrapwidth=78): """ Returns the unicode representation of the entry. """ ret = [] # comments first, if any (with text wrapping as xgettext does) if self.obsolete: comments = [('tcomment', '# ')] else: comments = [('tcomment', '# '), ('comment', '#. ')] for c in comments: val = getattr(self, c[0]) if val: for comment in val.split('\n'): if wrapwidth > 0 and len(comment) + len(c[1]) > wrapwidth: ret += textwrap.wrap( comment, wrapwidth, initial_indent=c[1], subsequent_indent=c[1], break_long_words=False ) else: ret.append('%s%s' % (c[1], comment)) # occurrences (with text wrapping as xgettext does) if not self.obsolete and self.occurrences: filelist = [] for fpath, lineno in self.occurrences: if lineno: filelist.append('%s:%s' % (fpath, lineno)) else: filelist.append(fpath) filestr = ' '.join(filelist) if wrapwidth > 0 and len(filestr) + 3 > wrapwidth: # textwrap split words that contain hyphen, this is not # what we want for filenames, so the dirty hack is to # temporally replace hyphens with a char that a file cannot # contain, like "*" ret += [line.replace('*', '-') for line in textwrap.wrap( filestr.replace('-', '*'), wrapwidth, initial_indent='#: ', subsequent_indent='#: ', break_long_words=False )] else: ret.append('#: ' + filestr) # flags (TODO: wrapping ?) if self.flags: ret.append('#, %s' % ', '.join(self.flags)) # previous context and previous msgid/msgid_plural fields = ['previous_msgctxt', 'previous_msgid', 'previous_msgid_plural'] if self.obsolete: prefix = "#~| " else: prefix = "#| " for f in fields: val = getattr(self, f) if val is not None: ret += self._str_field(f, prefix, "", val, wrapwidth) ret.append(_BaseEntry.__unicode__(self, wrapwidth)) ret = u('\n').join(ret) return ret def __cmp__(self, other): """ Called by comparison operations if rich comparison is not defined. """ # First: Obsolete test if self.obsolete != other.obsolete: if self.obsolete: return -1 else: return 1 # Work on a copy to protect original occ1 = sorted(self.occurrences[:]) occ2 = sorted(other.occurrences[:]) if occ1 > occ2: return 1 if occ1 < occ2: return -1 # Compare context msgctxt = self.msgctxt or '0' othermsgctxt = other.msgctxt or '0' if msgctxt > othermsgctxt: return 1 elif msgctxt < othermsgctxt: return -1 # Compare msgid_plural msgid_plural = self.msgid_plural or '0' othermsgid_plural = other.msgid_plural or '0' if msgid_plural > othermsgid_plural: return 1 elif msgid_plural < othermsgid_plural: return -1 # Compare msgstr_plural if self.msgstr_plural and isinstance(self.msgstr_plural, dict): msgstr_plural = list(self.msgstr_plural.values()) else: msgstr_plural = [] if other.msgstr_plural and isinstance(other.msgstr_plural, dict): othermsgstr_plural = list(other.msgstr_plural.values()) else: othermsgstr_plural = [] if msgstr_plural > othermsgstr_plural: return 1 elif msgstr_plural < othermsgstr_plural: return -1 # Compare msgid if self.msgid > other.msgid: return 1 elif self.msgid < other.msgid: return -1 # Compare msgstr if self.msgstr > other.msgstr: return 1 elif self.msgstr < other.msgstr: return -1 return 0 def __gt__(self, other): return self.__cmp__(other) > 0 def __lt__(self, other): return self.__cmp__(other) < 0 def __ge__(self, other): return self.__cmp__(other) >= 0 def __le__(self, other): return self.__cmp__(other) <= 0 def __eq__(self, other): return self.__cmp__(other) == 0 def __ne__(self, other): return self.__cmp__(other) != 0 def translated(self): """ Returns ``True`` if the entry has been translated or ``False`` otherwise. """ if self.obsolete or self.fuzzy: return False if self.msgstr != '': return True if self.msgstr_plural: for pos in self.msgstr_plural: if self.msgstr_plural[pos] == '': return False return True return False def merge(self, other): """ Merge the current entry with the given pot entry. """ self.msgid = other.msgid self.msgctxt = other.msgctxt self.occurrences = other.occurrences self.comment = other.comment fuzzy = self.fuzzy self.flags = other.flags[:] # clone flags if fuzzy: self.flags.append('fuzzy') self.msgid_plural = other.msgid_plural self.obsolete = other.obsolete self.previous_msgctxt = other.previous_msgctxt self.previous_msgid = other.previous_msgid self.previous_msgid_plural = other.previous_msgid_plural if other.msgstr_plural: for pos in other.msgstr_plural: try: # keep existing translation at pos if any self.msgstr_plural[pos] except KeyError: self.msgstr_plural[pos] = '' @property def fuzzy(self): return 'fuzzy' in self.flags @fuzzy.setter def fuzzy(self, value): if value and not self.fuzzy: self.flags.insert(0, 'fuzzy') elif not value and self.fuzzy: self.flags.remove('fuzzy') def __hash__(self): return hash((self.msgid, self.msgstr)) # }}} # class MOEntry {{{ class MOEntry(_BaseEntry): """ Represents a mo file entry. """ def __init__(self, *args, **kwargs): """ Constructor, accepts the following keyword arguments, for consistency with :class:`~polib.POEntry`: ``comment`` ``tcomment`` ``occurrences`` ``flags`` ``previous_msgctxt`` ``previous_msgid`` ``previous_msgid_plural`` Note: even though these keyword arguments are accepted, they hold no real meaning in the context of MO files and are simply ignored. """ _BaseEntry.__init__(self, *args, **kwargs) self.comment = '' self.tcomment = '' self.occurrences = [] self.flags = [] self.previous_msgctxt = None self.previous_msgid = None self.previous_msgid_plural = None def __hash__(self): return hash((self.msgid, self.msgstr)) # }}} # class _POFileParser {{{ class _POFileParser(object): """ A finite state machine to efficiently and correctly parse po file format. """ def __init__(self, pofile, *args, **kwargs): """ Constructor. Keyword arguments: ``pofile`` string, path to the po file or its content ``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional). ``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). """ enc = kwargs.get('encoding', default_encoding) if _is_file(pofile): try: self.fhandle = io.open(pofile, 'rt', encoding=enc) except LookupError: enc = default_encoding self.fhandle = io.open(pofile, 'rt', encoding=enc) else: self.fhandle = pofile.splitlines() klass = kwargs.get('klass') if klass is None: klass = POFile self.instance = klass( pofile=pofile, encoding=enc, check_for_duplicates=kwargs.get('check_for_duplicates', False) ) self.transitions = {} self.current_line = 0 self.current_entry = POEntry(linenum=self.current_line) self.current_state = 'st' self.current_token = None # two memo flags used in handlers self.msgstr_index = 0 self.entry_obsolete = 0 # Configure the state machine, by adding transitions. # Signification of symbols: # * ST: Beginning of the file (start) # * HE: Header # * TC: a translation comment # * GC: a generated comment # * OC: a file/line occurrence # * FL: a flags line # * CT: a message context # * PC: a previous msgctxt # * PM: a previous msgid # * PP: a previous msgid_plural # * MI: a msgid # * MP: a msgid plural # * MS: a msgstr # * MX: a msgstr plural # * MC: a msgid or msgstr continuation line all = ['st', 'he', 'gc', 'oc', 'fl', 'ct', 'pc', 'pm', 'pp', 'tc', 'ms', 'mp', 'mx', 'mi'] self.add('tc', ['st', 'he'], 'he') self.add('tc', ['gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mp', 'mx', 'mi'], 'tc') self.add('gc', all, 'gc') self.add('oc', all, 'oc') self.add('fl', all, 'fl') self.add('pc', all, 'pc') self.add('pm', all, 'pm') self.add('pp', all, 'pp') self.add('ct', ['st', 'he', 'gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mx'], 'ct') self.add('mi', ['st', 'he', 'gc', 'oc', 'fl', 'ct', 'tc', 'pc', 'pm', 'pp', 'ms', 'mx'], 'mi') self.add('mp', ['tc', 'gc', 'pc', 'pm', 'pp', 'mi'], 'mp') self.add('ms', ['mi', 'mp', 'tc'], 'ms') self.add('mx', ['mi', 'mx', 'mp', 'tc'], 'mx') self.add('mc', ['ct', 'mi', 'mp', 'ms', 'mx', 'pm', 'pp', 'pc'], 'mc') def parse(self): """ Run the state machine, parse the file line by line and call process() with the current matched symbol. """ try: keywords = { 'msgctxt': 'ct', 'msgid': 'mi', 'msgstr': 'ms', 'msgid_plural': 'mp', } prev_keywords = { 'msgid_plural': 'pp', 'msgid': 'pm', 'msgctxt': 'pc', } tokens = [] fpath = '%s ' % self.instance.fpath if self.instance.fpath else '' for line in self.fhandle: self.current_line += 1 if self.current_line == 1: BOM = codecs.BOM_UTF8.decode('utf-8') if line.startswith(BOM): line = line[len(BOM):] line = line.strip() if line == '': continue tokens = line.split(None, 2) nb_tokens = len(tokens) if tokens[0] == '#~|': continue if tokens[0] == '#~' and nb_tokens > 1: line = line[3:].strip() tokens = tokens[1:] nb_tokens -= 1 self.entry_obsolete = 1 else: self.entry_obsolete = 0 # Take care of keywords like # msgid, msgid_plural, msgctxt & msgstr. if tokens[0] in keywords and nb_tokens > 1: line = line[len(tokens[0]):].lstrip() if re.search(r'([^\\]|^)"', line[1:-1]): raise IOError('Syntax error in po file %s(line %s): ' 'unescaped double quote found' % (fpath, self.current_line)) self.current_token = line self.process(keywords[tokens[0]]) continue self.current_token = line if tokens[0] == '#:': if nb_tokens <= 1: continue # we are on a occurrences line self.process('oc') elif line[:1] == '"': # we are on a continuation line if re.search(r'([^\\]|^)"', line[1:-1]): raise IOError('Syntax error in po file %s(line %s): ' 'unescaped double quote found' % (fpath, self.current_line)) self.process('mc') elif line[:7] == 'msgstr[': # we are on a msgstr plural self.process('mx') elif tokens[0] == '#,': if nb_tokens <= 1: continue # we are on a flags line self.process('fl') elif tokens[0] == '#' or tokens[0].startswith('##'): if line == '#': line += ' ' # we are on a translator comment line self.process('tc') elif tokens[0] == '#.': if nb_tokens <= 1: continue # we are on a generated comment line self.process('gc') elif tokens[0] == '#|': if nb_tokens <= 1: raise IOError('Syntax error in po file %s(line %s)' % (fpath, self.current_line)) # Remove the marker and any whitespace right after that. line = line[2:].lstrip() self.current_token = line if tokens[1].startswith('"'): # Continuation of previous metadata. self.process('mc') continue if nb_tokens == 2: # Invalid continuation line. raise IOError('Syntax error in po file %s(line %s): ' 'invalid continuation line' % (fpath, self.current_line)) # we are on a "previous translation" comment line, if tokens[1] not in prev_keywords: # Unknown keyword in previous translation comment. raise IOError('Syntax error in po file %s(line %s): ' 'unknown keyword %s' % (fpath, self.current_line, tokens[1])) # Remove the keyword and any whitespace # between it and the starting quote. line = line[len(tokens[1]):].lstrip() self.current_token = line self.process(prev_keywords[tokens[1]]) else: raise IOError('Syntax error in po file %s(line %s)' % (fpath, self.current_line)) if self.current_entry and len(tokens) > 0 and \ not tokens[0].startswith('#'): # since entries are added when another entry is found, we must # add the last entry here (only if there are lines). Trailing # comments are ignored self.instance.append(self.current_entry) # before returning the instance, check if there's metadata and if # so extract it in a dict metadataentry = self.instance.find('') if metadataentry: # metadata found # remove the entry self.instance.remove(metadataentry) self.instance.metadata_is_fuzzy = metadataentry.flags key = None for msg in metadataentry.msgstr.splitlines(): try: key, val = msg.split(':', 1) self.instance.metadata[key] = val.strip() except (ValueError, KeyError): if key is not None: self.instance.metadata[key] += '\n' + msg.strip() finally: # close opened file if not isinstance(self.fhandle, list): # must be file self.fhandle.close() return self.instance def add(self, symbol, states, next_state): """ Add a transition to the state machine. Keywords arguments: ``symbol`` string, the matched token (two chars symbol). ``states`` list, a list of states (two chars symbols). ``next_state`` the next state the fsm will have after the action. """ for state in states: action = getattr(self, 'handle_%s' % next_state) self.transitions[(symbol, state)] = (action, next_state) def process(self, symbol): """ Process the transition corresponding to the current state and the symbol provided. Keywords arguments: ``symbol`` string, the matched token (two chars symbol). ``linenum`` integer, the current line number of the parsed file. """ try: (action, state) = self.transitions[(symbol, self.current_state)] if action(): self.current_state = state except Exception: fpath = '%s ' % self.instance.fpath if self.instance.fpath else '' if hasattr(self.fhandle, 'close'): self.fhandle.close() raise IOError('Syntax error in po file %s(line %s)' % (fpath, self.current_line)) # state handlers def handle_he(self): """Handle a header comment.""" if self.instance.header != '': self.instance.header += '\n' self.instance.header += self.current_token[2:] return 1 def handle_tc(self): """Handle a translator comment.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) if self.current_entry.tcomment != '': self.current_entry.tcomment += '\n' tcomment = self.current_token.lstrip('#') if tcomment.startswith(' '): tcomment = tcomment[1:] self.current_entry.tcomment += tcomment return True def handle_gc(self): """Handle a generated comment.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) if self.current_entry.comment != '': self.current_entry.comment += '\n' self.current_entry.comment += self.current_token[3:] return True def handle_oc(self): """Handle a file:num occurrence.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) occurrences = self.current_token[3:].split() for occurrence in occurrences: if occurrence != '': try: fil, line = occurrence.rsplit(':', 1) if not line.isdigit(): fil = occurrence line = '' self.current_entry.occurrences.append((fil, line)) except (ValueError, AttributeError): self.current_entry.occurrences.append((occurrence, '')) return True def handle_fl(self): """Handle a flags line.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.flags += [c.strip() for c in self.current_token[3:].split(',')] return True def handle_pp(self): """Handle a previous msgid_plural line.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.previous_msgid_plural = \ unescape(self.current_token[1:-1]) return True def handle_pm(self): """Handle a previous msgid line.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.previous_msgid = \ unescape(self.current_token[1:-1]) return True def handle_pc(self): """Handle a previous msgctxt line.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.previous_msgctxt = \ unescape(self.current_token[1:-1]) return True def handle_ct(self): """Handle a msgctxt.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.msgctxt = unescape(self.current_token[1:-1]) return True def handle_mi(self): """Handle a msgid.""" if self.current_state in ['mc', 'ms', 'mx']: self.instance.append(self.current_entry) self.current_entry = POEntry(linenum=self.current_line) self.current_entry.obsolete = self.entry_obsolete self.current_entry.msgid = unescape(self.current_token[1:-1]) return True def handle_mp(self): """Handle a msgid plural.""" self.current_entry.msgid_plural = unescape(self.current_token[1:-1]) return True def handle_ms(self): """Handle a msgstr.""" self.current_entry.msgstr = unescape(self.current_token[1:-1]) return True def handle_mx(self): """Handle a msgstr plural.""" index = self.current_token[7] value = self.current_token[self.current_token.find('"') + 1:-1] self.current_entry.msgstr_plural[int(index)] = unescape(value) self.msgstr_index = int(index) return True def handle_mc(self): """Handle a msgid or msgstr continuation line.""" token = unescape(self.current_token[1:-1]) if self.current_state == 'ct': self.current_entry.msgctxt += token elif self.current_state == 'mi': self.current_entry.msgid += token elif self.current_state == 'mp': self.current_entry.msgid_plural += token elif self.current_state == 'ms': self.current_entry.msgstr += token elif self.current_state == 'mx': self.current_entry.msgstr_plural[self.msgstr_index] += token elif self.current_state == 'pp': self.current_entry.previous_msgid_plural += token elif self.current_state == 'pm': self.current_entry.previous_msgid += token elif self.current_state == 'pc': self.current_entry.previous_msgctxt += token # don't change the current state return False # }}} # class _MOFileParser {{{ class _MOFileParser(object): """ A class to parse binary mo files. """ def __init__(self, mofile, *args, **kwargs): """ Constructor. Keyword arguments: ``mofile`` string, path to the mo file or its content ``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional). ``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). """ if _is_file(mofile): self.fhandle = open(mofile, 'rb') else: self.fhandle = io.BytesIO(mofile) klass = kwargs.get('klass') if klass is None: klass = MOFile self.instance = klass( fpath=mofile, encoding=kwargs.get('encoding', default_encoding), check_for_duplicates=kwargs.get('check_for_duplicates', False) ) def __del__(self): """ Make sure the file is closed, this prevents warnings on unclosed file when running tests with python >= 3.2. """ if self.fhandle and hasattr(self.fhandle, 'close'): self.fhandle.close() def parse(self): """ Build the instance with the file handle provided in the constructor. """ # parse magic number magic_number = self._readbinary('<I', 4) if magic_number == MOFile.MAGIC: ii = '<II' elif magic_number == MOFile.MAGIC_SWAPPED: ii = '>II' else: raise IOError('Invalid mo file, magic number is incorrect !') self.instance.magic_number = magic_number # parse the version number and the number of strings version, numofstrings = self._readbinary(ii, 8) # from MO file format specs: "A program seeing an unexpected major # revision number should stop reading the MO file entirely" if version >> 16 not in (0, 1): raise IOError('Invalid mo file, unexpected major revision number') self.instance.version = version # original strings and translation strings hash table offset msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8) # move to msgid hash table and read length and offset of msgids self.fhandle.seek(msgids_hash_offset) msgids_index = [] for i in range(numofstrings): msgids_index.append(self._readbinary(ii, 8)) # move to msgstr hash table and read length and offset of msgstrs self.fhandle.seek(msgstrs_hash_offset) msgstrs_index = [] for i in range(numofstrings): msgstrs_index.append(self._readbinary(ii, 8)) # build entries encoding = self.instance.encoding for i in range(numofstrings): self.fhandle.seek(msgids_index[i][1]) msgid = self.fhandle.read(msgids_index[i][0]) self.fhandle.seek(msgstrs_index[i][1]) msgstr = self.fhandle.read(msgstrs_index[i][0]) if i == 0 and not msgid: # metadata raw_metadata, metadata = msgstr.split(b('\n')), {} for line in raw_metadata: tokens = line.split(b(':'), 1) if tokens[0] != b(''): try: k = tokens[0].decode(encoding) v = tokens[1].decode(encoding) metadata[k] = v.strip() except IndexError: metadata[k] = u('') self.instance.metadata = metadata continue # test if we have a plural entry msgid_tokens = msgid.split(b('\0')) if len(msgid_tokens) > 1: entry = self._build_entry( msgid=msgid_tokens[0], msgid_plural=msgid_tokens[1], msgstr_plural=dict((k, v) for k, v in enumerate(msgstr.split(b('\0')))) ) else: entry = self._build_entry(msgid=msgid, msgstr=msgstr) self.instance.append(entry) # close opened file self.fhandle.close() return self.instance def _build_entry(self, msgid, msgstr=None, msgid_plural=None, msgstr_plural=None): msgctxt_msgid = msgid.split(b('\x04')) encoding = self.instance.encoding if len(msgctxt_msgid) > 1: kwargs = { 'msgctxt': msgctxt_msgid[0].decode(encoding), 'msgid': msgctxt_msgid[1].decode(encoding), } else: kwargs = {'msgid': msgid.decode(encoding)} if msgstr: kwargs['msgstr'] = msgstr.decode(encoding) if msgid_plural: kwargs['msgid_plural'] = msgid_plural.decode(encoding) if msgstr_plural: for k in msgstr_plural: msgstr_plural[k] = msgstr_plural[k].decode(encoding) kwargs['msgstr_plural'] = msgstr_plural return MOEntry(**kwargs) def _readbinary(self, fmt, numbytes): """ Private method that unpack n bytes of data using format <fmt>. It returns a tuple or a mixed value if the tuple length is 1. """ bytes = self.fhandle.read(numbytes) tup = struct.unpack(fmt, bytes) if len(tup) == 1: return tup[0] return tup # }}}
61,901
Python
.py
1,579
28.028499
79
0.531541
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,354
lc_data.py
kovidgoyal_calibre/setup/lc_data.py
#!/usr/bin/env python3 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' # A database of locale data for all the languages known to glibc # To regenerate run: # sudo locale-gen -A && python3 lc_time.py import locale import os import pprint import sys def generate_data(): def nl(code): return locale.nl_langinfo(code) ans = [] for x, limit in (('day', 8), ('mon', 13)): for attr in ('ab' + x, x): ans.append((attr, tuple(map(nl, (getattr(locale, '%s_%d' % (attr.upper(), i)) for i in range(1, limit)))))), for x in ('d_t_fmt', 'd_fmt', 't_fmt', 't_fmt_ampm', 'radixchar', 'thousep', 'yesexpr', 'noexpr'): ans.append((x, nl(getattr(locale, x.upper())))) return ans def main(): if sys.version_info[0] < 3: raise RuntimeError('Must be run using python 3.x') locale.setlocale(locale.LC_ALL, '') dest = os.path.abspath(__file__) os.chdir('/usr/share/i18n/locales') data = [] for f in sorted(os.listdir('.')): try: locale.setlocale(locale.LC_ALL, (f, 'utf-8')) except locale.Error: continue data.append((f, generate_data())) with open(dest, 'r+b') as f: raw = f.read() marker = b'# The data {{' + b'{' pos = raw.find(marker) data = pprint.pformat(data, width=160) if not isinstance(data, bytes): data = data.encode('utf-8') f.seek(pos) f.truncate() f.write(marker + b'\ndata = ' + data + b'\n' + b'# }}' + b'}') if __name__ == '__main__': main() # The data {{{ data = [('aa_DJ', [('abday', ('aca', 'etl', 'tal', 'arb', 'kam', 'gum', 'sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('qun', 'nah', 'cig', 'agd', 'cax', 'qas', 'qad', 'leq', 'way', 'dit', 'xim', 'kax')), ('mon', ('Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[mnMN].*')]), ('aa_ER', [('abday', ('Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('Qun', 'Nah', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax')), ('mon', ('Qunxa Garablu', 'Naharsi Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Leqeeni', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[mnMN].*')]), ('aa_ET', [('abday', ('Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('Qun', 'Kud', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax')), ('mon', ('Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[mnMN].*')]), ('af_ZA', [('abday', ('So', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Sa')), ('day', ('Sondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrydag', 'Saterdag')), ('abmon', ('Jan', 'Feb', 'Mrt', 'Apr', 'Mei', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Januarie', 'Februarie', 'Maart', 'April', 'Mei', 'Junie', 'Julie', 'Augustus', 'September', 'Oktober', 'November', 'Desember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[jJyY]'), ('noexpr', '^[nN]')]), ('ak_GH', [('abday', ('Kwe', 'Dwo', 'Ben', 'Wuk', 'Yaw', 'Fia', 'Mem')), ('day', ('Kwesida', 'Dwowda', 'Benada', 'Wukuda', 'Yawda', 'Fida', 'Memeneda')), ('abmon', ('S-Ɔ', 'K-Ɔ', 'E-Ɔ', 'E-O', 'E-K', 'O-A', 'A-K', 'D-Ɔ', 'F-Ɛ', 'Ɔ-A', 'Ɔ-O', 'M-Ɔ')), ('mon', ('Sanda-Ɔpɛpɔn', 'Kwakwar-Ɔgyefuo', 'Ebɔw-Ɔbenem', 'Ebɔbira-Oforisuo', 'Esusow Aketseaba-Kɔtɔnimba', 'Obirade-Ayɛwohomumu', 'Ayɛwoho-Kitawonsa', 'Difuu-Ɔsandaa', 'Fankwa-Ɛbɔ', 'Ɔbɛsɛ-Ahinime', 'Ɔberɛfɛw-Obubuo', 'Mumu-Ɔpɛnimba')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y/%m/%d'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[dDnN].*')]), ('am_ET', [('abday', ('እሑድ', 'ሰኞ ', 'ማክሰ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ')), ('day', ('እሑድ', 'ሰኞ', 'ማክሰኞ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ')), ('abmon', ('ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም')), ('mon', ('ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር')), ('d_t_fmt', '%A፣ %B %e ቀን %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('an_ES', [('abday', ('dom', 'lun', 'mar', 'mie', 'chu', 'bie', 'sab')), ('day', ('domingo', 'luns', 'martes', 'miecols', 'chuebes', 'biernes', 'sabado')), ('abmon', ('chi', 'fre', 'mar', 'abr', 'may', 'chn', 'chl', 'ago', 'set', 'oct', 'nob', 'abi')), ('mon', ('chinero', 'frebero', 'marzo', 'abril', 'mayo', 'chunio', 'chulio', 'agosto', 'setiembre', 'octubre', 'nobiembre', 'abiento')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('anp_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'बृहस्पति ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'बृहस्पतिवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[हवyY]'), ('noexpr', '^[नइnN]')]), ('ar_AE', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت ')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_BH', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_DZ', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_EG', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_IN', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_IQ', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_JO', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_KW', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_LB', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_LY', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_MA', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_OM', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_QA', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعـة', 'السبت')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسـان', 'أيار', 'حزيران', 'تـمـوز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%A %e %B %Y %k:%M:%S'), ('d_fmt', '%A %e %B %Y'), ('t_fmt', '%k:%M:%S'), ('t_fmt_ampm', '%k:%M:%S'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SD', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SS', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SY', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نواران', 'حزير', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_TN', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_YE', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('as_IN', [('abday', ('দেও', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহষ্পতি', 'শুক্ৰ', 'শনি')), ('day', ('দেওবাৰ', 'সোমবাৰ', 'মঙ্গলবাৰ', 'বুধবাৰ', 'বৃহষ্পতিবাৰ', 'শুক্ৰবাৰ', 'শনিবাৰ')), ('abmon', ('জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগ', 'চেপ্তেম্বৰ', 'অক্টোবৰ', 'নভেম্বৰ', 'ডিচেম্বৰ')), ('mon', ('জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগষ্ট', 'চেপ্তেম্বৰ', 'অক্টোবৰ', 'নভেম্বৰ', 'ডিচেম্বৰ')), ('d_t_fmt', '%e %B, %Y %I.%M.%S %p %Z'), ('d_fmt', '%e-%m-%Y'), ('t_fmt', '%I.%M.%S %p'), ('t_fmt_ampm', '%I.%M.%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYহ].*'), ('noexpr', '^[nNন].*')]), ('ast_ES', [('abday', ('dom', 'llu', 'mar', 'mié', 'xue', 'vie', 'sáb')), ('day', ('domingu', 'llunes', 'martes', 'miércoles', 'xueves', 'vienres', 'sábadu')), ('abmon', ('xin', 'feb', 'mar', 'abr', 'may', 'xun', 'xnt', 'ago', 'set', 'och', 'pay', 'avi')), ('mon', ('xineru', 'febreru', 'marzu', 'abril', 'mayu', 'xunu', 'xunetu', 'agostu', 'setiembre', 'ochobre', 'payares', 'avientu')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ayc_PE', [('abday', ('tum', 'lun', 'mar', 'mir', 'juy', 'wir', 'saw')), ('day', ('tuminku', 'lunisa', 'martisa', 'mirkulisa', 'juywisa', 'wirnisa', 'sawäru')), ('abmon', ('ini', 'phi', 'mar', 'awr', 'may', 'jun', 'jul', 'awu', 'sit', 'ukt', 'nuw', 'ris')), ('mon', ('inïru', 'phiwriru', 'marsu', 'awrila', 'mayu', 'junyu', 'julyu', 'awustu', 'sitimri', 'uktuwri', 'nuwimri', 'risimri')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[uUsSyY].*'), ('noexpr', '^[jJnN].*')]), ('az_AZ', [('abday', ('baz', 'ber', 'çax', 'çər', 'cax', 'cüm', 'şnb')), ('day', ('bazar günü', 'bazar ertəsi', 'çərşənbə axşamı', 'çərşənbə', 'cümə axşamı', 'cümə', 'şənbə')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('be_BY', [('abday', ('Няд', 'Пан', 'Аўт', 'Срд', 'Чцв', 'Пят', 'Суб')), ('day', ('Нядзеля', 'Панядзелак', 'Аўторак', 'Серада', 'Чацвер', 'Пятніца', 'Субота')), ('abmon', ('Стд', 'Лют', 'Сак', 'Крс', 'Тра', 'Чэр', 'Ліп', 'Жнв', 'Врс', 'Кст', 'Ліс', 'Снж')), ('mon', ('Студзень', 'Люты', 'Сакавік', 'Красавік', 'Травень', 'Чэрвень', 'Ліпень', 'Жнівень', 'Верасень', 'Кастрычнік', 'Лістапад', 'Снежань')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[ТтYy].*'), ('noexpr', '^[НнNn].*')]), ('bem_ZM', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Pa Mulungu', 'Palichimo', 'Palichibuli', 'Palichitatu', 'Palichine', 'Palichisano', 'Pachibelushi')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('Januari', 'Februari', 'Machi', 'Epreo', 'Mei', 'Juni', 'Julai', 'Ogasti', 'Septemba', 'Oktoba', 'Novemba', 'Disemba')), ('d_t_fmt', '%a %d %b %Y %R %Z'), ('d_fmt', '%m/%d/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE].*'), ('noexpr', '^[nNaA].*')]), ('ber_DZ', [('abday', ('baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt')), ('day', ('bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('ber_MA', [('abday', ('baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt')), ('day', ('bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('bg_BG', [('abday', ('нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб')), ('day', ('неделя', 'понеделник', 'вторник', 'сряда', 'четвъртък', 'петък', 'събота')), ('abmon', ('яну', 'фев', 'мар', 'апр', 'май', 'юни', 'юли', 'авг', 'сеп', 'окт', 'ное', 'дек')), ('mon', ('януари', 'февруари', 'март', 'април', 'май', 'юни', 'юли', 'август', 'септември', 'октомври', 'ноември', 'декември')), ('d_t_fmt', '%x (%a) %X %Z'), ('d_fmt', '%e.%m.%Y'), ('t_fmt', '%k,%M,%S'), ('t_fmt_ampm', '%l,%M,%S'), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[+1ДдDdYyOo].*'), ('noexpr', '^[-0НнNnKk].*')]), ('bho_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'गुरु ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'गुरुवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('bn_BD', [('abday', ('রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি')), ('day', ('রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার')), ('abmon', ('জানু', 'ফেব্রু', 'মার্চ', 'এপ্রি', 'মে', 'জুন', 'জুল', 'আগ', 'সেপ্টে', 'অক্টো', 'নভে', 'ডিসে')), ('mon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[হ্যাঁyY]'), ('noexpr', '^[নাnN]')]), ('bn_IN', [('abday', ('রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি')), ('day', ('রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার')), ('abmon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('mon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[হ্যাঁyY]'), ('noexpr', '^[নাnN]')]), ('bo_CN', [('abday', ('ཉི་', 'ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་')), ('day', ('གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('bo_IN', [('abday', ('ཉི་', 'ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་')), ('day', ('གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('br_FR', [('abday', ('sul', 'lun', 'meu', 'mer', 'yao', 'gwe', 'sad')), ('day', ('sul', 'lun', 'meurzh', "merc'her", 'yaou', 'gwener', 'sadorn')), ('abmon', ('Gen ', "C'hw", 'Meu ', 'Ebr ', 'Mae ', 'Eve ', 'Gou ', 'Eos ', 'Gwe ', 'Her ', 'Du ', 'Ker ')), ('mon', ('Genver', "C'hwevrer", 'Meurzh', 'Ebrel', 'Mae', 'Mezheven', 'Gouere', 'Eost', 'Gwengolo', 'Here', 'Du', 'Kerzu')), ('d_t_fmt', "D'ar %A %d a viz %B %Y"), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%Ie%M:%S %p'), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('brx_IN', [('abday', ('रबि', 'सम', 'मंगल', 'बुद', 'बिसथि', 'सुखुर', 'सुनि')), ('day', ('रबिबार', 'सोबार', 'मंगलबार', 'बुदबार', 'बिसथिबार', 'सुखुरबार', 'सुनिबार')), ('abmon', ('जानुवारी', 'फेब्रुवारी', 'मार्स', 'एप्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र')), ('mon', ('जानुवारी', 'फेब्रुवारी', 'मार्स', 'एप्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(नंगौ|[yY])'), ('noexpr', '^(नङा|[nN])')]), ('bs_BA', [('abday', ('Ned', 'Pon', 'Uto', 'Sri', 'Čet', 'Pet', 'Sub')), ('day', ('Nedjelja', 'Ponedjeljak', 'Utorak', 'Srijeda', 'Četvrtak', 'Petak', 'Subota')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec')), ('mon', ('Januar', 'Februar', 'Mart', 'April', 'Maj', 'Juni', 'Juli', 'August', 'Septembar', 'Oktobar', 'Novembar', 'Decembar')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[dDyY]*.'), ('noexpr', '^[nN]*.')]), ('byn_ER', [('abday', ('ሰ/ቅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ', 'ኣምድ', 'ኣርብ', 'ሰ/ሽ')), ('day', ('ሰንበር ቅዳዅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ ወሪ ለብዋ', 'ኣምድ', 'ኣርብ', 'ሰንበር ሽጓዅ')), ('abmon', ('ልደት', 'ካብኽ', 'ክብላ', 'ፋጅኺ', 'ክቢቅ', 'ም/ት', 'ኰር', 'ማርያ', 'ያኸኒ', 'መተሉ', 'ም/ም', 'ተሕሳ')), ('mon', ('ልደትሪ', 'ካብኽብቲ', 'ክብላ', 'ፋጅኺሪ', 'ክቢቅሪ', 'ምኪኤል ትጓ̅ኒሪ', 'ኰርኩ', 'ማርያም ትሪ', 'ያኸኒ መሳቅለሪ', 'መተሉ', 'ምኪኤል መሽወሪ', 'ተሕሳስሪ')), ('d_t_fmt', '%A፡ %B %e ግርጋ %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ca_AD', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_ES', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_FR', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_IT', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('cmn_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 (%A) %H點%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H點%M分%S秒'), ('t_fmt_ampm', '%p %I點%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN不否]')]), ('crh_UA', [('abday', ('Baz', 'Ber', 'Sal', 'Çar', 'Caq', 'Cum', 'Cer')), ('day', ('Bazar', 'Bazarertesi', 'Salı', 'Çarşembe', 'Cumaaqşamı', 'Cuma', 'Cumaertesi')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('Yanvar', 'Fevral', 'Mart', 'Aprel', 'Mayıs', 'İyun', 'İyul', 'Avgust', 'Sentâbr', 'Oktâbr', 'Noyabr', 'Dekabr')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('cs_CZ', [('abday', ('Ne', 'Po', 'Út', 'St', 'Čt', 'Pá', 'So')), ('day', ('Neděle', 'Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota')), ('abmon', ('led', 'úno', 'bře', 'dub', 'kvě', 'čen', 'čec', 'srp', 'zář', 'říj', 'lis', 'pro')), ('mon', ('leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec')), ('d_t_fmt', '%a\xa0%-d.\xa0%B\xa0%Y,\xa0%H:%M:%S\xa0%Z'), ('d_fmt', '%-d.%-m.%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S'), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[aAyY].*'), ('noexpr', '^[nN].*')]), ('csb_PL', [('abday', ('nie', 'pòn', 'wtó', 'str', 'czw', 'pią', 'sob')), ('day', ('niedzela', 'pòniedzôłk', 'wtórk', 'strzoda', 'czwiôrtk', 'piątk', 'sobòta')), ('abmon', ('stë', 'gro', 'stm', 'łżë', 'môj', 'cze', 'lëp', 'zél', 'séw', 'ruj', 'lës', 'gòd')), ('mon', ('stëcznik', 'gromicznik', 'strumiannik', 'łżëkwiôt', 'môj', 'czerwińc', 'lëpinc', 'zélnik', 'séwnik', 'rujan', 'lëstopadnik', 'gòdnik')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[JjTtYy].*'), ('noexpr', '^[nN].*')]), ('cv_RU', [('abday', ('vr', 'tn', 'yt', 'jn', 'kş', 'er', 'šm')), ('day', ('vyrsarnikun', 'tuntikun', 'ytlarikun', 'junkun', 'kĕşnernikun', 'ernekun', 'šămatkun')), ('abmon', ('KĂR', 'NAR', 'PUŠ', 'AKA', 'ŞU', 'ŞĔR', 'UTĂ', 'ŞUR', 'AVĂ', 'JUP', 'CÜK', 'RAŠ')), ('mon', ('kărlac', 'narăs', 'puš', 'aka', 'şu', 'şĕrtme', 'ută', 'şurla', 'avăn', 'jupa', 'cük', 'raštav')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('cy_GB', [('abday', ('Sul', 'Llu', 'Maw', 'Mer', 'Iau', 'Gwe', 'Sad')), ('day', ('Sul', 'Llun', 'Mawrth', 'Mercher', 'Iau', 'Gwener', 'Sadwrn')), ('abmon', ('Ion', 'Chw', 'Maw', 'Ebr', 'Mai', 'Meh', 'Gor', 'Aws', 'Med', 'Hyd', 'Tach', 'Rha')), ('mon', ('Ionawr', 'Chwefror', 'Mawrth', 'Ebrill', 'Mai', 'Mehefin', 'Gorffennaf', 'Awst', 'Medi', 'Hydref', 'Tachwedd', 'Rhagfyr')), ('d_t_fmt', 'Dydd %A %d mis %B %Y %T %Z'), ('d_fmt', '%d.%m.%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[iItTyY].*'), ('noexpr', '^[nN].*')]), ('da_DK', [('abday', ('søn', 'man', 'tir', 'ons', 'tor', 'fre', 'lør')), ('day', ('søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1JjYy].*'), ('noexpr', '^[0Nn].*')]), ('de_AT', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jän', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_BE', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_CH', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', "'"), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_DE', [('abday', ('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_LU', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('doi_IN', [('abday', ('ऐत ', 'सोम ', 'मंगल ', 'बुध ', 'बीर ', 'शुक्कर ', 'श्नीचर ')), ('day', ('ऐतबार ', 'सोमबार ', 'मंगलबर ', 'बुधबार ', 'बीरबार ', 'शुक्करबार ', 'श्नीचरबार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(ऑह|[yY])'), ('noexpr', '^(ना|[nN])')]), ('dv_MV', [('abday', ('އާދީއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު')), ('day', ('އާދީއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު')), ('abmon', ('ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރޗް', 'އެޕްރީލް', 'މެއި', 'ޖޫން', 'ޖުލައި', 'އޮގަސްޓް', 'ސެޕްޓެންބަރ', 'އޮކްޓޫބަރ', 'ނޮވެންބަރ', 'ޑިސެންބަރ')), ('mon', ('ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރޗް', 'އެޕްރީލް', 'މެއި', 'ޖޫން', 'ޖުލައި', 'އޮގަސްޓް', 'ސެޕްޓެންބަރ', 'އޮކްޓޫބަރ', 'ނޮވެންބަރ', 'ޑިސެންބަރ')), ('d_t_fmt', '%Z %H:%M:%S %Y %b %d %a'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%P %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('dz_BT', [('abday', ('ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་', 'ཉི་')), ('day', ('གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་', 'གཟའ་ཉི་མ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('el_CY', [('abday', ('Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ')), ('day', ('Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο')), ('abmon', ('Ιαν', 'Φεβ', 'Μάρ', 'Απρ', 'Μάι', 'Ιούν', 'Ιούλ', 'Αύγ', 'Σεπ', 'Οκτ', 'Νοέ', 'Δεκ')), ('mon', ('Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάιος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[νΝyY].*'), ('noexpr', '^[οΟnN].*')]), ('el_GR', [('abday', ('Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ')), ('day', ('Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο')), ('abmon', ('Ιαν', 'Φεβ', 'Μάρ', 'Απρ', 'Μάι', 'Ιούν', 'Ιούλ', 'Αύγ', 'Σεπ', 'Οκτ', 'Νοέ', 'Δεκ')), ('mon', ('Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάιος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[νΝyY].*'), ('noexpr', '^[οΟnN].*')]), ('en_AG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_AU', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_BW', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_CA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYoO].*'), ('noexpr', '^[nN].*')]), ('en_DK', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%Y-%m-%dT%T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1JjsSyYoO].*'), ('noexpr', '^[0nN].*')]), ('en_GB', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_HK', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A, %B %d, %Y %p%I:%M:%S %Z'), ('d_fmt', '%A, %B %d, %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%p%I:%M:%S %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_IE', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_IN', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_NG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_NZ', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_PH', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A, %d %B, %Y %I:%M:%S %p %Z'), ('d_fmt', '%A, %d %B, %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_SG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_US', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_ZA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_ZM', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE].*'), ('noexpr', '^[nNaA].*')]), ('en_ZW', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('es_AR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_BO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CL', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CU', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_DO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_EC', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_ES', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_GT', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_HN', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_MX', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', '\u2009'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_NI', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PA', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PE', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PY', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_SV', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_US', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_UY', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_VE', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('et_EE', [('abday', ('P', 'E', 'T', 'K', 'N', 'R', 'L')), ('day', ('pühapäev', 'esmaspäev', 'teisipäev', 'kolmapäev', 'neljapäev', 'reede', 'laupäev')), ('abmon', ('jaan ', 'veebr', 'märts', 'apr ', 'mai ', 'juuni', 'juuli', 'aug ', 'sept ', 'okt ', 'nov ', 'dets ')), ('mon', ('jaanuar', 'veebruar', 'märts', 'aprill', 'mai', 'juuni', 'juuli', 'august', 'september', 'oktoober', 'november', 'detsember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[EeNn].*')]), ('eu_ES', [('abday', ('ig.', 'al.', 'ar.', 'az.', 'og.', 'or.', 'lr.')), ('day', ('igandea', 'astelehena', 'asteartea', 'asteazkena', 'osteguna', 'ostirala', 'larunbata')), ('abmon', ('urt', 'ots', 'mar', 'api', 'mai', 'eka', 'uzt', 'abu', 'ira', 'urr', 'aza', 'abe')), ('mon', ('urtarrila', 'otsaila', 'martxoa', 'apirila', 'maiatza', 'ekaina', 'uztaila', 'abuztua', 'iraila', 'urria', 'azaroa', 'abendua')), ('d_t_fmt', '%y-%m-%d %T %Z'), ('d_fmt', '%a, %Y.eko %bren %da'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[bBsSyY].*'), ('noexpr', '^[eEnN].*')]), ('fa_IR', [('abday', ('یکشنبه', 'دوشنبه', 'سه\u200cشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه')), ('day', ('یکشنبه', 'دوشنبه', 'سه\u200cشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه')), ('abmon', ('ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اكتبر', 'نوامبر', 'دسامبر')), ('mon', ('ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اكتبر', 'نوامبر', 'دسامبر')), ('d_t_fmt', '\u202b%A %Oe %B %Oy، %OH:%OM:%OS\u202c'), ('d_fmt', '%Oy/%Om/%Od'), ('t_fmt', '%OH:%OM:%OS'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYآبHf].*'), ('noexpr', '^[nNخنok].*')]), ('ff_SN', [('abday', ('dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi')), ('day', ('dewo', 'aaɓnde', 'mawbaare', 'njeslaare', 'naasaande', 'mawnde', 'hoore-biir')), ('abmon', ('sii', 'col', 'mbo', 'see', 'duu', 'kor', 'mor', 'juk', 'slt', 'yar', 'jol', 'bow')), ('mon', ('siilo', 'colte', 'mbooy', 'seeɗto', 'duujal', 'korse', 'morso', 'juko', 'siilto', 'yarkomaa', 'jolal', 'bowte')), ('d_t_fmt', '%a %d %b %Y %R %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%R'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYeE].*'), ('noexpr', '^[nNaA].*')]), ('fi_FI', [('abday', ('su', 'ma', 'ti', 'ke', 'to', 'pe', 'la')), ('day', ('sunnuntai', 'maanantai', 'tiistai', 'keskiviikko', 'torstai', 'perjantai', 'lauantai')), ('abmon', ('tammi', 'helmi', 'maalis', 'huhti', 'touko', 'kesä', 'heinä', 'elo', 'syys', 'loka', 'marras', 'joulu')), ('mon', ('tammikuu', 'helmikuu', 'maaliskuu', 'huhtikuu', 'toukokuu', 'kesäkuu', 'heinäkuu', 'elokuu', 'syyskuu', 'lokakuu', 'marraskuu', 'joulukuu')), ('d_t_fmt', '%a %e. %Bta %Y %H.%M.%S'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%H.%M.%S'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[KkYy].*'), ('noexpr', '^[EeNn].*')]), ('fil_PH', [('abday', ('Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab')), ('day', ('Linggo', 'Lunes', 'Martes', 'Miyerkoles', 'Huwebes', 'Biyernes', 'Sabado')), ('abmon', ('Ene', 'Peb', 'Mar', 'Abr', 'May', 'Hun', 'Hul', 'Ago', 'Sep', 'Okt', 'Nob', 'Dis')), ('mon', ('Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Septiyembre', 'Oktubre', 'Nobiyembre', 'Disyembre')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '[oOyY].*'), ('noexpr', '[hHnN].*')]), ('fo_FO', [('abday', ('sun', 'mán', 'týs', 'mik', 'hós', 'frí', 'ley')), ('day', ('sunnudagur', 'mánadagur', 'týsdagur', 'mikudagur', 'hósdagur', 'fríggjadagur', 'leygardagur')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des')), ('mon', ('januar', 'februar', 'mars', 'apríl', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[Nn].*')]), ('fr_BE', [('abday', ('dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam')), ('day', ('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi')), ('abmon', ('jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc')), ('mon', ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[oOjJyY1].*'), ('noexpr', '^[nN0].*')]), ('fr_CA', [('abday', ('dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam')), ('day', ('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi')), ('abmon', ('jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc')), ('mon', ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('fr_CH', [('abday', ('dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam')), ('day', ('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi')), ('abmon', ('jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc')), ('mon', ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d. %m. %y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', "'"), ('yesexpr', '^[OojJsSyY].*'), ('noexpr', '^[nN].*')]), ('fr_FR', [('abday', ('dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.')), ('day', ('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi')), ('abmon', ('janv.', 'févr.', 'mars', 'avril', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.')), ('mon', ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('fr_LU', [('abday', ('dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam')), ('day', ('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi')), ('abmon', ('jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc')), ('mon', ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('fur_IT', [('abday', ('Dom', 'Lun', 'Mar', 'Mia', 'Joi', 'Vin', 'Sab')), ('day', ('Domenie', 'Lunis', 'Martars', 'Miarcus', 'Joibe', 'Vinars', 'Sabide')), ('abmon', ('Zen', 'Fev', 'Mar', 'Avr', 'Mai', 'Jug', 'Lui', 'Avo', 'Set', 'Otu', 'Nov', 'Dec')), ('mon', ('Zenâr', 'Fevrâr', 'Març', 'Avrîl', 'Mai', 'Jugn', 'Lui', 'Avost', 'Setembar', 'Otubar', 'Novembar', 'Decembar')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d. %m. %y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSjJoOyY].*'), ('noexpr', '^[nN].*')]), ('fy_DE', [('abday', ('Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd')), ('day', ('Sinndag', 'Mondag', 'Dingsdag', 'Meddwäakj', 'Donnadag', 'Friedag', 'Sinnowend')), ('abmon', ('Jan', 'Feb', 'Moz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Now', 'Dez')), ('mon', ('Jaunuwoa', 'Februwoa', 'Moaz', 'Aprell', 'Mai', 'Juni', 'Juli', 'August', 'Septamba', 'Oktoba', 'Nowamba', 'Dezamba')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('fy_NL', [('abday', ('Sn', 'Mo', 'Ti', 'Wo', 'To', 'Fr', 'Sn')), ('day', ('Snein', 'Moandei', 'Tiisdei', 'Woansdei', 'Tongersdei', 'Freed', 'Sneon')), ('abmon', ('Jan', 'Feb', 'Maa', 'Apr', 'Maa', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Janaris', 'Febrewaris', 'Maart', 'April', 'Maaie', 'Juny', 'July', 'Augustus', 'Septimber', 'Oktober', 'Novimber', 'Desimber')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('ga_IE', [('abday', ('Domh', 'Luan', 'Máirt', 'Céad', 'Déar', 'Aoine', 'Sath')), ('day', ('Dé Domhnaigh', 'Dé Luain', 'Dé Máirt', 'Dé Céadaoin', 'Déardaoin', 'Dé hAoine', 'Dé Sathairn')), ('abmon', ('Ean', 'Feabh', 'Márta', 'Aib', 'Beal', 'Meith', 'Iúil', 'Lún', 'MFómh', 'DFómh', 'Samh', 'Noll')), ('mon', ('Eanáir', 'Feabhra', 'Márta', 'Aibreán', 'Bealtaine', 'Meitheamh', 'Iúil', 'Lúnasa', 'Meán Fómhair', 'Deireadh Fómhair', 'Samhain', 'Nollaig')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[tTyY].*'), ('noexpr', '^[nN].*')]), ('gd_GB', [('abday', ('DiD', 'DiL', 'DiM', 'DiC', 'Dia', 'Dih', 'DiS')), ('day', ('DiDòmhnaich', 'DiLuain', 'DiMàirt', 'DiCiadain', 'DiarDaoin', 'DihAoine', 'DiSathairne')), ('abmon', ('Faoi', 'Gearr', 'Màrt', 'Gibl', 'Mhàrt', 'Ògmh', 'Iuch', 'Lùna', 'Sult', 'Dàmh', 'Samh', 'Dùbh')), ('mon', ('Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[tTyY].*'), ('noexpr', '^[cCnN].*')]), ('gez_ER', [('abday', ('እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ')), ('day', ('እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚት')), ('abmon', ('ጠሐረ', 'ከተተ', 'መገበ', 'አኀዘ', 'ግንባ', 'ሠንየ', 'ሐመለ', 'ነሐሰ', 'ከረመ', 'ጠቀመ', 'ኀደረ', 'ኀሠሠ')), ('mon', ('ጠሐረ', 'ከተተ', 'መገበ', 'አኀዘ', 'ግንባት', 'ሠንየ', 'ሐመለ', 'ነሐሰ', 'ከረመ', 'ጠቀመ', 'ኀደረ', 'ኀሠሠ')), ('d_t_fmt', '%A፥%B፡%e፡መዓልት፡%Y፡%r፡%Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X፡%p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('gez_ET', [('abday', ('እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚ')), ('day', ('እኁድ', 'ሰኑይ', 'ሠሉስ', 'ራብዕ', 'ሐሙስ', 'ዓርበ', 'ቀዳሚት')), ('abmon', ('ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም')), ('mon', ('ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር')), ('d_t_fmt', '%A፥%B፡%e፡መዓልት፡%Y፡%r፡%Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X፡%p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('gl_ES', [('abday', ('Dom', 'Lun', 'Mar', 'Mér', 'Xov', 'Ven', 'Sáb')), ('day', ('Domingo', 'Luns', 'Martes', 'Mércores', 'Xoves', 'Venres', 'Sábado')), ('abmon', ('Xan', 'Feb', 'Mar', 'Abr', 'Mai', 'Xuñ', 'Xul', 'Ago', 'Set', 'Out', 'Nov', 'Dec')), ('mon', ('Xaneiro', 'Febreiro', 'Marzo', 'Abril', 'Maio', 'Xuño', 'Xullo', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Decembro')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('gu_IN', [('abday', ('રવિ', 'સોમ', 'મંગળ', 'બુધ', 'ગુરુ', 'શુક્ર', 'શનિ')), ('day', ('રવિવાર', 'સોમવાર', 'મંગળવાર', 'બુધવાર', 'ગુરુવાર', 'શુક્રવાર', 'શનિવાર')), ('abmon', ('જાન', 'ફેબ', 'માર', 'એપ્ર', 'મે', 'જુન', 'જુલ', 'ઓગ', 'સપ્ટ', 'ઓક્ટ', 'નોવ', 'ડિસ')), ('mon', ('જાન્યુઆરી', 'ફેબ્રુઆરી', 'માર્ચ', 'એપ્રિલ', 'મે', 'જુન', 'જુલાઇ', 'ઓગસ્ટ', 'સપ્ટેમ્બર', 'ઓક્ટોબર', 'નવેમ્બર', 'ડિસેમ્બર')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYહ]'), ('noexpr', '^[nNન]')]), ('gv_GB', [('abday', ('Jed', 'Jel', 'Jem', 'Jerc', 'Jerd', 'Jeh', 'Jes')), ('day', ('Jedoonee', 'Jelhein', 'Jemayrt', 'Jercean', 'Jerdein', 'Jeheiney', 'Jesarn')), ('abmon', ('J-guer', 'T-arree', 'Mayrnt', 'Avrril', 'Boaldyn', 'M-souree', 'J-souree', 'Luanistyn', 'M-fouyir', 'J-fouyir', 'M.Houney', 'M.Nollick')), ('mon', ('Jerrey-geuree', 'Toshiaght-arree', 'Mayrnt', 'Averil', 'Boaldyn', 'Mean-souree', 'Jerrey-souree', 'Luanistyn', 'Mean-fouyir', 'Jerrey-fouyir', 'Mee Houney', 'Mee ny Nollick')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ha_NG', [('abday', ('Lah', 'Lit', 'Tal', 'Lar', 'Alh', 'Jum', 'Asa')), ('day', ('Lahadi', 'Litini', 'Talata', 'Laraba', 'Alhamis', "Juma'a", 'Asabar')), ('abmon', ('Jan', 'Fab', 'Mar', 'Afr', 'May', 'Yun', 'Yul', 'Agu', 'Sat', 'Okt', 'Nuw', 'Dis')), ('mon', ('Janairu', 'Fabrairu', 'Maris', 'Afrilu', 'Mayu', 'Yuni', 'Yuli', 'Agusta', 'Satumba', 'Oktoba', 'Nuwamba', 'Disamba')), ('d_t_fmt', 'ranar %A, %d ga %B cikin %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[TtiIYy].*'), ('noexpr', '^[bBaAnN].*')]), ('hak_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('禮拜日', '禮拜一', '禮拜二', '禮拜三', '禮拜四', '禮拜五', '禮拜六')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 (%A) %H點%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H點%M分%S秒'), ('t_fmt_ampm', '%p %I點%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY係]'), ('noexpr', '^[nN毋]')]), ('he_IL', [('abday', ("א'", "ב'", "ג'", "ד'", "ה'", "ו'", "ש'")), ('day', ('ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת')), ('abmon', ('ינו', 'פבר', 'מרץ', 'אפר', 'מאי', 'יונ', 'יול', 'אוג', 'ספט', 'אוק', 'נוב', 'דצמ')), ('mon', ('ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר')), ('d_t_fmt', '%Z %H:%M:%S %Y %b %d %a'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %P'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Yyכ].*'), ('noexpr', '^[Nnל].*')]), ('hi_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'गुरु ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'गुरुवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('hne_IN', [('abday', ('इत ', 'सोम ', 'मंग ', 'बुध ', 'बिर ', 'सुक', 'सनि')), ('day', ('इतवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'बिरसपत ', 'सुकरवार ', 'सनिवार ')), ('abmon', ('जन', 'फर', 'मार्च', 'अप', 'मई', 'जून', 'जुला', 'अग', 'सित', 'अकटू', 'नव', 'दिस')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अपरेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितमबर', 'अकटूबर', 'नवमबर', 'दिसमबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[हवyY]'), ('noexpr', '^[नइnN]')]), ('hr_HR', [('abday', ('Ned', 'Pon', 'Uto', 'Sri', 'Čet', 'Pet', 'Sub')), ('day', ('Nedjelja', 'Ponedjeljak', 'Utorak', 'Srijeda', 'Četvrtak', 'Petak', 'Subota')), ('abmon', ('Sij', 'Vel', 'Ožu', 'Tra', 'Svi', 'Lip', 'Srp', 'Kol', 'Ruj', 'Lis', 'Stu', 'Pro')), ('mon', ('Siječanj', 'Veljača', 'Ožujak', 'Travanj', 'Svibanj', 'Lipanj', 'Srpanj', 'Kolovoz', 'Rujan', 'Listopad', 'Studeni', 'Prosinac')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[dDyY].*'), ('noexpr', '^[nN].*')]), ('hsb_DE', [('abday', ('Nj', 'Pó', 'Wu', 'Sr', 'Št', 'Pj', 'So')), ('day', ('Njedźela', 'Póndźela', 'Wutora', 'Srjeda', 'Štvórtk', 'Pjatk', 'Sobota')), ('abmon', ('Jan', 'Feb', 'Měr', 'Apr', 'Mej', 'Jun', 'Jul', 'Awg', 'Sep', 'Okt', 'Now', 'Dec')), ('mon', ('Januar', 'Februar', 'Měrc', 'Apryl', 'Meja', 'Junij', 'Julij', 'Awgust', 'September', 'Oktober', 'Nowember', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[hHyY].*'), ('noexpr', '^[nN].*')]), ('ht_HT', [('abday', ('dim', 'len ', 'mad', 'mèk', 'jed', 'van', 'sam')), ('day', ('dimanch', 'lendi ', 'madi', 'mèkredi', 'jedi', 'vandredi', 'samdi')), ('abmon', ('jan', 'fev', 'mas', 'avr', 'me', 'jen', 'jiy', 'out', 'sep', 'okt', 'nov', 'des')), ('mon', ('janvye', 'fevriye', 'mas', 'avril', 'me', 'jen', 'jiyè', 'out', 'septanm', 'oktòb', 'novanm', 'desanm')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[wWoOyY].*'), ('noexpr', '^[nN].*')]), ('hu_HU', [('abday', ('v', 'h', 'k', 'sze', 'cs', 'p', 'szo')), ('day', ('vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat')), ('abmon', ('jan', 'febr', 'márc', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec')), ('mon', ('január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december')), ('d_t_fmt', '%Y. %b. %e., %A, %H.%M.%S %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%H.%M.%S'), ('t_fmt_ampm', '%H.%M.%S'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[IiYy].*'), ('noexpr', '^[nN].*')]), ('hy_AM', [('abday', ('Կրկ', 'Երկ', 'Երք', 'Չրք', 'Հնգ', 'Ուր', 'Շբթ')), ('day', ('Կիրակի', 'Երկուշաբթի', 'Երեքշաբթի', 'Չորեքշաբթի', 'Հինգշաբթի', 'Ուրբաթ', 'Շաբաթ')), ('abmon', ('Հնվ', 'Փտր', 'Մար', 'Ապր', 'Մայ', 'Հնս', 'Հլս', 'Օգս', 'Սեպ', 'Հոկ', 'Նմբ', 'Դեկ')), ('mon', ('Հունվարի', 'Փետրվարի', 'Մարտի', 'Ապրիլի', 'Մայիսի', 'Հունիսի', 'Հուլիսի', 'Օգոստոսի', 'Սեպտեմբերի', 'Հոկտեմբերի', 'Նոյեմբերի', 'Դեկտեմբերի')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYsSաԱ]'), ('noexpr', '^[nNոՈ]')]), ('ia_FR', [('abday', ('dom', 'lun', 'mar', 'mer', 'jov', 'ven', 'sab')), ('day', ('dominica', 'lunedi', 'martedi', 'mercuridi', 'jovedi', 'venerdi', 'sabbato')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')), ('mon', ('januario', 'februario', 'martio', 'april', 'maio', 'junio', 'julio', 'augusto', 'septembre', 'octobre', 'novembre', 'decembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('id_ID', [('abday', ('Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab')), ('day', ('Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu')), ('abmon', ('Jan', 'Peb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Januari', 'Pebruari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yY].*'), ('noexpr', '^[tTnN].*')]), ('ig_NG', [('abday', ('sọn', 'mọn', 'tuz', 'wen', 'tọs', 'fra', 'sat')), ('day', ('sọnde', 'mọnde', 'tuzde', 'wenzde', 'tọsde', 'fraịde', 'satọde')), ('abmon', ('jen', 'feb', 'maa', 'epr', 'mee', 'juu', 'jul', 'ọgọ', 'sep', 'ọkt', 'nọv', 'dis')), ('mon', ('jenụwarị', 'febụrụwarị', 'maachị', 'epreel', 'mee', 'juun', 'julaị', 'ọgọstụ', 'septemba', 'ọktoba', 'nọvemba', 'disemba')), ('d_t_fmt', '%A, %d %B %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[EeIiYy].*'), ('noexpr', '^[0MmNn].*')]), ('ik_CA', [('abday', ('Min', 'Sav', 'Ila', 'Qit', 'Sis', 'Tal', 'Maq')), ('day', ('Minġuiqsioiq', 'Savałłiq', 'Ilaqtchiioiq', 'Qitchiioiq', 'Sisamiioiq', 'Tallimmiioiq', 'Maqinġuoiq')), ('abmon', ('Sñt', 'Sñs', 'Pan', 'Qil', 'Sup', 'Iġñ', 'Itc', 'Tiñ', 'Ami', 'Sik', 'Nip', 'Siq')), ('mon', ('Siqiññaatchiaq', 'Siqiññaasrugruk', 'Paniqsiqsiivik', 'Qilġich Tatqiat', 'Suppivik', 'Iġñivik', 'Itchavik', 'Tiññivik', 'Amiġaiqsivik', 'Sikkuvik', 'Nippivik', 'Siqiñġiḷaq')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '[yYiIaA].*'), ('noexpr', '[nNqQ].*')]), ('is_IS', [('abday', ('sun', 'mán', 'þri', 'mið', 'fim', 'fös', 'lau')), ('day', ('sunnudagur', 'mánudagur', 'þriðjudagur', 'miðvikudagur', 'fimmtudagur', 'föstudagur', 'laugardagur')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maí', 'jún', 'júl', 'ágú', 'sep', 'okt', 'nóv', 'des')), ('mon', ('janúar', 'febrúar', 'mars', 'apríl', 'maí', 'júní', 'júlí', 'ágúst', 'september', 'október', 'nóvember', 'desember')), ('d_t_fmt', '%a %e.%b %Y, %T %Z'), ('d_fmt', '%a %e.%b %Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('it_CH', [('abday', ('dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab')), ('day', ('domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato')), ('abmon', ('gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic')), ('mon', ('gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d. %m. %y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', "'"), ('yesexpr', '^[sSjJoOyY].*'), ('noexpr', '^[nN].*')]), ('it_IT', [('abday', ('dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab')), ('day', ('domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato')), ('abmon', ('gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic')), ('mon', ('gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('iu_CA', [('abday', ('ᓈ', 'ᓇ', 'ᓕ', 'ᐱ', 'ᕿ', 'ᐅ', 'ᓯ')), ('day', ('ᓈᑦᑎᖑᔭᕐᕕᒃ', 'ᓇᒡᒐᔾᔭᐅ', 'ᓇᒡᒐᔾᔭᐅᓕᖅᑭᑦ', 'ᐱᖓᓲᓕᖅᓯᐅᑦ', 'ᕿᑎᖅᑰᑦ', 'ᐅᓪᓗᕈᓘᑐᐃᓇᖅ', 'ᓯᕙᑖᕕᒃ')), ('abmon', ('ᔮᓄ', 'ᕕᕗ', 'ᒪᔅ', 'ᐃᐳ', 'ᒪᐃ', 'ᔪᓂ', 'ᔪᓚ', 'ᐊᒋ', 'ᓯᑎ', 'ᐊᑦ', 'ᓄᕕ', 'ᑎᓯ')), ('mon', ('ᔮᓄᐊᓕ', 'ᕕᕗᐊᓕ', 'ᒪᔅᓯ', 'ᐃᐳᓗ', 'ᒪᐃ', 'ᔪᓂ', 'ᔪᓚᐃ', 'ᐊᒋᓯ', 'ᓯᑎᕙ', 'ᐊᑦᑐᕙ', 'ᓄᕕᕙ', 'ᑎᓯᕝᕙ')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '[yYsS].*'), ('noexpr', '[nN].*')]), ('iw_IL', [('abday', ("א'", "ב'", "ג'", "ד'", "ה'", "ו'", "ש'")), ('day', ('ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת')), ('abmon', ('ינו', 'פבר', 'מרץ', 'אפר', 'מאי', 'יונ', 'יול', 'אוג', 'ספט', 'אוק', 'נוב', 'דצמ')), ('mon', ('ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר')), ('d_t_fmt', '%Z %H:%M:%S %Y %b %d %a'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %P'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Yyכ].*'), ('noexpr', '^[Nnל].*')]), ('ja_JP', [('abday', ('日', '月', '火', '水', '木', '金', '土')), ('day', ('日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月')), ('d_t_fmt', '%Y年%m月%d日 %H時%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H時%M分%S秒'), ('t_fmt_ampm', '%p%I時%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^([yYyY]|はい|ハイ)'), ('noexpr', '^([nNnN]|いいえ|イイエ)')]), ('ka_GE', [('abday', ('კვი', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ')), ('day', ('კვირა', 'ორშაბათი', 'სამშაბათი', 'ოთხშაბათი', 'ხუთშაბათი', 'პარასკევი', 'შაბათი')), ('abmon', ('იან', 'თებ', 'მარ', 'აპრ', 'მაი', 'ივნ', 'ივლ', 'აგვ', 'სექ', 'ოქტ', 'ნოე', 'დეკ')), ('mon', ('იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი')), ('d_t_fmt', '%Y წლის %d %B, %T %Z'), ('d_fmt', '%m/%d/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1yYkKxXხ].*'), ('noexpr', '^[0nNaAა].*')]), ('kk_KZ', [('abday', ('Жк', 'Дс', 'Сс', 'Ср', 'Бс', 'Жм', 'Сн')), ('day', ('Жексенбі', 'Дүйсенбі', 'Сейсенбі', 'Сәрсенбі', 'Бейсенбі', 'Жұма', 'Сенбі')), ('abmon', ('Қаң', 'Ақп', 'Нау', 'Сәу', 'Мам', 'Мау', 'Шіл', 'Там', 'Қыр', 'Қаз', 'Қар', 'Жел')), ('mon', ('Қаңтар', 'Ақпан', 'Наурыз', 'Сәуір', 'Мамыр', 'Маусым', 'Шілде', 'Тамыз', 'Қыркүйек', 'Қазан', 'Қараша', 'Желтоқсан')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[ИиYy].*'), ('noexpr', '^[ЖжNn].*')]), ('kl_GL', [('abday', ('sab', 'ata', 'mar', 'pin', 'sis', 'tal', 'arf')), ('day', ('sabaat', 'ataasinngorneq', 'marlunngorneq', 'pingasunngorneq', 'sisamanngorneq', 'tallimanngorneq', 'arfininngorneq')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'martsi', 'aprili', 'maji', 'juni', 'juli', 'augustusi', 'septemberi', 'oktoberi', 'novemberi', 'decemberi')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d %b %Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[JjYyAa].*'), ('noexpr', '^[Nn].*')]), ('km_KH', [('abday', ('អា', 'ច', 'អ', 'ពុ', 'ព្រ', 'សុ', 'ស')), ('day', ('ថ្ងៃ\u200bអាទិត្យ', 'ថ្ងៃ\u200bច័ន្ទ', 'ថ្ងៃ\u200bអង្គារ', 'ថ្ងៃ\u200bពុធ', 'ថ្ងៃ\u200bព្រហស្បតិ៍', 'ថ្ងៃ\u200bសុក្រ', 'ថ្ងៃ\u200bសៅរ៍')), ('abmon', ('១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩', '១០', '១១', '១២')), ('mon', ('មករា', 'កុម្ភៈ', 'មិនា', 'មេសា', 'ឧសភា', 'មិថុនា', 'កក្កដា', 'សីហា', 'កញ្ញា', 'តុលា', 'វិច្ឆិកា', 'ធ្នូ')), ('d_t_fmt', '%A ថ្ងៃ %e ខែ %B ឆ្នាំ %Y, %H ម៉ោង m នាទី %S វិនាទី\u200b'), ('d_fmt', '%e %B %Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]([eE][sS])?'), ('noexpr', '^[nN][oO]?')]), ('kn_IN', [('abday', ('ರ', 'ಸೋ', 'ಮಂ', 'ಬು', 'ಗು', 'ಶು', 'ಶ')), ('day', ('ರವಿವಾರ', 'ಸೋಮವಾರ', 'ಮಂಗಳವಾರ', 'ಬುಧವಾರ', 'ಗುರುವಾರ', 'ಶುಕ್ರವಾರ', 'ಶನಿವಾರ')), ('abmon', ('ಜ', 'ಫೆ', 'ಮಾ', 'ಏ', 'ಮೇ', 'ಜೂ', 'ಜು', 'ಆ', 'ಸೆ', 'ಅ', 'ನ', 'ದ')), ('mon', ('ಜನವರಿ', 'ಫೆಬ್ರವರಿ', 'ಮಾರ್ಚ', 'ಏಪ್ರಿಲ್', 'ಮೇ', 'ಜೂನ್', 'ಜುಲಾಯಿ', 'ಆಗಸ್ತು', 'ಸೆಪ್ಟೆಂಬರ', 'ಅಕ್ತೂಬರ', 'ನವೆಂಬರ', 'ದಶಂಬರ')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ko_KR', [('abday', ('일', '월', '화', '수', '목', '금', '토')), ('day', ('일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일')), ('abmon', (' 1월', ' 2월', ' 3월', ' 4월', ' 5월', ' 6월', ' 7월', ' 8월', ' 9월', '10월', '11월', '12월')), ('mon', ('1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월')), ('d_t_fmt', '%x (%a) %r'), ('d_fmt', '%Y년 %m월 %d일'), ('t_fmt', '%H시 %M분 %S초'), ('t_fmt_ampm', '%p %I시 %M분 %S초'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY예]'), ('noexpr', '^[nN아]')]), ('kok_IN', [('abday', ('आयतार', 'सोमार', 'मंगळवार', 'बुधवार', 'बेरेसतार', 'शुकरार', 'शेनवार')), ('day', ('आयतार', 'सोमार', 'मंगळवार', 'बुधवार', 'बेरेसतार', 'शुकरार', 'शेनवार')), ('abmon', ('जेनवरी', 'फेब्ररी', 'मारच', 'एप्रील', 'में', 'जुन', 'जुलै', 'ओगस्ट', 'सेपटेंबर', 'ओकटोबर', 'नोवेंबर', 'दिसेंबर')), ('mon', ('जेनवरी', 'फेब्ररी', 'मारच', 'एप्रील', 'में', 'जुन', 'जुलै', 'ओगस्ट', 'सेपटेंबर', 'ओकटोबर', 'नोवेंबर', 'दिसेंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(हय|[yY])'), ('noexpr', '^(न्ही|[nN])')]), ('ks_IN', [('abday', ('آتهوار', 'ژءنتروار', 'بوءںوار', 'بودهوار', 'برىسوار', 'جمع', 'بٹوار')), ('day', ('آتهوار', 'ژءندروار', 'بوءںوار', 'بودهوار', 'برىسوار', 'جمع', 'بٹوار')), ('abmon', ('جنوری', 'فروری', 'مارچ', 'اپریل', 'مئ', 'جون', 'جُلئ', 'اگست', 'ستنبر', 'اکتوبر', 'نوںبر', 'دسنبر')), ('mon', ('جنوری', 'فروری', 'مارچ', 'اپریل', 'مئ', 'جون', 'جُلئ', 'اگست', 'ستنبر', 'اکتوبر', 'نوںبر', 'دسنبر')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[آyY].*'), ('noexpr', '^[نnN].*')]), ('ku_TR', [('abday', ('yêk', 'dus', 'sês', 'çar', 'pên', 'înî', 'sep')), ('day', ('yêksêm', 'dusêm', 'sêsêm', 'çarsêm', 'pêncsêm', 'înî', 'sept')), ('abmon', ('Çil', 'Sib', 'Ada', 'Nîs', 'Gul', 'Hez', 'Tîr', 'Teb', 'Îlo', 'Cot', 'Mij', 'Kan')), ('mon', ('Çile', 'Sibat', 'Adar', 'Nîsan', 'Gulan', 'Hezîran', 'Tîrmeh', 'Tebax', 'Îlon', 'Cotmeh', 'Mijdar', 'Kanûn')), ('d_t_fmt', '%A %d %B %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[eEdDyY].*'), ('noexpr', '^[nN].*')]), ('kw_GB', [('abday', ('Sul', 'Lun', 'Mth', 'Mhr', 'Yow', 'Gwe', 'Sad')), ('day', ('De Sul', 'De Lun', 'De Merth', 'De Merher', 'De Yow', 'De Gwener', 'De Sadorn')), ('abmon', ('Gen', 'Whe>', 'Mer', 'Ebr', 'Me', 'Evn', 'Gor', 'Est', 'Gwn', 'Hed', 'Du', 'Kev')), ('mon', ('Mys Genver', 'Mys Whevrel', 'Mys Merth', 'Mys Ebrel', 'Mys Me', 'Mys Evan', 'Mys Gortheren', 'Mye Est', 'Mys Gwyngala', 'Mys Hedra', 'Mys Du', 'Mys Kevardhu')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[eEyY].*'), ('noexpr', '^[nN].*')]), ('ky_KG', [('abday', ('жк', 'дш', 'ше', 'ша', 'бш', 'жм', 'иш')), ('day', ('жекшемби', 'дүйшөмбү', 'шейшемби', 'шаршемби', 'бейшемби', 'жума', 'ишемби')), ('abmon', ('янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек')), ('mon', ('январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[ОоYy].*'), ('noexpr', '^[ЖжNn].*')]), ('lb_LU', [('abday', ('So', 'Mé', 'Dë', 'Më', 'Do', 'Fr', 'Sa')), ('day', ('Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg')), ('abmon', ('Jan', 'Feb', 'Mäe', 'Abr', 'Mee', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'Mäerz', 'Abrëll', 'Mee', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d. %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('lg_UG', [('abday', ('Sab', 'Bal', 'Lw2', 'Lw3', 'Lw4', 'Lw5', 'Lw6')), ('day', ('Sabiiti', 'Balaza', 'Lwakubiri', 'Lwakusatu', 'Lwakuna', 'Lwakutaano', 'Lwamukaaga')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apu', 'Maa', 'Jun', 'Jul', 'Agu', 'Seb', 'Oki', 'Nov', 'Des')), ('mon', ('Janwaliyo', 'Febwaliyo', 'Marisi', 'Apuli', 'Maayi', 'Juuni', 'Julaai', 'Agusito', 'Sebuttemba', 'Okitobba', 'Novemba', 'Desemba')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('li_BE', [('abday', ('zón', 'mao', 'dae', 'goo', 'dón', 'vri', 'z\x91o')), ('day', ('zóndig', 'maondig', 'daensdig', 'goonsdig', 'dónderdig', 'vriedig', 'zaoterdig')), ('abmon', ('jan', 'fib', 'mie', 'epr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des')), ('mon', ('jannewarie', 'fibberwarie', 'miert', 'eprèl', 'meij', 'junie', 'julie', 'augustus', 'september', 'oktober', 'november', 'desember')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('li_NL', [('abday', ('zón', 'mao', 'dae', 'goo', 'dón', 'vri', 'z\x91o')), ('day', ('zóndig', 'maondig', 'daensdig', 'goonsdig', 'dónderdig', 'vriedig', 'zaoterdig')), ('abmon', ('jan', 'fib', 'mie', 'epr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des')), ('mon', ('jannewarie', 'fibberwarie', 'miert', 'eprèl', 'meij', 'junie', 'julie', 'augustus', 'september', 'oktober', 'november', 'desember')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('lij_IT', [('abday', ('dom', 'lûn', 'mar', 'mer', 'zêu', 'ven', 'sab')), ('day', ('domenega', 'lûnedì', 'martedì', 'mercUrdì', 'zêggia', 'venardì', 'sabbo')), ('abmon', ('zen', 'fev', 'mar', 'arv', 'maz', 'zûg', 'lûg', 'ago', 'set', 'ött', 'nov', 'dix')), ('mon', ('zenâ', 'fevrâ', 'marzo', 'avrî', 'mazzo', 'zûgno', 'lûggio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dixembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('lo_LA', [('abday', ('ອາ.', 'ຈ.', 'ຄ.', 'ພ.', 'ພຫ.', 'ສ.', 'ສ.')), ('day', ('ອາທິດ', 'ຈັນ', 'ອັງຄານ', 'ພຸດ', 'ພະຫັດ', 'ສຸກ', 'ເສົາ')), ('abmon', ('ມ.ກ.', 'ກ.ພ.', 'ມ.ນ.', 'ມ.ສ.', 'ພ.ພ.', 'ມິ.ຖ.', 'ກ.ລ.', 'ສ.ຫ.', 'ກ.ຍ.', 'ຕ.ລ.', 'ພ.ຈ.', 'ທ.ວ.')), ('mon', ('ມັງກອນ', 'ກຸມຟາ', 'ມີນາ', 'ເມສາ', 'ພຶດສະພາ', 'ມິຖຸນາ', 'ກໍລະກົດ', 'ສິງຫາ', 'ກັນຍາ', 'ຕຸລາ', 'ພະຈິກ', 'ທັນວາ')), ('d_t_fmt', '%a %e %b %Ey, %H:%M:%S'), ('d_fmt', '%d/%m/%Ey'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYມ]'), ('noexpr', '^[nNບ]')]), ('lt_LT', [('abday', ('Sk', 'Pr', 'An', 'Tr', 'Kt', 'Pn', 'Št')), ('day', ('Sekmadienis', 'Pirmadienis', 'Antradienis', 'Trečiadienis', 'Ketvirtadienis', 'Penktadienis', 'Šeštadienis')), ('abmon', ('Sau', 'Vas', 'Kov', 'Bal', 'Geg', 'Bir', 'Lie', 'Rgp', 'Rgs', 'Spa', 'Lap', 'Grd')), ('mon', ('sausio', 'vasario', 'kovo', 'balandžio', 'gegužės', 'birželio', 'liepos', 'rugpjūčio', 'rugsėjo', 'spalio', 'lapkričio', 'gruodžio')), ('d_t_fmt', '%Y m. %B %d d. %T'), ('d_fmt', '%Y.%m.%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[TtYy].*'), ('noexpr', '^[Nn].*')]), ('lv_LV', [('abday', ('Sv', 'P\xa0', 'O\xa0', 'T\xa0', 'C\xa0', 'Pk', 'S\xa0')), ('day', ('svētdiena', 'pirmdiena', 'otrdiena', 'trešdiena', 'ceturtdiena', 'piektdiena', 'sestdiena')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'mai', 'jūn', 'jūl', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('janvāris', 'februāris', 'marts', 'aprīlis', 'maijs', 'jūnijs', 'jūlijs', 'augusts', 'septembris', 'oktobris', 'novembris', 'decembris')), ('d_t_fmt', '%A, %Y. gada %e. %B, plkst. %H un %M'), ('d_fmt', '%Y.%m.%d.'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[Nn].*')]), ('lzh_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('週日', '週一', '週二', '週三', '週四', '週五', '週六')), ('abmon', (' 一 ', ' 二 ', ' 三 ', ' 四 ', ' 五 ', ' 六 ', ' 七 ', ' 八 ', ' 九 ', ' 十 ', '十一', '十二')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%OC%Oy年%B%Od日 (%A) %OH時%OM分%OS秒'), ('d_fmt', '%OC%Oy年%B%Od日'), ('t_fmt', '%OH時%OM分%OS秒'), ('t_fmt_ampm', '%p %OI時%OM分%OS秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN非]')]), ('mag_IN', [('abday', ('एतवार ', 'सोमार ', 'मंगर ', 'बुध ', 'बिफे ', 'सूक ', 'सनिचर ')), ('day', ('एतवार ', 'सोमार ', 'मंगर ', 'बुध ', 'बिफे ', 'सूक ', 'सनिचर ')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('mai_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'गुरु ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'गुरुवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('mg_MG', [('abday', ('lhd', 'lts', 'tlt', 'lrb', 'lkm', 'zom', 'sab')), ('day', ('alahady', 'alatsinainy', 'talata', 'alarobia', 'alakamisy', 'zoma', 'sabotsy')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'mey', 'jon', 'jol', 'aog', 'sep', 'okt', 'nov', 'des')), ('mon', ('janoary', 'febroary', 'martsa', 'aprily', 'mey', 'jona', 'jolay', 'aogositra', 'septambra', 'oktobra', 'novambra', 'desambra')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[eEyY].*'), ('noexpr', '^[tTnN].*')]), ('mhr_RU', [('abday', ('Ршр', 'Шчм', 'Кжм', 'Вгч', 'Изр', 'Кгр', 'Шмт')), ('day', ('Рушарня', 'Шочмо', 'Кушкыжмо', 'Вӱргече', 'Изарня', 'Кугарня', 'Шуматкече')), ('abmon', ('Шрк', 'Пгж', 'Ӱрн', 'Вшр', 'Ага', 'Пдш', 'Срм', 'Срл', 'Идм', 'Шыж', 'Клм', 'Тел')), ('mon', ('Шорыкйол', 'Пургыж', 'Ӱярня', 'Вӱдшор', 'Ага', 'Пеледыш', 'Сӱрем', 'Сорла', 'Идым', 'Шыжа', 'Кылме', 'Теле')), ('d_t_fmt', '%A %Y %B %d %T'), ('d_fmt', '%Y.%m.%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[ТтYy].*'), ('noexpr', '^[УуNn].*')]), ('mi_NZ', [('abday', ('Ta', 'Ma', 'Tū', 'We', 'Tāi', 'Pa', 'Hā')), ('day', ('Rātapu', 'Mane', 'Tūrei', 'Wenerei', 'Tāite', 'Paraire', 'Hātarei')), ('abmon', ('Kohi', 'Hui', 'Pou', 'Pae', 'Hara', 'Pipi', 'Hōngoi', 'Here', 'Mahu', 'Whi-nu', 'Whi-ra', 'Haki')), ('mon', ('Kohi-tātea', 'Hui-tanguru', 'Poutū-te-rangi', 'Paenga-whāwhā', 'Haratua', 'Pipiri', 'Hōngoingoi', 'Here-turi-kōkā', 'Mahuru', 'Whiringa-ā-nuku', 'Whiringa-ā-rangi', 'Hakihea')), ('d_t_fmt', 'Te %A, te %d o %B, %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[1yYāĀäÄaA].*'), ('noexpr', '^[0nNkK].*')]), ('mk_MK', [('abday', ('нед', 'пон', 'вто', 'сре', 'чет', 'пет', 'саб')), ('day', ('недела', 'понеделник', 'вторник', 'среда', 'четврток', 'петок', 'сабота')), ('abmon', ('јан', 'фев', 'мар', 'апр', 'мај', 'јун', 'јул', 'авг', 'сеп', 'окт', 'ное', 'дек')), ('mon', ('јануари', 'февруари', 'март', 'април', 'мај', 'јуни', 'јули', 'август', 'септември', 'октомври', 'ноември', 'декември')), ('d_t_fmt', '%a, %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[ДдDdYy1].*'), ('noexpr', '^[НнNn0].*')]), ('ml_IN', [('abday', ('ഞാ', 'തി', 'ചൊ', 'ബു', 'വ്യാ', 'വെ', 'ശ')), ('day', ('ഞായര്\u200d', 'തിങ്കള്\u200d', 'ചൊവ്വ', 'ബുധന്\u200d', 'വ്യാഴം', 'വെള്ളി', 'ശനി')), ('abmon', ('ജനു', 'ഫെബ്', 'മാര്\u200d', 'ഏപ്ര', 'മെ', 'ജൂണ്\u200d', 'ജൂലൈ', 'ആഗ്', 'സെപ്', 'ഒക്ടോ', 'നവം', 'ഡിസം')), ('mon', ('ജനുവരി', 'ഫെബ്രുവരി', 'മാര്\u200dച്ച്', 'ഏപ്രില്\u200d ', 'മെയ്', 'ജൂണ്\u200d', 'ജൂലൈ', 'ആഗസ്റ്റ്', 'സെപ്റ്റംബര്\u200d', 'ഒക്ടോബര്\u200d', 'നവംബര്\u200d', 'ഡിസംബര്\u200d')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[അതെyY]'), ('noexpr', '^[അല്ലnN]')]), ('mn_MN', [('abday', ('Ня', 'Да', 'Мя', 'Лх', 'Пү', 'Ба', 'Бя')), ('day', ('Ням', 'Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба')), ('abmon', ('Хул', 'Үхэ', 'Бар', 'Туу', 'Луу', 'Мог', 'Мор', 'Хон', 'Бич', 'Тах', 'Нох', 'Гах')), ('mon', ('Хулгана сарын', 'Үхэр сарын', 'Бар сарын', 'Туулай сарын', 'Луу сарын', 'Могой сарын', 'Морь сарын', 'Хонь сарын', 'Бич сарын', 'Тахиа сарын', 'Нохой сарын', 'Гахай сарын')), ('d_t_fmt', '%Y %b %d, %a %T'), ('d_fmt', '%Y.%m.%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[тТyY].*'), ('noexpr', '^[үҮnN].*')]), ('mni_IN', [('abday', ('নোং', 'নিং', 'লৈবাক', 'য়ুম', 'শগোল', 'ইরা', 'থাং')), ('day', ('নোংমাইজিং', 'নিংথৌকাবা', 'লৈবাকপোকপা', 'য়ুমশকৈশা', 'শগোলশেন', 'ইরাই', 'থাংজ')), ('abmon', ('জান', 'ফেব', 'মার', 'এপ্রি', 'মে', 'জুন', 'জুল', 'আগ', 'সেপ', 'ওক্ত', 'নবে', 'ডিস')), ('mon', ('জানুৱারি', 'ফেব্রুৱারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগষ্ট', 'সেপ্তেম্বর', 'ওক্তোবর', 'নবেম্বর', 'ডিসেম্বর')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('mr_IN', [('abday', ('रवि', 'सोम', 'मंगळ', 'बुध', 'गुरु', 'शुक्र', 'शनि')), ('day', ('रविवार', 'सोमवार', 'मंगळवार', 'बुधवार', 'गुरुवार', 'शुक्रवार', 'शनिवार')), ('abmon', ('जानेवारी', 'फेबृवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलै', 'ऑगस्ट', 'सप्टेंबर', 'ऑक्टोबर', 'नोव्हेंबर', 'डिसेंबर')), ('mon', ('जानेवारी', 'फेबृवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलै', 'ऑगस्ट', 'सप्टेंबर', 'ऑक्टोबर', 'नोव्हेंबर', 'डिसेंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(Yes|[yY])'), ('noexpr', '^(No|[nN])')]), ('ms_MY', [('abday', ('Ahd', 'Isn', 'Sel', 'Rab', 'Kha', 'Jum', 'Sab')), ('day', ('Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu')), ('abmon', ('Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogos', 'Sep', 'Okt', 'Nov', 'Dis')), ('mon', ('Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[tT]')]), ('mt_MT', [('abday', ('Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib')), ('day', ('il-Ħadd', 'it-Tnejn', 'it-Tlieta', 'l-Erbgħa', 'il-Ħamis', 'il-Ġimgħa', 'is-Sibt')), ('abmon', ('Jan', 'Fra', 'Mar', 'Apr', 'Mej', 'Ġun', 'Lul', 'Aww', 'Set', 'Ott', 'Nov', 'Diċ')), ('mon', ('Jannar', 'Frar', 'Marzu', 'April', 'Mejju', 'Ġunju', 'Lulju', 'Awwissu', 'Settembru', 'Ottubru', 'Novembru', 'Diċembru ')), ('d_t_fmt', '%A, %d ta %b, %Y %I:%M:%S %p %Z'), ('d_fmt', '%A, %d ta %b, %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(Yes|[yY])'), ('noexpr', '^(No|[nN])')]), ('my_MM', [('abday', ('နွေ', 'လာ', 'ဂါ', 'ဟူး', 'တေး', 'သော', 'နေ')), ('day', ('တနင်္ဂနွေ', 'တနင်္လာ', 'အင်္ဂါ', 'ဗုဒ္ဓဟူး', 'ကြာသပတေး', 'သောကြာ', 'စနေ')), ('abmon', ('ဇန်', 'ဖေ', 'မတ်', 'ဧပြီ', 'မေ', 'ဇွန်', 'ဇူ', 'ဩ', 'စက်', 'အောက်', 'နို', 'ဒီ')), ('mon', ('ဇန်နဝါရီ', 'ဖေဖော်ဝါရီ', 'မတ်', 'ဧပြီ', 'မေ', 'ဇွန်', 'ဇူလိုင်', 'ဩဂုတ်', 'စက်တင်ဘာ', 'အောက်တိုဘာ', 'နိုဝင်ဘာ', 'ဒီဇင်ဘာ')), ('d_t_fmt', '%OC%Oy %b %Od %A %OI:%OM:%OS %Op %Z'), ('d_fmt', '%OC%Oy %b %Od %A'), ('t_fmt', '%OI:%OM:%OS %p'), ('t_fmt_ampm', '%OI:%OM:%OS %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYဟ].*'), ('noexpr', '^[nNမ].*')]), ('nan_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('禮拜日', '禮拜一', '禮拜二', '禮拜三', '禮拜四', '禮拜五', '禮拜六')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 (%A) %H點%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H點%M分%S秒'), ('t_fmt_ampm', '%p %I點%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN伓]')]), ('nb_NO', [('abday', ('sø.', 'ma.', 'ti.', 'on.', 'to.', 'fr.', 'lø.')), ('day', ('søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag')), ('abmon', ('jan.', 'feb.', 'mars', 'april', 'mai', 'juni', 'juli', 'aug.', 'sep.', 'okt.', 'nov.', 'des.')), ('mon', ('januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember')), ('d_t_fmt', '%a %d. %b %Y kl. %H.%M %z'), ('d_fmt', '%d. %b %Y'), ('t_fmt', 'kl. %H.%M %z'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[Nn].*')]), ('nds_DE', [('abday', ('Sdag', 'Maan', 'Ding', 'Migg', 'Dunn', 'Free', 'Svd.')), ('day', ('Sünndag', 'Maandag', 'Dingsdag', 'Middeweek', 'Dunnersdag', 'Freedag', 'Sünnavend')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Jannuaar', 'Feberwaar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('nds_NL', [('abday', ('Sdg', 'Mdg', 'Dsg', 'Mwk', 'Ddg', 'Fdg', 'Swd')), ('day', ('Sinndag', 'Mondag', 'Dingsdag', 'Meddwäakj', 'Donnadag', 'Friedag', 'Sinnowend')), ('abmon', ('Jan', 'Feb', 'Moz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Now', 'Dez')), ('mon', ('Jaunuwoa', 'Februwoa', 'Moaz', 'Aprell', 'Mai', 'Juni', 'Juli', 'August', 'Septamba', 'Oktoba', 'Nowamba', 'Dezamba')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('ne_NP', [('abday', ('आइत ', 'सोम ', 'मंगल ', 'बुध ', 'बिहि ', 'शुक्र ', 'शनि ')), ('day', ('आइतबार ', 'सोमबार ', 'मंगलबार ', 'बुधबार ', 'बिहिबार ', 'शुक्रबार ', 'शनिबार ')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('nhn_MX', [('abday', ('teo', 'cei', 'ome', 'yei', 'nau', 'mac', 'chi')), ('day', ('teoilhuitl', 'ceilhuitl', 'omeilhuitl', 'yeilhuitl', 'nahuilhuitl', 'macuililhuitl', 'chicuaceilhuitl')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', '\u2009'), ('yesexpr', '^[sSqQyY].*'), ('noexpr', '^[nNaA].*')]), ('niu_NU', [('abday', ('Tapu', 'Gofua', 'Ua', 'Lotu', 'Tuloto', 'Falaile', 'Faiumu')), ('day', ('Aho Tapu', 'Aho Gofua', 'Aho Ua', 'Aho Lotu', 'Aho Tuloto', 'Aho Falaile', 'Aho Faiumu')), ('abmon', ('Ian', 'Fep', 'Mas', 'Ape', 'Me', 'Iun', 'Iul', 'Aok', 'Sep', 'Oke', 'Nov', 'Tes')), ('mon', ('Ianuali', 'Fepuali', 'Masi', 'Apelila', 'Me', 'Iuni', 'Iulai', 'Aokuso', 'Sepetema', 'Oketopa', 'Novema', 'Tesemo')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ēĒyY].*'), ('noexpr', '^[nN].*')]), ('niu_NZ', [('abday', ('Tapu', 'Gofua', 'Ua', 'Lotu', 'Tuloto', 'Falaile', 'Faiumu')), ('day', ('Aho Tapu', 'Aho Gofua', 'Aho Ua', 'Aho Lotu', 'Aho Tuloto', 'Aho Falaile', 'Aho Faiumu')), ('abmon', ('Ian', 'Fep', 'Mas', 'Ape', 'Me', 'Iun', 'Iul', 'Aok', 'Sep', 'Oke', 'Nov', 'Tes')), ('mon', ('Ianuali', 'Fepuali', 'Masi', 'Apelila', 'Me', 'Iuni', 'Iulai', 'Aokuso', 'Sepetema', 'Oketopa', 'Novema', 'Tesemo')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ēĒyY].*'), ('noexpr', '^[nN].*')]), ('nl_AW', [('abday', ('zo', 'ma', 'di', 'wo', 'do', 'vr', 'za')), ('day', ('zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag')), ('abmon', ('jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('nl_BE', [('abday', ('zo', 'ma', 'di', 'wo', 'do', 'vr', 'za')), ('day', ('zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag')), ('abmon', ('jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('nl_NL', [('abday', ('zo', 'ma', 'di', 'wo', 'do', 'vr', 'za')), ('day', ('zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag')), ('abmon', ('jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('nn_NO', [('abday', ('su.', 'må.', 'ty.', 'on.', 'to.', 'fr.', 'la.')), ('day', ('sundag ', 'måndag ', 'tysdag ', 'onsdag ', 'torsdag ', 'fredag ', 'laurdag ')), ('abmon', ('jan.', 'feb.', 'mars', 'april', 'mai', 'juni', 'juli', 'aug.', 'sep.', 'okt.', 'nov.', 'des.')), ('mon', ('januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember')), ('d_t_fmt', '%a %d. %b %Y kl. %H.%M %z'), ('d_fmt', '%d. %b %Y'), ('t_fmt', 'kl. %H.%M %z'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[Nn].*')]), ('nr_ZA', [('abday', ('Son', 'Mvu', 'Bil', 'Tha', 'Ne', 'Hla', 'Gqi')), ('day', ('uSonto', 'uMvulo', 'uLesibili', 'lesithathu', 'uLesine', 'ngoLesihlanu', 'umGqibelo')), ('abmon', ('Jan', 'Feb', 'Mat', 'Apr', 'Mey', 'Jun', 'Jul', 'Arh', 'Sep', 'Okt', 'Usi', 'Dis')), ('mon', ('Janabari', 'uFeberbari', 'uMatjhi', 'u-Apreli', 'Meyi', 'Juni', 'Julayi', 'Arhostosi', 'Septemba', 'Oktoba', 'Usinyikhaba', 'Disemba')), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('nso_ZA', [('abday', ('Son', 'Moš', 'Bed', 'Rar', 'Ne', 'Hla', 'Mok')), ('day', ('LaMorena', 'Mošupologo', 'Labobedi', 'Laboraro', 'Labone', 'Labohlano', 'Mokibelo')), ('abmon', ('Jan', 'Feb', 'Mat', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Set', 'Okt', 'Nof', 'Dis')), ('mon', ('Janaware', 'Febereware', 'Matšhe', 'Aprele', 'Mei', 'June', 'Julae', 'Agostose', 'Setemere', 'Oktobere', 'Nofemere', 'Disemere')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNaA]')]), ('oc_FR', [('abday', ('dim', 'lun', 'mar', 'mec', 'jòu', 'ven', 'sab')), ('day', ('dimenge', 'diluns', 'dimars', 'dimecres', 'dijóus', 'divendres', 'disabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'dec')), ('mon', ('genièr', 'febrièr', 'març', 'abrial', 'mai', 'junh', 'julhet', 'agost', 'setembre', 'octobre', 'novembre', 'decembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOsSyY].*'), ('noexpr', '^[nN].*')]), ('om_ET', [('abday', ('Dil', 'Wix', 'Qib', 'Rob', 'Kam', 'Jim', 'San')), ('day', ('Dilbata', 'Wiixata', 'Qibxata', 'Roobii', 'Kamiisa', 'Jimaata', 'Sanbata')), ('abmon', ('Ama', 'Gur', 'Bit', 'Elb', 'Cam', 'Wax', 'Ado', 'Hag', 'Ful', 'Onk', 'Sad', 'Mud')), ('mon', ('Amajjii', 'Guraandhala', 'Bitooteessa', 'Elba', 'Caamsa', 'Waxabajjii', 'Adooleessa', 'Hagayya', 'Fuulbana', 'Onkololeessa', 'Sadaasa', 'Muddee')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('om_KE', [('abday', ('Dil', 'Wix', 'Qib', 'Rob', 'Kam', 'Jim', 'San')), ('day', ('Dilbata', 'Wiixata', 'Qibxata', 'Roobii', 'Kamiisa', 'Jimaata', 'Sanbata')), ('abmon', ('Ama', 'Gur', 'Bit', 'Elb', 'Cam', 'Wax', 'Ado', 'Hag', 'Ful', 'Onk', 'Sad', 'Mud')), ('mon', ('Amajjii', 'Guraandhala', 'Bitooteessa', 'Elba', 'Caamsa', 'Waxabajjii', 'Adooleessa', 'Hagayya', 'Fuulbana', 'Onkololeessa', 'Sadaasa', 'Muddee')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('or_IN', [('abday', ('ରବି', 'ସୋମ', 'ମଙ୍ଗଳ', 'ବୁଧ', 'ଗୁରୁ', 'ଶୁକ୍ର', 'ଶନି')), ('day', ('ରବିବାର', 'ସୋମବାର', 'ମଙ୍ଗଳବାର', 'ବୁଧବାର', 'ଗୁରୁବାର', 'ଶୁକ୍ରବାର', 'ଶନିବାର')), ('abmon', ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12')), ('mon', ('ଜାନୁଆରୀ', 'ଫେବୃଆରୀ', 'ମାର୍ଚ୍ଚ', 'ଅପ୍ରେଲ', 'ମଇ', 'ଜୁନ', 'ଜୁଲାଇ', 'ଅଗଷ୍ଟ', 'ସେପ୍ଟେମ୍ବର', 'ଅକ୍ଟୋବର', 'ନଭେମ୍ବର', 'ଡିସେମ୍ବର')), ('d_t_fmt', '%Oe %B %Oy %OI:%OM:%OS %p %Z'), ('d_fmt', '%Od-%Om-%Oy'), ('t_fmt', '%OI:%OM:%OS %p'), ('t_fmt_ampm', '%OI:%OM:%OS %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('os_RU', [('abday', ('Хцб', 'Крс', 'Дцг', 'Æрт', 'Цпр', 'Мрб', 'Сбт')), ('day', ('Хуыцаубон', 'Къуырисæр', 'Дыццæг', 'Æртыццæг', 'Цыппæрæм', 'Майрæмбон', 'Сабат')), ('abmon', ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек')), ('mon', ('Январь', 'Февраль', 'Мартъи', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[УдYy].*'), ('noexpr', '^[унNn].*')]), ('pa_IN', [('abday', ('ਐਤ ', 'ਸੋਮ ', 'ਮੰਗਲ ', 'ਬੁੱਧ ', 'ਵੀਰ ', 'ਸ਼ੁੱਕਰ ', 'ਸ਼ਨਿੱਚਰ ')), ('day', ('ਐਤਵਾਰ ', 'ਸੋਮਵਾਰ ', 'ਮੰਗਲਵਾਰ ', 'ਬੁੱਧਵਾਰ ', 'ਵੀਰਵਾਰ ', 'ਸ਼ੁੱਕਰਵਾਰ ', 'ਸ਼ਨਿੱਚਰਵਾਰ ')), ('abmon', ('ਜਨਵਰੀ', 'ਫ਼ਰਵਰੀ', 'ਮਾਰਚ', 'ਅਪਰੈਲ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾਈ', 'ਅਗਸਤ', 'ਸਤੰਬਰ', 'ਅਕਤੂਬਰ', 'ਨਵੰਬਰ', 'ਦਸੰਬਰ')), ('mon', ('ਜਨਵਰੀ', 'ਫ਼ਰਵਰੀ', 'ਮਾਰਚ', 'ਅਪਰੈਲ', 'ਮਈ', 'ਜੂਨ', 'ਜੁਲਾਈ', 'ਅਗਸਤ', 'ਸਤੰਬਰ', 'ਅਕਤੂਬਰ', 'ਨਵੰਬਰ', 'ਦਸੰਬਰ')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('pa_PK', [('abday', ('اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته')), ('day', ('اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته')), ('abmon', ('جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('mon', ('جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('d_t_fmt', 'و %H:%M:%S %Z ت %d %B %Y'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%P %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYهبf].*'), ('noexpr', '^[nNنo].*')]), ('pap_AN', [('abday', ('do', 'lu', 'ma', 'we', 'ra', 'bi', 'sa')), ('day', ('Djadomingo', 'Djaluna', 'Djamars', 'Djawebs', 'Djarason', 'Djabierne', 'Djasabra')), ('abmon', ('Yan', 'Feb', 'Mar', 'Apr', 'Mei', 'Yün', 'Yül', 'Oug', 'Sèp', 'Okt', 'Nov', 'Des')), ('mon', ('Yanüari', 'Febrüari', 'Mart', 'Aprel', 'Mei', 'Yüni', 'Yüli', 'Ougùstùs', 'Sèptèmber', 'Oktober', 'Novèmber', 'Desèmber')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('pap_AW', [('abday', ('do', 'lu', 'ma', 'we', 'ra', 'bi', 'sa')), ('day', ('Djadomingo', 'Djaluna', 'Djamars', 'Djawebs', 'Djarason', 'Djabierne', 'Djasabra')), ('abmon', ('Yan', 'Feb', 'Mar', 'Apr', 'Mei', 'Yün', 'Yül', 'Oug', 'Sèp', 'Okt', 'Nov', 'Des')), ('mon', ('Yanüari', 'Febrüari', 'Mart', 'Aprel', 'Mei', 'Yüni', 'Yüli', 'Ougùstùs', 'Sèptèmber', 'Oktober', 'Novèmber', 'Desèmber')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('pap_CW', [('abday', ('do', 'lu', 'ma', 'we', 'ra', 'bi', 'sa')), ('day', ('Djadomingo', 'Djaluna', 'Djamars', 'Djawebs', 'Djarason', 'Djabierne', 'Djasabra')), ('abmon', ('Yan', 'Feb', 'Mar', 'Apr', 'Mei', 'Yün', 'Yül', 'Oug', 'Sèp', 'Okt', 'Nov', 'Des')), ('mon', ('Yanüari', 'Febrüari', 'Mart', 'Aprel', 'Mei', 'Yüni', 'Yüli', 'Ougùstùs', 'Sèptèmber', 'Oktober', 'Novèmber', 'Desèmber')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('pl_PL', [('abday', ('nie', 'pon', 'wto', 'śro', 'czw', 'pią', 'sob')), ('day', ('niedziela', 'poniedziałek', 'wtorek', 'środa', 'czwartek', 'piątek', 'sobota')), ('abmon', ('sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru')), ('mon', ('styczeń', 'luty', 'marzec', 'kwiecień', 'maj', 'czerwiec', 'lipiec', 'sierpień', 'wrzesień', 'październik', 'listopad', 'grudzień')), ('d_t_fmt', '%a, %-d %b %Y, %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[TtYy].*'), ('noexpr', '^[nN].*')]), ('ps_AF', [('abday', ('ی.', 'د.', 'س.', 'چ.', 'پ.', 'ج.', 'ش.')), ('day', ('یکشنبه', 'دوشنبه', 'سه\u200cشنبه', 'چارشنبه', 'پنجشنبه', 'جمعه', 'شنبه')), ('abmon', ('جنو', 'فبر', 'مار', 'اپر', 'مـې', 'جون', 'جول', 'اګس', 'سپت', 'اکت', 'نوم', 'دسم')), ('mon', ('جنوري', 'فبروري', 'مارچ', 'اپریل', 'مې', 'جون', 'جولاي', 'اګست', 'سپتمبر', 'اکتوبر', 'نومبر', 'دسمبر')), ('d_t_fmt', '%A د %Y د %B %e، %Z %H:%M:%S'), ('d_fmt', 'د %Y د %B %e'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '\u202b%I:%M:%S %p\u202c'), ('radixchar', '٫'), ('thousep', '٬'), ('yesexpr', '^[yYبf].*'), ('noexpr', '^[nNخنo].*')]), ('pt_BR', [('abday', ('Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb')), ('day', ('domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado')), ('abmon', ('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez')), ('mon', ('janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[SsyY].*'), ('noexpr', '^[nN].*')]), ('pt_PT', [('abday', ('Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb')), ('day', ('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado')), ('abmon', ('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez')), ('mon', ('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[SsyY].*'), ('noexpr', '^[nN].*')]), ('quz_PE', [('abday', ('tum', 'lun', 'mar', 'miy', 'juy', 'wiy', 'saw')), ('day', ('tuminku', 'lunis', 'martis', 'miyirkulis', 'juywis', 'wiyirnis', 'sawatu')), ('abmon', ('ini', 'phi', 'mar', 'awr', 'may', 'hun', 'hul', 'agu', 'sip', 'ukt', 'nuw', 'tis')), ('mon', ('iniru', 'phiwriru', 'marsu', 'awril', 'mayu', 'huniyu', 'huliyu', 'agustu', 'siptiyimri', 'uktuwri', 'nuwiyimri', 'tisiyimri')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%I:%M:%S %p'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[aAsSyY].*'), ('noexpr', '^[mMnN].*')]), ('ro_RO', [('abday', ('Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sb')), ('day', ('duminică', 'luni', 'marţi', 'miercuri', 'joi', 'vineri', 'sâmbătă')), ('abmon', ('ian', 'feb', 'mar', 'apr', 'mai', 'iun', 'iul', 'aug', 'sep', 'oct', 'nov', 'dec')), ('mon', ('ianuarie', 'februarie', 'martie', 'aprilie', 'mai', 'iunie', 'iulie', 'august', 'septembrie', 'octombrie', 'noiembrie', 'decembrie')), ('d_t_fmt', '%a %d %b %Y %T %z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[DdYy].*'), ('noexpr', '^[nN].*')]), ('ru_RU', [('abday', ('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб')), ('day', ('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота')), ('abmon', ('янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек')), ('mon', ('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[ДдYy].*'), ('noexpr', '^[НнNn].*')]), ('ru_UA', [('abday', ('Вск', 'Пнд', 'Вто', 'Срд', 'Чтв', 'Птн', 'Суб')), ('day', ('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота')), ('abmon', ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек')), ('mon', ('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[ДдYy].*'), ('noexpr', '^[НнNn].*')]), ('rw_RW', [('abday', ('Mwe', 'Mbe', 'Kab', 'Gtu', 'Kan', 'Gnu', 'Gnd')), ('day', ('Ku cyumweru', 'Kuwa mbere', 'Kuwa kabiri', 'Kuwa gatatu', 'Kuwa kane', 'Kuwa gatanu', 'Kuwa gatandatu')), ('abmon', ('Mut', 'Gas', 'Wer', 'Mat', 'Gic', 'Kam', 'Nya', 'Kan', 'Nze', 'Ukw', 'Ugu', 'Uku')), ('mon', ('Mutarama', 'Gashyantare', 'Werurwe', 'Mata', 'Gicuransi', 'Kamena', 'Nyakanga', 'Kanama', 'Nzeli', 'Ukwakira', 'Ugushyingo', 'Ukuboza')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[yY]'), ('noexpr', '^[nNoO]')]), ('sa_IN', [('abday', ('रविः', 'सोम:', 'मंगल:', 'बुध:', 'बृहस्पतिः', 'शुक्र', 'शनि:')), ('day', ('रविवासर:', 'सोमवासर:', 'मंगलवासर:', 'बुधवासर:', 'बृहस्पतिवासरः', 'शुक्रवासर', 'शनिवासर:')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[aAyY].*'), ('noexpr', '^[nN].*')]), ('sat_IN', [('abday', ('सिंगे', 'ओते', 'बाले', 'सागुन', 'सारदी', 'जारुम', 'ञुहुम')), ('day', ('सिंगेमाँहाँ', 'ओतेमाँहाँ', 'बालेमाँहाँ', 'सागुनमाँहाँ', 'सारदीमाँहाँ', 'जारुममाँहाँ', 'ञुहुममाँहाँ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(होय|[yY])'), ('noexpr', '^(बाङ|[nN])')]), ('sc_IT', [('abday', ('Dom', 'Lun', 'Mar', 'Mèr', 'Jòb', 'Cen', 'Sàb')), ('day', ('Domìngu', 'Lunis', 'Martis', 'Mèrcuris', 'Jòbia', 'Cenàbara', 'Sàbadu')), ('abmon', ('Gen', 'Fri', 'Mar', 'Abr', 'May', 'Làm', 'Arj', 'Aus', 'Cab', 'Lad', 'Don', 'Ida')), ('mon', ('Gennarju', 'Friarju', 'Martzu', 'Abrili', 'Mayu', 'Làmpadas', 'Arjolas', 'Austu', 'Cabudanni', 'Ladàmini', 'Donnyasantu', 'Idas')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d. %m. %y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSjJoOyY].*'), ('noexpr', '^[nN].*')]), ('sd_IN', [('abday', ('آرتوارُ', 'سومرُ', 'منگلُ', 'ٻُڌرُ', 'وسپت', 'جُمو', 'ڇنڇر')), ('day', ('آرتوارُ', 'سومرُ', 'منگلُ', 'ٻُڌرُ', 'وسپت', 'جُمو', 'ڇنڇر')), ('abmon', ('جنوري', 'فبروري', 'مارچ', 'اپريل', 'مي', 'جون', 'جولاءِ', 'آگسٽ', 'سيپٽيمبر', 'آڪٽوبر', 'نومبر', 'ڊسمبر')), ('mon', ('جنوري', 'فبروري', 'مارچ', 'اپريل', 'مي', 'جون', 'جولاءِ', 'آگسٽ', 'سيپٽيمبر', 'آڪٽوبر', 'نومبر', 'ڊسمبر')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('se_NO', [('abday', ('sotn', 'vuos', 'maŋ', 'gask', 'duor', 'bear', 'láv')), ('day', ('sotnabeaivi', 'vuossárga', 'maŋŋebarga', 'gaskavahkku', 'duorasdat', 'bearjadat', 'lávvardat')), ('abmon', ('ođđj', 'guov', 'njuk', 'cuoŋ', 'mies', 'geas', 'suoi', 'borg', 'čakč', 'golg', 'skáb', 'juov')), ('mon', ('ođđajagemánu', 'guovvamánu', 'njukčamánu', 'cuoŋománu', 'miessemánu', 'geassemánu', 'suoidnemánu', 'borgemánu', 'čakčamánu', 'golggotmánu', 'skábmamánu', 'juovlamánu')), ('d_t_fmt', '%a, %b %e. b. %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[JjYy].*'), ('noexpr', '^[Ii].*')]), ('shs_CA', [('abday', ('Sxe', 'Spe', 'Sel', 'Ske', 'Sme', 'Sts', 'Stq')), ('day', ('Sxetspesq̓t', 'Spetkesq̓t', 'Selesq̓t', 'Skellesq̓t', 'Smesesq̓t', 'Stselkstesq̓t', 'Stqmekstesq̓t')), ('abmon', ('Kwe', 'Tsi', 'Sqe', 'Éwt', 'Ell', 'Tsp', 'Tqw', 'Ct̓é', 'Qel', 'Wél', 'U7l', 'Tet')), ('mon', ('Pellkwet̓min', 'Pelctsipwen̓ten', 'Pellsqépts', 'Peslléwten', 'Pell7ell7é7llqten', 'Pelltspéntsk', 'Pelltqwelq̓wél̓t', 'Pellct̓éxel̓cten', 'Pesqelqlélten', 'Pesllwélsten', 'Pellc7ell7é7llcwten̓', 'Pelltetétq̓em')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYoO].*'), ('noexpr', '^[nN].*')]), ('si_LK', [('abday', ('ඉ', 'ස', 'අ', 'බ', 'බ්\u200dර', 'සි', 'සෙ')), ('day', ('ඉරිදා', 'සඳුදා', 'අඟහරුවාදා', 'බදාදා', 'බ්\u200dරහස්පතින්දා', 'සිකුරාදා', 'සෙනසුරාදා')), ('abmon', ('ජන', 'පෙබ', 'මාර්', 'අප්\u200dරි', 'මැයි', 'ජූනි', 'ජූලි', 'අගෝ', 'සැප්', 'ඔක්', 'නෙවැ', 'දෙසැ')), ('mon', ('ජනවාරි', 'පෙබරවාරි', 'මාර්තු', 'අප්\u200dරියෙල්', 'මැයි', 'ජූනි', 'ජූලි', 'අගෝස්තු', 'සැප්තැම්බර්', 'ඔක්තෝබර්', 'නොවැම්බර්', 'දෙසැම්බර්')), ('d_t_fmt', '%Y-%m-%d %H:%M:%S %z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%p %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ඔYy]'), ('noexpr', '^[නNn]')]), ('sid_ET', [('abday', ('Sam', 'San', 'Mak', 'Row', 'Ham', 'Arb', 'Qid')), ('day', ('Sambata', 'Sanyo', 'Maakisanyo', 'Roowe', 'Hamuse', 'Arbe', 'Qidaame')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('sk_SK', [('abday', ('Ne', 'Po', 'Ut', 'St', 'Št', 'Pi', 'So')), ('day', ('Nedeľa', 'Pondelok', 'Utorok', 'Streda', 'Štvrtok', 'Piatok', 'Sobota')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december')), ('d_t_fmt', '%a\xa0%e.\xa0%B\xa0%Y,\xa0%H:%M:%S\xa0%Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S'), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[aAáÁyY].*'), ('noexpr', '^[nN].*')]), ('sl_SI', [('abday', ('ned', 'pon', 'tor', 'sre', 'čet', 'pet', 'sob')), ('day', ('nedelja', 'ponedeljek', 'torek', 'sreda', 'četrtek', 'petek', 'sobota')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'avg', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januar', 'februar', 'marec', 'april', 'maj', 'junij', 'julij', 'avgust', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d. %m. %Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[YyJj].*'), ('noexpr', '^[Nn].*')]), ('so_DJ', [('abday', ('axa', 'isn', 'sal', 'arb', 'kha', 'jim', 'sab')), ('day', ('Axad', 'Isniin', 'Salaaso', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti')), ('abmon', ('kob', 'lab', 'sad', 'afr', 'sha', 'lix', 'tod', 'sid', 'sag', 'tob', 'kit', 'lit')), ('mon', ('Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('so_ET', [('abday', ('Axa', 'Isn', 'Sal', 'Arb', 'Kha', 'Jim', 'Sab')), ('day', ('Axad', 'Isniin', 'Salaaso', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti')), ('abmon', ('Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT')), ('mon', ('Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('so_KE', [('abday', ('Axa', 'Isn', 'Sal', 'Arb', 'Kha', 'Jim', 'Sab')), ('day', ('Axad', 'Isniin', 'Salaaso', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti')), ('abmon', ('Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT')), ('mon', ('Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('so_SO', [('abday', ('Axa', 'Isn', 'Sal', 'Arb', 'Kha', 'Jim', 'Sab')), ('day', ('Axad', 'Isniin', 'Salaaso', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti')), ('abmon', ('Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT')), ('mon', ('Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('sq_AL', [('abday', ('Die ', 'Hën ', 'Mar ', 'Mër ', 'Enj ', 'Pre ', 'Sht ')), ('day', ('e diel ', 'e hënë ', 'e martë ', 'e mërkurë ', 'e enjte ', 'e premte ', 'e shtunë ')), ('abmon', ('Jan', 'Shk', 'Mar', 'Pri', 'Maj', 'Qer', 'Kor', 'Gsh', 'Sht', 'Tet', 'Nën', 'Dhj')), ('mon', ('janar', 'shkurt', 'mars', 'prill', 'maj', 'qershor', 'korrik', 'gusht', 'shtator', 'tetor', 'nëntor', 'dhjetor')), ('d_t_fmt', '%Y-%b-%d %I.%M.%S.%p %Z'), ('d_fmt', '%Y-%b-%d'), ('t_fmt', '%I.%M.%S. %Z'), ('t_fmt_ampm', '%I.%M.%S.%p %Z'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYpP].*'), ('noexpr', '^[nNjJ].*')]), ('sq_MK', [('abday', ('Die ', 'Hën ', 'Mar ', 'Mër ', 'Enj ', 'Pre ', 'Sht ')), ('day', ('e diel ', 'e hënë ', 'e martë ', 'e mërkurë ', 'e enjte ', 'e premte ', 'e shtunë ')), ('abmon', ('Jan', 'Shk', 'Mar', 'Pri', 'Maj', 'Qer', 'Kor', 'Gsh', 'Sht', 'Tet', 'Nën', 'Dhj')), ('mon', ('janar', 'shkurt', 'mars', 'prill', 'maj', 'qershor', 'korrik', 'gusht', 'shtator', 'tetor', 'nëntor', 'dhjetor')), ('d_t_fmt', '%Y-%b-%d %I.%M.%S.%p %Z'), ('d_fmt', '%Y-%b-%d'), ('t_fmt', '%I.%M.%S. %Z'), ('t_fmt_ampm', '%I.%M.%S.%p %Z'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYpP].*'), ('noexpr', '^[nNjJ].*')]), ('sr_ME', [('abday', ('нед', 'пон', 'уто', 'сри', 'чет', 'пет', 'суб')), ('day', ('недјеља', 'понедељак', 'уторак', 'сриједа', 'четвртак', 'петак', 'субота')), ('abmon', ('јан', 'феб', 'мар', 'апр', 'мај', 'јун', 'јул', 'авг', 'сеп', 'окт', 'нов', 'дец')), ('mon', ('јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар')), ('d_t_fmt', '%A, %d. %B %Y. %T %Z'), ('d_fmt', '%d.%m.%Y.'), ('t_fmt', '%T'), ('t_fmt_ampm', '%T'), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[ДдDdYy]'), ('noexpr', '^[НнNn]')]), ('sr_RS', [('abday', ('нед', 'пон', 'уто', 'сре', 'чет', 'пет', 'суб')), ('day', ('недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота')), ('abmon', ('јан', 'феб', 'мар', 'апр', 'мај', 'јун', 'јул', 'авг', 'сеп', 'окт', 'нов', 'дец')), ('mon', ('јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар')), ('d_t_fmt', '%A, %d. %B %Y. %T %Z'), ('d_fmt', '%d.%m.%Y.'), ('t_fmt', '%T'), ('t_fmt_ampm', '%T'), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[ДдDdYy]'), ('noexpr', '^[НнNn]')]), ('ss_ZA', [('abday', ('Son', 'Mso', 'Bil', 'Tsa', 'Ne', 'Hla', 'Mgc')), ('day', ('Lisontfo', 'uMsombuluko', 'Lesibili', 'Lesitsatfu', 'Lesine', 'Lesihlanu', 'uMgcibelo')), ('abmon', ('Bhi', 'Van', 'Vul', 'Mab', 'Khk', 'Nhl', 'Kho', 'Ngc', 'Nyo', 'Imp', 'Lwe', 'Ngo')), ('mon', ('Bhimbidvwane', 'iNdlovane', 'iNdlovulenkhulu', 'Mabasa', 'Inkhwenkhweti', 'iNhlaba', 'Kholwane', 'iNgci', 'iNyoni', 'Impala', 'Lweti', 'iNgongoni')), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nNaA]')]), ('st_ZA', [('abday', ('Son', 'Mma', 'Bed', 'Rar', 'Ne', 'Hla', 'Moq')), ('day', ('Sontaha', 'Mantaha', 'Labobedi', 'Laboraro', 'Labone', 'Labohlano', 'Moqebelo')), ('abmon', ('Phe', 'Hla', 'TlH', 'Mme', 'Mot', 'Jan', 'Upu', 'Pha', 'Leo', 'Mph', 'Pud', 'Tsh')), ('mon', ('Pherekgong', 'Hlakola', 'Tlhakubele', 'Mmese', 'Motsheanong', 'Phupjane', 'Phupu', 'Phato', 'Leotse', 'Mphalane', 'Pudungwana', 'Tshitwe')), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('sv_FI', [('abday', ('sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör')), ('day', ('söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %e. %B %Y %H.%M.%S'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%H.%M.%S'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('sv_SE', [('abday', ('sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör')), ('day', ('söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %e %b %Y %H:%M:%S'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('sw_KE', [('abday', ('J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1')), ('day', ('Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi')), ('abmon', ('Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba')), ('d_t_fmt', '%e %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%I:%M:%S %p'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[nNyY].*'), ('noexpr', '^[hHlL].*')]), ('sw_TZ', [('abday', ('J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1')), ('day', ('Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi')), ('abmon', ('Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba')), ('d_t_fmt', '%e %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%I:%M:%S %p'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[nNyY].*'), ('noexpr', '^[hHlL].*')]), ('szl_PL', [('abday', ('niy', 'pyń', 'wtŏ', 'str', 'szt', 'pjō', 'sob')), ('day', ('niydziela', 'pyńdziŏek', 'wtŏrek', 'strzŏda', 'sztwortek', 'pjōntek', 'sobŏta')), ('abmon', ('sty', 'lut', 'mer', 'kwj', 'moj', 'czy', 'lip', 'siy', 'wrz', 'paź', 'lis', 'gru')), ('mon', ('styczyń', 'luty', 'merc', 'kwjeciyń', 'moj', 'czyrwjyń', 'lipjyń', 'siyrpjyń', 'wrzesiyń', 'październik', 'listopad', 'grudziyń')), ('d_t_fmt', '%a, %-d %b %Y, %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[JjTtYy].*'), ('noexpr', '^[nN].*')]), ('ta_IN', [('abday', ('ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச')), ('day', ('ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி')), ('abmon', ('ஜன', 'பிப்', 'மார்', 'ஏப்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக', 'செப்', 'அக்', 'நவ', 'டிச')), ('mon', ('ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ஆம்yY]'), ('noexpr', '^[இல்லைnN]')]), ('ta_LK', [('abday', ('ஞா', 'தி', 'செ', 'பு', 'வி', 'வெ', 'ச')), ('day', ('ஞாயிறு', 'திங்கள்', 'செவ்வாய்', 'புதன்', 'வியாழன்', 'வெள்ளி', 'சனி')), ('abmon', ('ஜன', 'பிப்', 'மார்', 'ஏப்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக', 'செப்', 'அக்', 'நவ', 'டிச')), ('mon', ('ஜனவரி', 'பிப்ரவரி', 'மார்ச்', 'ஏப்ரல்', 'மே', 'ஜூன்', 'ஜூலை', 'ஆகஸ்ட்', 'செப்டம்பர்', 'அக்டோபர்', 'நவம்பர்', 'டிசம்பர்')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ஆம்yY]'), ('noexpr', '^[இல்லைnN]')]), ('te_IN', [('abday', ('ఆది', 'సోమ', 'మంగళ', 'బుధ', 'గురు', 'శుక్ర', 'శని')), ('day', ('ఆదివారం', 'సోమవారం', 'మంగళవారం', 'బుధవారం', 'గురువారం', 'శుక్రవారం', 'శనివారం')), ('abmon', ('జనవరి', 'ఫిబ్రవరి', 'మార్చి', 'ఏప్రిల్', 'మే', 'జూన్', 'జూలై', 'ఆగస్టు', 'సెప్టెంబరు', 'అక్టోబరు', 'నవంబరు', 'డిసెంబరు')), ('mon', ('జనవరి', 'ఫిబ్రవరి', 'మార్చి', 'ఏప్రిల్', 'మే', 'జూన్', 'జూలై', 'ఆగస్టు', 'సెప్టెంబరు', 'అక్టోబరు', 'నవంబరు', 'డిసెంబరు')), ('d_t_fmt', '%B %d %A %Y %p%I.%M.%S %Z'), ('d_fmt', '%B %d %A %Y'), ('t_fmt', '%p%I.%M.%S %Z'), ('t_fmt_ampm', '%p%I.%M.%S %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYఅ].*'), ('noexpr', '^[nNక].*')]), ('tg_TJ', [('abday', ('Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт')), ('day', ('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота')), ('abmon', ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек')), ('mon', ('Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[ҲҳХхДдYy].*'), ('noexpr', '^[НнNn].*')]), ('th_TH', [('abday', ('อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.')), ('day', ('อาทิตย์', 'จันทร์', 'อังคาร', 'พุธ', 'พฤหัสบดี', 'ศุกร์', 'เสาร์')), ('abmon', ('ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.')), ('mon', ('มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม')), ('d_t_fmt', '%a %e %b %Ey, %H:%M:%S'), ('d_fmt', '%d/%m/%Ey'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYช]'), ('noexpr', '^[nNม]')]), ('the_NP', [('abday', ('आइत ', 'सोम ', 'मंगल ', 'बुध ', 'बिहि ', 'शुक्र ', 'शनि ')), ('day', ('आइतबार ', 'सोमबार ', 'मंगलबार ', 'बुधबार ', 'बिहिबार ', 'शुक्रबार ', 'शनिबार ')), ('abmon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ti_ER', [('abday', ('ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም')), ('day', ('ሰንበት', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም')), ('abmon', ('ጥሪ ', 'ለካቲ', 'መጋቢ', 'ሚያዝ', 'ግንቦ', 'ሰነ ', 'ሓምለ', 'ነሓሰ', 'መስከ', 'ጥቅም', 'ሕዳር', 'ታሕሳ')), ('mon', ('ጥሪ', 'ለካቲት', 'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰነ', 'ሓምለ', 'ነሓሰ', 'መስከረም', 'ጥቅምቲ', 'ሕዳር', 'ታሕሳስ')), ('d_t_fmt', '%A፡ %B %e መዓልቲ %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ti_ET', [('abday', ('ሰንበ', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም')), ('day', ('ሰንበት', 'ሰኑይ', 'ሰሉስ', 'ረቡዕ', 'ሓሙስ', 'ዓርቢ', 'ቀዳም')), ('abmon', ('ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም')), ('mon', ('ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር')), ('d_t_fmt', '%A፣ %B %e መዓልቲ %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('tig_ER', [('abday', ('ሰ/ዓ', 'ሰኖ ', 'ታላሸ', 'ኣረር', 'ከሚሽ', 'ጅምዓ', 'ሰ/ን')), ('day', ('ሰንበት ዓባይ', 'ሰኖ', 'ታላሸኖ', 'ኣረርባዓ', 'ከሚሽ', 'ጅምዓት', 'ሰንበት ንኢሽ')), ('abmon', ('ጥሪ ', 'ለካቲ', 'መጋቢ', 'ሚያዝ', 'ግንቦ', 'ሰነ ', 'ሓምለ', 'ነሓሰ', 'መስከ', 'ጥቅም', 'ሕዳር', 'ታሕሳ')), ('mon', ('ጥሪ', 'ለካቲት', 'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰነ', 'ሓምለ', 'ነሓሰ', 'መስከረም', 'ጥቅምቲ', 'ሕዳር', 'ታሕሳስ')), ('d_t_fmt', '%A፡ %B %e ዮም %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('tk_TM', [('abday', ('Duş', 'Siş', 'Çar', 'Pen', 'Ann', 'Şen', 'Ýek')), ('day', ('Duşenbe', 'Sişenbe', 'Çarşenbe', 'Penşenbe', 'Anna', 'Şenbe', 'Ýekşenbe')), ('abmon', ('Ýan', 'Few', 'Mar', 'Apr', 'Maý', 'Iýn', 'Iýl', 'Awg', 'Sen', 'Okt', 'Noý', 'Dek')), ('mon', ('Ýanwar', 'Fewral', 'Mart', 'Aprel', 'Maý', 'Iýun', 'Iýul', 'Awgust', 'Sentýabr', 'Oktýabr', 'Noýabr', 'Dekabr')), ('d_t_fmt', '%d.%m.%Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[hH].*'), ('noexpr', '^[ýÝnN].*')]), ('tl_PH', [('abday', ('Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab')), ('day', ('Linggo', 'Lunes', 'Martes', 'Miyerkoles', 'Huwebes', 'Biyernes', 'Sabado')), ('abmon', ('Ene', 'Peb', 'Mar', 'Abr', 'May', 'Hun', 'Hul', 'Ago', 'Sep', 'Okt', 'Nob', 'Dis')), ('mon', ('Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Septiyembre', 'Oktubre', 'Nobiyembre', 'Disyembre')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('tn_ZA', [('abday', ('Tsh', 'Mos', 'Bed', 'Rar', 'Ne', 'Tlh', 'Mat')), ('day', ('laTshipi', 'Mosupologo', 'Labobedi', 'Laboraro', 'Labone', 'Labotlhano', 'Lamatlhatso')), ('abmon', ('Fer', 'Tlh', 'Mop', 'Mor', 'Mot', 'See', 'Phu', 'Pha', 'Lwe', 'Dip', 'Ngw', 'Sed')), ('mon', ('Ferikgong', 'Tlhakole', 'Mopitlwe', 'Moranang', 'Motsheganong', 'Seetebosigo', 'Phukwi', 'Phatwe', 'Lwetse', 'Diphalane', 'Ngwanatsele', 'Sedimonthole')), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nN]')]), ('tr_CY', [('abday', ('Paz', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cts')), ('day', ('Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi')), ('abmon', ('Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara')), ('mon', ('Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('tr_TR', [('abday', ('Paz', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cts')), ('day', ('Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi')), ('abmon', ('Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara')), ('mon', ('Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('ts_ZA', [('abday', ('Son', 'Mus', 'Bir', 'Har', 'Ne', 'Tlh', 'Mug')), ('day', ('Sonto', 'Musumbhunuku', 'Ravumbirhi', 'Ravunharhu', 'Ravumune', 'Ravuntlhanu', 'Mugqivela')), ('abmon', ('Sun', 'Yan', 'Kul', 'Dzi', 'Mud', 'Kho', 'Maw', 'Mha', 'Ndz', 'Nhl', 'Huk', "N'w")), ('mon', ('Sunguti', 'Nyenyenyani', 'Nyenyankulu', 'Dzivamisoko', 'Mudyaxihi', 'Khotavuxika', 'Mawuwani', 'Mhawuri', 'Ndzhati', 'Nhlangula', 'Hukuri', "N'wendzamhala")), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('tt_RU', [('abday', ('Якш', 'Дыш', 'Сиш', 'Чәрш', 'Пәнҗ', 'Җом', 'Шим')), ('day', ('Якшәмбе', 'Дышәмбе', 'Сишәмбе', 'Чәршәәмбе', 'Пәнҗешмбе', 'Җомга', 'Шимбә')), ('abmon', ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек')), ('mon', ('Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[ДдYy].*'), ('noexpr', '^[НнNn].*')]), ('ug_CN', [('abday', ('ي', 'د', 'س', 'چ', 'پ', 'ج', 'ش')), ('day', ('يەكشەنبە', 'دۈشەنبە', 'سەيشەنبە', 'چارشەنبە', 'پەيشەنبە', 'جۈمە', 'شەنبە')), ('abmon', ('قەھرىتان', 'ھۇت', 'نورۇز', 'ئۈمىد', 'باھار', 'سەپەر', 'چىللە', 'تومۇز', 'مىزان', 'ئوغۇز', 'ئوغلاق', 'كۆنەك')), ('mon', ('قەھرىتان', 'ھۇت', 'نورۇز', 'ئۈمىد', 'باھار', 'سەپەر', 'چىللە', 'تومۇز', 'مىزان', 'ئوغۇز', 'ئوغلاق', 'كۆنەك')), ('d_t_fmt', '%a، %d-%m-%Y، %T'), ('d_fmt', '%a، %d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%T'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('uk_UA', [('abday', ('нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб')), ('day', ('неділя', 'понеділок', 'вівторок', 'середа', 'четвер', "п'ятниця", 'субота')), ('abmon', ('січ', 'лют', 'бер', 'кві', 'тра', 'чер', 'лип', 'сер', 'вер', 'жов', 'лис', 'гру')), ('mon', ('січень', 'лютий', 'березень', 'квітень', 'травень', 'червень', 'липень', 'серпень', 'вересень', 'жовтень', 'листопад', 'грудень')), ('d_t_fmt', '%a, %d-%b-%Y %X %z'), ('d_fmt', '%d.%m.%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^([Yy+]|[Тт][Аа][Кк]?)$'), ('noexpr', '^([Nn-]|[Нн][Іі])$')]), ('unm_US', [('abday', ('ken', 'man', 'tus', 'lel', 'tas', 'pel', 'sat')), ('day', ('kentuwei', 'manteke', 'tusteke', 'lelai', 'tasteke', 'pelaiteke', 'sateteke')), ('abmon', ('eni', 'chk', 'xam', 'kwe', 'tai', 'nip', 'lai', 'win', 'tah', 'puk', 'kun', 'mux')), ('mon', ('enikwsi', 'chkwali', 'xamokhwite', 'kwetayoxe', 'tainipen', 'kichinipen', 'lainipen', 'winaminke', 'kichitahkok', 'puksit', 'wini', 'muxkotae')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ' '), ('yesexpr', '^[yY].*'), ('noexpr', '^[kKmM].*')]), ('ur_IN', [('abday', ('اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'سنیچر')), ('day', ('اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'سنیچر')), ('abmon', ('جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('mon', ('جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ہyY].*'), ('noexpr', '^[نnN].*')]), ('ur_PK', [('abday', ('اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته')), ('day', ('اتوار', 'پير', 'منگل', 'بدھ', 'جمعرات', 'جمعه', 'هفته')), ('abmon', ('جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('mon', ('جنوري', 'فروري', 'مارچ', 'اپريل', 'مٓی', 'جون', 'جولاي', 'اگست', 'ستمبر', 'اكتوبر', 'نومبر', 'دسمبر')), ('d_t_fmt', 'و %H:%M:%S %Z ت %d %B %Y'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%P %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYهبf].*'), ('noexpr', '^[nNنo].*')]), ('ve_ZA', [('abday', ('Swo', 'Mus', 'Vhi', 'Rar', 'ṋa', 'Ṱan', 'Mug')), ('day', ('Swondaha', 'Musumbuluwo', 'Ḽavhuvhili', 'Ḽavhuraru', 'Ḽavhuṋa', 'Ḽavhuṱanu', 'Mugivhela')), ('abmon', ('Pha', 'Luh', 'Fam', 'Lam', 'Shu', 'Lwi', 'Lwa', 'Ngu', 'Khu', 'Tsh', 'Ḽar', 'Nye')), ('mon', ('Phando', 'Luhuhi', 'Ṱhafamuhwe', 'Lambamai', 'Shundunthule', 'Fulwi', 'Fulwana', 'Ṱhangule', 'Khubvumedzi', 'Tshimedzi', 'Ḽara', 'Nyendavhusiku')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('vi_VN', [('abday', ('CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7')), ('day', ('Chủ nhật', 'Thứ hai', 'Thứ ba', 'Thứ tư', 'Thứ năm', 'Thứ sáu', 'Thứ bảy')), ('abmon', ('Th01', 'Th02', 'Th03', 'Th04', 'Th05', 'Th06', 'Th07', 'Th08', 'Th09', 'Th10', 'Th11', 'Th12')), ('mon', ('Tháng một', 'Tháng hai', 'Tháng ba', 'Tháng tư', 'Tháng năm', 'Tháng sáu', 'Tháng bảy', 'Tháng tám', 'Tháng chín', 'Tháng mười', 'Tháng mười một', 'Tháng mười hai')), ('d_t_fmt', '%A, %d %B Năm %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1yYcC].*'), ('noexpr', '^[0nNkK].*')]), ('wa_BE', [('abday', ('dim', 'lon', 'mår', 'mie', 'dju', 'vén', 'sem')), ('day', ('dimegne', 'londi', 'mårdi', 'mierkidi', 'djudi', 'vénrdi', 'semdi')), ('abmon', ('dja', 'fev', 'mås', 'avr', 'may', 'djn', 'djl', 'awo', 'set', 'oct', 'nôv', 'dec')), ('mon', ('djanvî', 'fevrî', 'måss', 'avri', 'may', 'djun', 'djulete', 'awousse', 'setimbe', 'octôbe', 'nôvimbe', 'decimbe')), ('d_t_fmt', 'Li %A %d di %B %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[oOyYaAwW].*'), ('noexpr', '^[nN].*')]), ('wae_CH', [('abday', ('Sun', 'Män', 'Zis', 'Mit', 'Fro', 'Fri', 'Sam')), ('day', ('Suntag', 'Mäntag', 'Zischtag', 'Mittwuch', 'Frontag', 'Fritag', 'Samschtag')), ('abmon', ('Jen', 'Hor', 'Mär', 'Abr', 'Mei', 'Brá', 'Hei', 'Öig', 'Her', 'Wím', 'Win', 'Chr')), ('mon', ('Jener', 'Hornig', 'Märze', 'Abrille', 'Meije', 'Bráchet', 'Heiwet', 'Öigschte', 'Herbschtmánet', 'Wímánet', 'Wintermánet', 'Chrischtmánet')), ('d_t_fmt', '%a %d. %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', "'"), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('wal_ET', [('abday', ('ወጋ ', 'ሳይኖ', 'ማቆሳ', 'አሩዋ', 'ሃሙሳ', 'አርባ', 'ቄራ ')), ('day', ('ወጋ', 'ሳይኖ', 'ማቆሳኛ', 'አሩዋ', 'ሃሙሳ', 'አርባ', 'ቄራ')), ('abmon', ('ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም')), ('mon', ('ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር')), ('d_t_fmt', '%A፣ %B %e ጋላሳ %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('wo_SN', [('abday', ('dib', 'alt', 'tal', 'all', 'alx', 'ajj', 'gaa')), ('day', ("dib'eer", 'altine', 'talaata', 'allarba', 'alxames', 'ajjuma', 'gaawu')), ('abmon', ('san', 'fee', 'mar', 'awr', 'me ', 'suw', 'sul', 'uut', 'sep', 'okt', 'now', 'des')), ('mon', ("sanwiy'e", "feebriy'e", 'mars', 'awril', 'me', 'suwen', 'sulet', 'uut', 'septaambar', 'oktoobar', 'nowaambar', 'desaambar')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[wWyY].*'), ('noexpr', '^[dDnN].*')]), ('xh_ZA', [('abday', ('Caw', 'Mvu', 'Bin', 'Tha', 'Sin', 'Hla', 'Mgq')), ('day', ('iCawa', 'uMvulo', 'lwesiBini', 'lwesiThathu', 'ulweSine', 'lwesiHlanu', 'uMgqibelo')), ('abmon', ('Mqu', 'Mdu', 'Kwi', 'Tsh', 'Can', 'Sil', 'Kha', 'Thu', 'Msi', 'Dwa', 'Nka', 'Mng')), ('mon', ('eyoMqungu', 'eyoMdumba', 'eyoKwindla', 'uTshazimpuzi', 'uCanzibe', 'eyeSilimela', 'eyeKhala', 'eyeThupa', 'eyoMsintsi', 'eyeDwarha', 'eyeNkanga', 'eyoMnga')), ('d_t_fmt', '%a %-e %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('yi_US', [('abday', ("זונ'", "מאָנ'", "דינ'", "מיט'", "דאָנ'", "פֿרײַ'", 'שבת')), ('day', ('זונטיק', 'מאָנטיק', 'דינסטיק', 'מיטװאָך', 'דאָנערשטיק', 'פֿרײַטיק', 'שבת')), ('abmon', ('יאַנ', 'פֿעב', 'מאַר', 'אַפּר', 'מײַ ', 'יונ', 'יול', 'אױג', 'סעפּ', 'אָקט', 'נאָװ', 'דעצ')), ('mon', ('יאַנואַר', 'פֿעברואַר', 'מאַרץ', 'אַפּריל', 'מײַ', 'יוני', 'יולי', 'אױגוסט', 'סעפּטעמבער', 'אָקטאָבער', 'נאָװעמבער', 'דעצעמבער')), ('d_t_fmt', '%Z %H:%M:%S %Y %b %d %a'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S %P'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Yyי].*'), ('noexpr', '^[Nnנק].*')]), ('yo_NG', [('abday', ('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT')), ('day', ('Àìkú', 'Ajé', 'Ìṣẹ́gun', 'Ọjọ́rú', 'Ọjọ́bọ̀', 'Ẹ̀tì', 'Àbámẹ́ta')), ('abmon', ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC')), ('mon', ('Jánúárì', 'Fẹ́búárì', 'Máàṣì', 'Épírì', 'Méè', 'Júùnù', 'Júláì', 'Ọ́ọ́gọsì', 'Sẹ̀tẹ̀ńbà', 'Ọtóbà', 'Nòfẹ̀ńbà', 'Dìsẹ̀ńbà')), ('d_t_fmt', 'ọjọ́ %A, %d oṣù %B ọdún %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[EeyY].*'), ('noexpr', '^[rROoKkNn].*')]), ('yue_HK', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', ('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 %A %H點%M分%S秒'), ('d_fmt', '%Y年%m月%d日 %A'), ('t_fmt', '%H點%M分%S秒'), ('t_fmt_ampm', '%p%I點%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('zh_CN', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', ('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 %A %H时%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H时%M分%S秒'), ('t_fmt_ampm', '%p %I时%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN不否]')]), ('zh_HK', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', ('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 %A %H:%M:%S'), ('d_fmt', '%Y年%m月%d日 %A'), ('t_fmt', '%I時%M分%S秒 %Z'), ('t_fmt_ampm', '%p %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN不否]')]), ('zh_SG', [('abday', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 %H时%M分%S秒 %Z'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H时%M分%S秒 %Z'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('zh_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('週日', '週一', '週二', '週三', '週四', '週五', '週六')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '西元%Y年%m月%d日 (%A) %H時%M分%S秒'), ('d_fmt', '西元%Y年%m月%d日'), ('t_fmt', '%H時%M分%S秒'), ('t_fmt_ampm', '%p %I時%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN不否]')]), ('zu_ZA', [('abday', ('Son', 'Mso', 'Bil', 'Tha', 'Sin', 'Hla', 'Mgq')), ('day', ('iSonto', 'uMsombuluko', 'uLwesibili', 'uLwesithathu', 'uLwesine', 'uLwesihlanu', 'uMgqibelo')), ('abmon', ('Mas', 'Ola', 'Nda', 'Mba', 'Aba', 'Ang', 'Ntu', 'Ncw', 'Man', 'Mfu', 'Lwe', 'Zib')), ('mon', ('uMasingana', 'uNhlolanja', 'uNdasa', 'uMbasa', 'uNhlaba', 'uNhlangulana', 'uNtulikazi', 'uNcwaba', 'uMandulo', 'uMfumfu', 'uLwezi', 'uZibandlela')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nNcC]')])] # }}}
203,563
Python
.py
3,892
40.984841
157
0.428652
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,355
check.py
kovidgoyal_calibre/setup/check.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import hashlib import json import os import subprocess from setup import Command, build_cache_dir, dump_json, edit_file class Message: def __init__(self, filename, lineno, msg): self.filename, self.lineno, self.msg = filename, lineno, msg def __str__(self): return f'{self.filename}:{self.lineno}: {self.msg}' def checkable_python_files(SRC): for dname in ('odf', 'calibre'): for x in os.walk(os.path.join(SRC, dname)): for f in x[-1]: y = os.path.join(x[0], f) if (f.endswith('.py') and f not in ( 'dict_data.py', 'unicodepoints.py', 'krcodepoints.py', 'jacodepoints.py', 'vncodepoints.py', 'zhcodepoints.py') and 'prs500/driver.py' not in y) and not f.endswith('_ui.py'): yield y class Check(Command): description = 'Check for errors in the calibre source code' CACHE = 'check.json' def get_files(self): yield from checkable_python_files(self.SRC) for x in os.walk(self.j(self.d(self.SRC), 'recipes')): for f in x[-1]: f = self.j(x[0], f) if f.endswith('.recipe'): yield f for x in os.walk(self.j(self.SRC, 'pyj')): for f in x[-1]: f = self.j(x[0], f) if f.endswith('.pyj'): yield f if self.has_changelog_check: yield self.j(self.d(self.SRC), 'Changelog.txt') def read_file(self, f): with open(f, 'rb') as f: return f.read() def file_hash(self, f): try: return self.fhash_cache[f] except KeyError: self.fhash_cache[f] = ans = hashlib.sha1(self.read_file(f)).hexdigest() return ans def is_cache_valid(self, f, cache): return cache.get(f) == self.file_hash(f) @property def cache_file(self): return self.j(build_cache_dir(), self.CACHE) def save_cache(self, cache): dump_json(cache, self.cache_file) def file_has_errors(self, f): ext = os.path.splitext(f)[1] if ext in {'.py', '.recipe'}: p2 = subprocess.Popen(['ruff', 'check', f]) return p2.wait() != 0 if ext == '.pyj': p = subprocess.Popen(['rapydscript', 'lint', f]) return p.wait() != 0 if ext == '.yaml': p = subprocess.Popen(['python', self.j(self.wn_path, 'whats_new.py'), f]) return p.wait() != 0 def run(self, opts): self.fhash_cache = {} cache = {} self.wn_path = os.path.expanduser('~/work/srv/main/static') self.has_changelog_check = os.path.exists(self.wn_path) try: with open(self.cache_file, 'rb') as f: cache = json.load(f) except OSError as err: if err.errno != errno.ENOENT: raise dirty_files = tuple(f for f in self.get_files() if not self.is_cache_valid(f, cache)) try: for i, f in enumerate(dirty_files): self.info('\tChecking', f) if self.file_has_errors(f): self.info('%d files left to check' % (len(dirty_files) - i - 1)) edit_file(f) if self.file_has_errors(f): raise SystemExit(1) cache[f] = self.file_hash(f) finally: self.save_cache(cache) def report_errors(self, errors): for err in errors: self.info('\t\t', str(err)) def clean(self): try: os.remove(self.cache_file) except OSError as err: if err.errno != errno.ENOENT: raise class UpgradeSourceCode(Command): description = 'Upgrade python source code' def run(self, opts): files = [] for f in os.listdir(os.path.dirname(os.path.abspath(__file__))): q = os.path.join('setup', f) if f.endswith('.py') and f not in ('linux-installer.py',) and not os.path.isdir(q): files.append(q) for path in checkable_python_files(self.SRC): q = path.replace(os.sep, '/') if '/metadata/sources/' in q or '/store/stores/' in q: continue files.append(q) subprocess.call(['pyupgrade', '--py38-plus'] + files)
4,596
Python
.py
115
29.243478
95
0.537857
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,356
win-ci.py
kovidgoyal_calibre/setup/win-ci.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import io import os import subprocess import sys import tarfile import time def printf(*args, **kw): print(*args, **kw) sys.stdout.flush() def download_file(url): from urllib.request import urlopen count = 5 while count > 0: count -= 1 try: printf('Downloading', url) return urlopen(url).read() except Exception: if count <= 0: raise print('Download failed retrying...') time.sleep(1) def sw(): sw = os.environ['SW'] os.chdir(sw) url = 'https://download.calibre-ebook.com/ci/calibre7/windows-64.tar.xz' tarball = download_file(url) with tarfile.open(fileobj=io.BytesIO(tarball)) as tf: tf.extractall() printf('Download complete') def sanitize_path(): needed_paths = [] executables = 'git.exe curl.exe rapydscript.cmd node.exe'.split() for p in os.environ['PATH'].split(os.pathsep): for x in tuple(executables): if os.path.exists(os.path.join(p, x)): needed_paths.append(p) executables.remove(x) sw = os.environ['SW'] paths = r'{0}\private\python\bin {0}\private\python\Lib\site-packages\pywin32_system32 {0}\bin {0}\qt\bin C:\Windows\System32'.format( sw ).split() + needed_paths os.environ['PATH'] = os.pathsep.join(paths) print('PATH:', os.environ['PATH']) def python_exe(): return os.path.join(os.environ['SW'], 'private', 'python', 'python.exe') def build(): sanitize_path() cmd = [python_exe(), 'setup.py', 'bootstrap', '--ephemeral'] printf(*cmd) p = subprocess.Popen(cmd) raise SystemExit(p.wait()) def test(): sanitize_path() for q in ('test', 'test_rs'): cmd = [python_exe(), 'setup.py', q] printf(*cmd) p = subprocess.Popen(cmd) if p.wait() != 0: raise SystemExit(p.returncode) def setup_env(): os.environ['SW'] = SW = r'C:\r\sw64\sw' os.makedirs(SW, exist_ok=True) os.environ['QMAKE'] = os.path.join(SW, r'qt\bin\qmake') os.environ['CALIBRE_QT_PREFIX'] = os.path.join(SW, r'qt') os.environ['CI'] = 'true' os.environ['OPENSSL_MODULES'] = os.path.join(SW, 'lib', 'ossl-modules') os.environ['PIPER_TTS_DIR'] = os.path.join(SW, 'piper') def main(): q = sys.argv[-1] setup_env() if q == 'bootstrap': build() elif q == 'test': test() elif q == 'install': sw() else: if len(sys.argv) == 1: raise SystemExit('Usage: win-ci.py sw|build|test') raise SystemExit('%r is not a valid action' % sys.argv[-1]) if __name__ == '__main__': main()
2,783
Python
.py
85
26.447059
138
0.599028
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,357
installers.py
kovidgoyal_calibre/setup/installers.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import binascii import json import os import subprocess import sys from setup import Command d = os.path.dirname def get_paths(): base = d(d(os.path.abspath(__file__))) bypy = os.path.join(d(base), 'bypy') bypy = os.environ.get('BYPY_LOCATION', bypy) if not os.path.isdir(bypy): raise SystemExit( 'Cannot find the bypy code. Set the environment variable BYPY_LOCATION to point to it' ) return base, bypy def get_exe(): return 'python3' if sys.version_info.major == 2 else sys.executable def get_cmd(exe, bypy, which, bitness, sign_installers=False, notarize=True, compression_level='9', action='program', dont_strip=False): cmd = [exe, bypy, which] if bitness and bitness != '64': cmd += ['--arch', bitness] cmd.append(action) if action == 'program': if sign_installers or notarize: cmd.append('--sign-installers') if notarize: cmd.append('--notarize') if dont_strip: cmd.append('--dont-strip') cmd.append('--compression-level=' + compression_level) return cmd def get_dist(base, which, bitness): dist = os.path.join(base, 'bypy', 'b', which) if bitness: dist = os.path.join(dist, bitness) for q in 'dist sw/dist'.split(): if os.path.exists(os.path.join(dist, q)): dist = os.path.join(dist, q) break return dist def shutdown_allowed(which, bitness): # The ARM64 VM is extremely flakey often booting up to a non-functional # state so dont shut it down as it seems to be more stable once bootup is # done. return bitness != 'arm64' def build_only(which, bitness, spec, shutdown=False): base, bypy = get_paths() exe = get_exe() cmd = get_cmd(exe, bypy, which, bitness, False) cmd.extend(['--build-only', spec]) ret = subprocess.Popen(cmd).wait() if ret != 0: raise SystemExit(ret) dist = get_dist(base, which, bitness) dist = os.path.join(dist, 'c-extensions') if shutdown and shutdown_allowed(which, bitness): cmd = get_cmd(exe, bypy, which, bitness, action='shutdown') subprocess.Popen(cmd).wait() return dist def build_single(which='windows', bitness='64', shutdown=True, sign_installers=True, notarize=True, compression_level='9', dont_strip=False): base, bypy = get_paths() exe = get_exe() cmd = get_cmd(exe, bypy, which, bitness, sign_installers, notarize, compression_level=compression_level, dont_strip=dont_strip) ret = subprocess.Popen(cmd).wait() if ret != 0: raise SystemExit(ret) dist = get_dist(base, which, bitness) for x in os.listdir(dist): src = os.path.join(dist, x) if os.path.isdir(src): continue print(x) dest = os.path.join(base, 'dist', x) try: os.remove(dest) except OSError: pass os.link(src, dest) if shutdown and shutdown_allowed(which, bitness): cmd = get_cmd(exe, bypy, which, bitness, action='shutdown') subprocess.Popen(cmd).wait() def build_dep(args): base, bypy = get_paths() exe = get_exe() pl = args[0] args.insert(1, 'dependencies') if '-' in pl: args[0:1] = pl.split('-')[0], f'--arch={pl.split("-")[-1]}' cmd = [exe, bypy] + list(args) ret = subprocess.Popen(cmd).wait() if ret != 0: raise SystemExit(ret) class BuildInstaller(Command): OS = '' BITNESS = '' def add_options(self, parser): parser.add_option( '--dont-shutdown', default=False, action='store_true', help='Do not shutdown the VM after building' ) parser.add_option( '--dont-sign', default=False, action='store_true', help='Do not sign the installers' ) parser.add_option( '--dont-notarize', default=False, action='store_true', help='Do not notarize the installers' ) parser.add_option( '--compression-level', default='9', choices=list('123456789'), help='Do not notarize the installers' ) parser.add_option( '--dont-strip', default=False, action='store_true', help='Do not strip the binaries' ) def run(self, opts): build_single( self.OS, self.BITNESS, not opts.dont_shutdown, not opts.dont_sign, not opts.dont_notarize, compression_level=opts.compression_level, dont_strip=opts.dont_strip ) class BuildInstallers(BuildInstaller): OS = '' ALL_ARCHES = '64', def run(self, opts): for bitness in self.ALL_ARCHES: shutdown = bitness is self.ALL_ARCHES[-1] and not opts.dont_shutdown build_single(self.OS, bitness, shutdown) class Linux64(BuildInstaller): OS = 'linux' BITNESS = '64' description = 'Build the 64-bit Linux calibre installer' class LinuxArm64(BuildInstaller): OS = 'linux' BITNESS = 'arm64' description = 'Build the 64-bit ARM Linux calibre installer' class Win64(BuildInstaller): OS = 'windows' BITNESS = '64' description = 'Build the 64-bit windows calibre installer' class OSX(BuildInstaller): OS = 'macos' class Linux(BuildInstallers): OS = 'linux' ALL_ARCHES = '64', 'arm64' class Win(BuildInstallers): OS = 'windows' class BuildDep(Command): description = ( 'Build a calibre dependency. For example, build_dep windows expat.' ' Without arguments builds all deps for specified platform. Use linux-arm64 for Linux ARM.' ' Use build_dep all somedep to build a dep for all platforms.' ) def run(self, opts): args = opts.cli_args if args and args[0] == 'all': for x in ('linux', 'linux-arm64', 'macos', 'windows'): build_dep(x.split() + list(args)[1:]) else: build_dep(args) class ExportPackages(Command): description = 'Export built deps to a server for CI testing' def run(self, opts): base, bypy = get_paths() exe = get_exe() for which in ('linux', 'macos', 'windows'): cmd = [exe, bypy, 'export'] + ['download.calibre-ebook.com:/srv/download/ci/calibre7'] + [which] ret = subprocess.Popen(cmd).wait() if ret != 0: raise SystemExit(ret) class ExtDev(Command): description = 'Develop a single native extension conveniently' def run(self, opts): which, ext = opts.cli_args[:2] cmd = opts.cli_args[2:] or ['calibre-debug', '--test-build'] if which == 'windows': cp = subprocess.run([sys.executable, 'setup.py', 'build', '--cross-compile-extensions=windows', f'--only={ext}']) if cp.returncode != 0: raise SystemExit(cp.returncode) src = f'src/calibre/plugins/{ext}.cross-windows-x64.pyd' host = 'win' path = '/cygdrive/c/Program Files/Calibre2/app/bin/{}.pyd' bin_dir = '/cygdrive/c/Program Files/Calibre2' elif which == 'macos': ext_dir = build_only(which, '', ext) src = os.path.join(ext_dir, f'{ext}.so') print( "\n\n\x1b[33;1mWARNING: This does not work on macOS, unless you use un-signed builds with ", ' ./update-on-ox develop\x1b[m', file=sys.stderr, end='\n\n\n') host = 'ox' path = '/Applications/calibre.app/Contents/Frameworks/plugins/{}.so' bin_dir = '/Applications/calibre.app/Contents/MacOS' else: raise SystemExit(f'Unknown OS {which}') control_path = os.path.expanduser('~/.ssh/extdev-master-%C') if subprocess.Popen([ 'ssh', '-o', 'ControlMaster=auto', '-o', 'ControlPath=' + control_path, '-o', 'ControlPersist=yes', host, 'echo', 'ssh master running' ]).wait() != 0: raise SystemExit(1) try: path = path.format(ext) subprocess.check_call(['ssh', '-S', control_path, host, 'chmod', '+wx', f'"{path}"']) with open(src, 'rb') as f: p = subprocess.Popen(['ssh', '-S', control_path, host, f'cat - > "{path}"'], stdin=subprocess.PIPE) p.communicate(f.read()) if p.wait() != 0: raise SystemExit(1) subprocess.check_call(['ssh', '-S', control_path, host, './update-calibre']) enc = json.dumps(cmd) if not isinstance(enc, bytes): enc = enc.encode('utf-8') enc = binascii.hexlify(enc).decode('ascii') wcmd = ['"{}"'.format(os.path.join(bin_dir, 'calibre-debug')), '-c', '"' 'import sys, json, binascii, os, subprocess; cmd = json.loads(binascii.unhexlify(sys.argv[-1]));' 'env = os.environ.copy();' '''env[str('CALIBRE_DEVELOP_FROM')] = str(os.path.abspath('calibre-src/src'));''' 'from calibre.debug import get_debug_executable; exe_dir = os.path.dirname(get_debug_executable()[0]);' 'cmd[0] = os.path.join(exe_dir, cmd[0]); ret = subprocess.Popen(cmd, env=env).wait();' 'sys.stdout.flush(); sys.stderr.flush(); sys.exit(ret)' '"', enc] ret = subprocess.Popen(['ssh', '-S', control_path, host] + wcmd).wait() if ret != 0: raise SystemExit('The test command "{}" failed with exit code: {}'.format(' '.join(cmd), ret)) finally: subprocess.Popen(['ssh', '-O', 'exit', '-S', control_path, host])
9,917
Python
.py
241
32.224066
141
0.585221
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,358
translations.py
kovidgoyal_calibre/setup/translations.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import glob import hashlib import json import os import re import shlex import shutil import subprocess import sys import tempfile import textwrap import time from collections import defaultdict from functools import partial from locale import normalize as normalize_locale from polyglot.builtins import codepoint_to_chr, iteritems from setup import Command, __appname__, __version__, build_cache_dir, dump_json, edit_file, is_ci, require_git_master from setup.iso_codes import iso_data from setup.parallel_build import batched_parallel_jobs def qt_sources(): qtdir = os.environ.get('QT_SRC', '/usr/src/qt6/qtbase') j = partial(os.path.join, qtdir) return list(map(j, [ 'src/gui/kernel/qplatformtheme.cpp', 'src/widgets/dialogs/qcolordialog.cpp', 'src/widgets/dialogs/qfontdialog.cpp', 'src/widgets/widgets/qscrollbar.cpp', ])) class POT(Command): # {{{ description = 'Update the .pot translation template and upload it' TRANSLATIONS = os.path.join(os.path.dirname(Command.SRC), 'translations') MANUAL = os.path.join(os.path.dirname(Command.SRC), 'manual') def tx(self, cmd, **kw): kw['cwd'] = kw.get('cwd', self.TRANSLATIONS) if hasattr(cmd, 'format'): cmd = shlex.split(cmd) cmd = [os.environ.get('TX', 'tx')] + cmd self.info(' '.join(cmd)) return subprocess.check_call(cmd, **kw) def git(self, cmd, **kw): kw['cwd'] = kw.get('cwd', self.TRANSLATIONS) if hasattr(cmd, 'format'): cmd = shlex.split(cmd) f = getattr(subprocess, ('call' if kw.pop('use_call', False) else 'check_call')) return f(['git'] + cmd, **kw) def upload_pot(self, resource): self.tx(['push', '-r', 'calibre.'+resource, '-s'], cwd=self.TRANSLATIONS) def source_files(self): ans = [self.a(self.j(self.MANUAL, x)) for x in ('custom.py', 'conf.py')] for root, _, files in os.walk(self.j(self.SRC, __appname__)): for name in files: if name.endswith('.py'): ans.append(self.a(self.j(root, name))) return ans def get_tweaks_docs(self): path = self.a(self.j(self.SRC, '..', 'resources', 'default_tweaks.py')) with open(path, 'rb') as f: raw = f.read().decode('utf-8') msgs = [] lines = list(raw.splitlines()) for i, line in enumerate(lines): if line.startswith('#:'): msgs.append((i, line[2:].strip())) j = i block = [] while True: j += 1 line = lines[j] if not line.startswith('#'): break block.append(line[1:].strip()) if block: msgs.append((i+1, '\n'.join(block))) ans = [] for lineno, msg in msgs: ans.append('#: %s:%d'%(path, lineno)) slash = codepoint_to_chr(92) msg = msg.replace(slash, slash*2).replace('"', r'\"').replace('\n', r'\n').replace('\r', r'\r').replace('\t', r'\t') ans.append('msgid "%s"'%msg) ans.append('msgstr ""') ans.append('') return '\n'.join(ans) def get_content_server_strings(self): self.info('Generating translation template for content_server') from calibre import walk from calibre.utils.rapydscript import create_pot files = (f for f in walk(self.j(self.SRC, 'pyj')) if f.endswith('.pyj')) pottext = create_pot(files).encode('utf-8') dest = self.j(self.TRANSLATIONS, 'content-server', 'content-server.pot') with open(dest, 'wb') as f: f.write(pottext) self.upload_pot(resource='content_server') self.git(['add', dest]) def get_user_manual_docs(self): self.info('Generating translation templates for user_manual') base = tempfile.mkdtemp() subprocess.check_call([sys.executable, self.j(self.d(self.SRC), 'manual', 'build.py'), 'gettext', base]) tbase = self.j(self.TRANSLATIONS, 'manual') for x in os.listdir(base): if not x.endswith('.pot'): continue src, dest = self.j(base, x), self.j(tbase, x) needs_import = not os.path.exists(dest) with open(src, 'rb') as s, open(dest, 'wb') as d: shutil.copyfileobj(s, d) bname = os.path.splitext(x)[0] slug = 'user_manual_' + bname if needs_import: self.tx(['set', '-r', 'calibre.' + slug, '--source', '-l', 'en', '-t', 'PO', dest]) with open(self.j(self.d(tbase), '.tx/config'), 'r+b') as f: lines = f.read().decode('utf-8').splitlines() for i in range(len(lines)): line = lines[i].strip() if line == '[calibre.%s]' % slug: lines.insert(i+1, 'file_filter = manual/<lang>/%s.po' % bname) f.seek(0), f.truncate(), f.write('\n'.join(lines).encode('utf-8')) break else: raise SystemExit(f'Failed to add file_filter for slug={slug} to config file') self.git('add .tx/config') self.upload_pot(resource=slug) self.git(['add', dest]) shutil.rmtree(base) def get_website_strings(self): self.info('Generating translation template for website') self.wn_path = os.path.expanduser('~/work/srv/main/static/generate.py') data = subprocess.check_output([self.wn_path, '--pot', '/tmp/wn']) data = json.loads(data) def do(name): messages = data[name] bdir = os.path.join(self.TRANSLATIONS, name) if not os.path.exists(bdir): os.makedirs(bdir) pot = os.path.abspath(os.path.join(bdir, name + '.pot')) with open(pot, 'wb') as f: f.write(self.pot_header().encode('utf-8')) f.write(b'\n') f.write('\n'.join(messages).encode('utf-8')) self.upload_pot(resource=name) self.git(['add', pot]) do('website') do('changelog') def pot_header(self, appname=__appname__, version=__version__): return textwrap.dedent('''\ # Translation template file.. # Copyright (C) %(year)s Kovid Goyal # Kovid Goyal <kovid@kovidgoyal.net>, %(year)s. # msgid "" msgstr "" "Project-Id-Version: %(appname)s %(version)s\\n" "POT-Creation-Date: %(time)s\\n" "PO-Revision-Date: %(time)s\\n" "Last-Translator: Automatically generated\\n" "Language-Team: LANGUAGE\\n" "MIME-Version: 1.0\\n" "Report-Msgid-Bugs-To: https://bugs.launchpad.net/calibre\\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: 8bit\\n" ''')%dict(appname=appname, version=version, year=time.strftime('%Y'), time=time.strftime('%Y-%m-%d %H:%M+%Z')) def run(self, opts): if not is_ci: require_git_master() if not is_ci: self.get_website_strings() self.get_content_server_strings() self.get_user_manual_docs() files = self.source_files() qt_inputs = qt_sources() pot_header = self.pot_header() with tempfile.NamedTemporaryFile() as fl: fl.write('\n'.join(files).encode('utf-8')) fl.flush() out = tempfile.NamedTemporaryFile(suffix='.pot', delete=False) out.close() self.info('Creating translations template...') subprocess.check_call(['xgettext', '-f', fl.name, '--default-domain=calibre', '-o', out.name, '-L', 'Python', '--from-code=UTF-8', '--sort-by-file', '--omit-header', '--no-wrap', '-k__', '-kpgettext:1c,2', '--add-comments=NOTE:', ]) subprocess.check_call(['xgettext', '-j', '--default-domain=calibre', '-o', out.name, '--from-code=UTF-8', '--sort-by-file', '--omit-header', '--no-wrap', '-kQT_TRANSLATE_NOOP:2', '-ktr', '-ktranslate:2', ] + qt_inputs) with open(out.name, 'rb') as f: src = f.read().decode('utf-8') os.remove(out.name) src = pot_header + '\n' + src src += '\n\n' + self.get_tweaks_docs() bdir = os.path.join(self.TRANSLATIONS, __appname__) if not os.path.exists(bdir): os.makedirs(bdir) pot = os.path.join(bdir, 'main.pot') # Workaround for bug in xgettext: # https://savannah.gnu.org/bugs/index.php?41668 src = re.sub(r'#, python-brace-format\s+msgid ""\s+.*<code>{0:</code>', lambda m: m.group().replace('python-brace', 'no-python-brace'), src) with open(pot, 'wb') as f: f.write(src.encode('utf-8')) self.info('Translations template:', os.path.abspath(pot)) self.upload_pot(resource='main') self.git(['add', os.path.abspath(pot)]) if not is_ci and self.git('diff-index --cached --quiet --ignore-submodules HEAD --', use_call=True) != 0: self.git(['commit', '-m', 'Updated translation templates']) self.git('push') return pot # }}} class Translations(POT): # {{{ description='''Compile the translations''' DEST = os.path.join(os.path.dirname(POT.SRC), 'resources', 'localization', 'locales') @property def cache_dir(self): ans = self.j(build_cache_dir(), 'translations') if not hasattr(self, 'cache_dir_created'): self.cache_dir_created = True try: os.mkdir(ans) except OSError as err: if err.errno != errno.EEXIST: raise return ans def cache_name(self, f): f = os.path.relpath(f, self.d(self.SRC)) return f.replace(os.sep, '.').replace('/', '.').lstrip('.') def read_cache(self, f): cname = self.cache_name(f) try: with open(self.j(self.cache_dir, cname), 'rb') as f: data = f.read() return data[:20], data[20:] except OSError as err: if err.errno != errno.ENOENT: raise return None, None def write_cache(self, data, h, f): cname = self.cache_name(f) assert len(h) == 20 with open(self.j(self.cache_dir, cname), 'wb') as f: f.write(h), f.write(data) def is_po_file_ok(self, x): bname = os.path.splitext(os.path.basename(x))[0] # sr@latin.po is identical to sr.po. And we dont support country # specific variants except for a few. if '_' in bname: return bname.partition('_')[0] in ('pt', 'zh', 'bn') return bname != 'sr@latin' def po_files(self): return [x for x in glob.glob(os.path.join(self.TRANSLATIONS, __appname__, '*.po')) if self.is_po_file_ok(x)] def mo_file(self, po_file): locale = os.path.splitext(os.path.basename(po_file))[0] return locale, os.path.join(self.DEST, locale, 'messages.mo') def run(self, opts): self.compile_main_translations() self.compile_content_server_translations() self.freeze_locales() self.compile_user_manual_translations() self.compile_website_translations() self.compile_changelog_translations() def compile_group(self, files, handle_stats=None, action_per_file=None, make_translated_strings_unique=False, keyfunc=lambda x: x): ok_files = [] hashmap = {} def stats_cache(src, data=None): cname = self.cache_name(keyfunc(src)) + '.stats.json' with open(self.j(self.cache_dir, cname), ('rb' if data is None else 'wb')) as f: if data is None: return json.loads(f.read()) data = json.dumps(data) if not isinstance(data, bytes): data = data.encode('utf-8') f.write(data) for src, dest in files: base = os.path.dirname(dest) if not os.path.exists(base): os.makedirs(base) data, h = self.hash_and_data(src, keyfunc) current_hash = h.digest() saved_hash, saved_data = self.read_cache(keyfunc(src)) if current_hash == saved_hash: with open(dest, 'wb') as d: d.write(saved_data) if handle_stats is not None: handle_stats(src, stats_cache(src)) else: ok_files.append((src, dest)) hashmap[keyfunc(src)] = current_hash if action_per_file is not None: action_per_file(src) self.info(f'\tCompiling {len(ok_files)} files') items = [] results = batched_parallel_jobs( [sys.executable, self.j(self.SRC, 'calibre', 'translations', 'msgfmt.py'), 'STDIN', 'uniqify' if make_translated_strings_unique else ' '], ok_files) for (src, dest), data in zip(ok_files, results): items.append((src, dest, data)) for (src, dest, data) in items: self.write_cache(open(dest, 'rb').read(), hashmap[keyfunc(src)], keyfunc(src)) stats_cache(src, data) if handle_stats is not None: handle_stats(src, data) def compile_main_translations(self): l = {} lc_dataf = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lc_data.py') exec(compile(open(lc_dataf, 'rb').read(), lc_dataf, 'exec'), l, l) lcdata = {k:{k1:v1 for k1, v1 in v} for k, v in l['data']} self.info('Compiling main UI translation files...') fmap = {f:self.mo_file(f) for f in self.po_files()} files = [(f, fmap[f][1]) for f in self.po_files()] def action_per_file(f): locale, dest = fmap[f] ln = normalize_locale(locale).partition('.')[0] if ln in lcdata: ld = lcdata[ln] lcdest = self.j(self.d(dest), 'lcdata.calibre_msgpack') from calibre.utils.serialize import msgpack_dumps with open(lcdest, 'wb') as lcf: lcf.write(msgpack_dumps(ld)) stats = {} def handle_stats(f, data): trans, untrans = data['translated'], data['untranslated'] total = trans + untrans locale = fmap[f][0] stats[locale] = min(1.0, float(trans)/total) self.compile_group(files, handle_stats=handle_stats, action_per_file=action_per_file) self.info('Compiling ISO639 files...') files = [] skip_iso = { 'si', 'te', 'km', 'en_GB', 'en_AU', 'en_CA', 'yi', 'ku', 'my', 'uz@Latn', 'fil', 'hy', 'ltg', 'km_KH', 'km', 'ur', 'ml', 'fo', 'ug', 'jv', 'nds', } def handle_stats(f, data): if False and data['uniqified']: print(f'{data["uniqified"]:3d} non-unique language name translations in {os.path.basename(f)}', file=sys.stderr) with tempfile.TemporaryDirectory() as tdir: iso_data.extract_po_files('iso_639-3', tdir) for f, (locale, dest) in iteritems(fmap): iscpo = {'zh_HK':'zh_CN'}.get(locale, locale) iso639 = self.j(tdir, '%s.po'%iscpo) if os.path.exists(iso639): files.append((iso639, self.j(self.d(dest), 'iso639.mo'))) else: iscpo = iscpo.partition('_')[0] iso639 = self.j(tdir, '%s.po'%iscpo) if os.path.exists(iso639): files.append((iso639, self.j(self.d(dest), 'iso639.mo'))) elif locale not in skip_iso: self.warn('No ISO 639 translations for locale:', locale) self.compile_group(files, make_translated_strings_unique=True, handle_stats=handle_stats, keyfunc=lambda x: os.path.join(self.d(self.SRC), 'iso639', os.path.basename(x))) self.info('Compiling ISO3166 files...') files = [] skip_iso = { 'en_GB', 'en_AU', 'en_CA', 'yi', 'ku', 'uz@Latn', 'ltg', 'nds', 'jv' } with tempfile.TemporaryDirectory() as tdir: iso_data.extract_po_files('iso_3166-1', tdir) for f, (locale, dest) in iteritems(fmap): pofile = self.j(tdir, f'{locale}.po') if os.path.exists(pofile): files.append((pofile, self.j(self.d(dest), 'iso3166.mo'))) else: pofile = self.j(tdir, f'{locale.partition("_")[0]}.po') if os.path.exists(pofile): files.append((pofile, self.j(self.d(dest), 'iso3166.mo'))) elif locale not in skip_iso: self.warn('No ISO 3166 translations for locale:', locale) self.compile_group(files, make_translated_strings_unique=True, handle_stats=lambda f,d:None, keyfunc=lambda x: os.path.join(self.d(self.SRC), 'iso3166', os.path.basename(x))) dest = self.stats base = self.d(dest) try: os.mkdir(base) except OSError as err: if err.errno != errno.EEXIST: raise from calibre.utils.serialize import msgpack_dumps with open(dest, 'wb') as f: f.write(msgpack_dumps(stats)) def hash_and_data(self, f, keyfunc=lambda x:x): with open(f, 'rb') as s: data = s.read() h = hashlib.sha1(data) h.update(keyfunc(f).encode('utf-8')) return data, h def compile_content_server_translations(self): self.info('Compiling content-server translations') from calibre.utils.rapydscript import msgfmt from calibre.utils.zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo with ZipFile(self.j(self.RESOURCES, 'content-server', 'locales.zip'), 'w', ZIP_DEFLATED) as zf: for src in glob.glob(os.path.join(self.TRANSLATIONS, 'content-server', '*.po')): if not self.is_po_file_ok(src): continue data, h = self.hash_and_data(src) current_hash = h.digest() saved_hash, saved_data = self.read_cache(src) if current_hash == saved_hash: raw = saved_data else: # self.info('\tParsing ' + os.path.basename(src)) raw = None po_data = data.decode('utf-8') data = json.loads(msgfmt(po_data)) translated_entries = {k:v for k, v in iteritems(data['entries']) if v and sum(map(len, v))} data['entries'] = translated_entries data['hash'] = h.hexdigest() cdata = b'{}' if translated_entries: raw = json.dumps(data, ensure_ascii=False, sort_keys=True) if isinstance(raw, str): raw = raw.encode('utf-8') cdata = raw self.write_cache(cdata, current_hash, src) if raw: zi = ZipInfo(os.path.basename(src).rpartition('.')[0]) zi.compress_type = ZIP_STORED if is_ci else ZIP_DEFLATED zf.writestr(zi, raw) def freeze_locales(self): zf = self.DEST + '.zip' from calibre import CurrentDir from calibre.utils.zipfile import ZIP_DEFLATED, ZipFile with ZipFile(zf, 'w', ZIP_DEFLATED) as zf: with CurrentDir(self.DEST): zf.add_dir('.') shutil.rmtree(self.DEST) @property def stats(self): return self.j(self.d(self.DEST), 'stats.calibre_msgpack') def _compile_website_translations(self, name='website', threshold=50): from calibre.ptempfile import TemporaryDirectory from calibre.utils.localization import get_language, translator_for_lang from calibre.utils.zipfile import ZIP_STORED, ZipFile, ZipInfo self.info('Compiling', name, 'translations...') srcbase = self.j(self.d(self.SRC), 'translations', name) if not os.path.exists(srcbase): os.makedirs(srcbase) fmap = {} files = [] stats = {} done = [] def handle_stats(src, data): locale = fmap[src] trans, untrans = data['translated'], data['untranslated'] total = trans + untrans stats[locale] = int(round(100 * trans / total)) with TemporaryDirectory() as tdir, ZipFile(self.j(srcbase, 'locales.zip'), 'w', ZIP_STORED) as zf: for f in os.listdir(srcbase): if f.endswith('.po'): if not self.is_po_file_ok(f): continue l = f.partition('.')[0] pf = l.split('_')[0] if pf in {'en'}: continue d = os.path.join(tdir, l + '.mo') f = os.path.join(srcbase, f) fmap[f] = l files.append((f, d)) self.compile_group(files, handle_stats=handle_stats) for locale, translated in iteritems(stats): if translated >= threshold: with open(os.path.join(tdir, locale + '.mo'), 'rb') as f: raw = f.read() zi = ZipInfo(os.path.basename(f.name)) zi.compress_type = ZIP_STORED zf.writestr(zi, raw) done.append(locale) dl = done + ['en'] lang_names = {} for l in dl: translator = translator_for_lang(l)['translator'] t = translator.gettext t = partial(get_language, gettext_func=t) lang_names[l] = {x: t(x) for x in dl} zi = ZipInfo('lang-names.json') zi.compress_type = ZIP_STORED zf.writestr(zi, json.dumps(lang_names, ensure_ascii=False).encode('utf-8')) return done def compile_website_translations(self): done = self._compile_website_translations() dest = self.j(self.d(self.stats), 'website-languages.txt') data = ' '.join(sorted(done)) if not isinstance(data, bytes): data = data.encode('utf-8') with open(dest, 'wb') as f: f.write(data) def compile_changelog_translations(self): self._compile_website_translations('changelog', threshold=0) def compile_user_manual_translations(self): self.info('Compiling user manual translations...') srcbase = self.j(self.d(self.SRC), 'translations', 'manual') destbase = self.j(self.d(self.SRC), 'manual', 'locale') complete = {} all_stats = defaultdict(lambda : {'translated': 0, 'untranslated': 0}) files = [] for x in os.listdir(srcbase): q = self.j(srcbase, x) if not os.path.isdir(q) or not self.is_po_file_ok(q): continue dest = self.j(destbase, x, 'LC_MESSAGES') if os.path.exists(dest): shutil.rmtree(dest) os.makedirs(dest) for po in os.listdir(q): if not po.endswith('.po'): continue mofile = self.j(dest, po.rpartition('.')[0] + '.mo') files.append((self.j(q, po), mofile)) def handle_stats(src, data): locale = self.b(self.d(src)) stats = all_stats[locale] stats['translated'] += data['translated'] stats['untranslated'] += data['untranslated'] self.compile_group(files, handle_stats=handle_stats) for locale, stats in iteritems(all_stats): dump_json(stats, self.j(srcbase, locale, 'stats.json')) total = stats['translated'] + stats['untranslated'] # Raise the 30% threshold in the future if total and (stats['translated'] / float(total)) > 0.3: complete[locale] = stats dump_json(complete, self.j(destbase, 'completed.json')) def clean(self): if os.path.exists(self.stats): os.remove(self.stats) zf = self.DEST + '.zip' if os.path.exists(zf): os.remove(zf) destbase = self.j(self.d(self.SRC), 'manual', 'locale') if os.path.exists(destbase): shutil.rmtree(destbase) shutil.rmtree(self.cache_dir) # }}} class GetTranslations(Translations): # {{{ description = 'Get updated translations from Transifex' @property def is_modified(self): return bool(subprocess.check_output('git status --porcelain'.split(), cwd=self.TRANSLATIONS)) def add_options(self, parser): parser.add_option('-e', '--check-for-errors', default=False, action='store_true', help='Check for errors in .po files') def run(self, opts): require_git_master() if opts.check_for_errors: self.check_all() return self.tx('pull -a') if not self.is_modified: self.info('No translations were updated') return self.upload_to_vcs() self.check_all() def check_all(self): self.check_for_errors() self.check_for_user_manual_errors() if self.is_modified: self.upload_to_vcs('Fixed translations') def check_for_user_manual_errors(self): sys.path.insert(0, self.j(self.d(self.SRC), 'setup')) import polib del sys.path[0] self.info('Checking user manual translations...') srcbase = self.j(self.d(self.SRC), 'translations', 'manual') changes = defaultdict(set) for lang in os.listdir(srcbase): if lang.startswith('en_') or lang == 'en': continue q = self.j(srcbase, lang) if not os.path.isdir(q): continue for po in os.listdir(q): if not po.endswith('.po'): continue f = polib.pofile(os.path.join(q, po)) changed = False for entry in f.translated_entries(): if '`generated/en/' in entry.msgstr: changed = True entry.msgstr = entry.msgstr.replace('`generated/en/', '`generated/' + lang + '/') bname = os.path.splitext(po)[0] slug = 'user_manual_' + bname changes[slug].add(lang) if changed: f.save() for slug, languages in iteritems(changes): print('Pushing fixes for languages: {} in {}'.format(', '.join(languages), slug)) self.tx('push -r calibre.{} -t -l {}'.format(slug, ','.join(languages))) def check_for_errors(self): self.info('Checking for errors in .po files...') groups = 'calibre content-server website'.split() for group in groups: self.check_group(group) self.check_website() for group in groups: self.push_fixes(group) def push_fixes(self, group): languages = set() for line in subprocess.check_output('git status --porcelain'.split(), cwd=self.TRANSLATIONS).decode('utf-8').splitlines(): parts = line.strip().split() if len(parts) > 1 and 'M' in parts[0] and parts[-1].startswith(group + '/') and parts[-1].endswith('.po'): languages.add(os.path.basename(parts[-1]).partition('.')[0]) if languages: pot = 'main' if group == 'calibre' else group.replace('-', '_') print('Pushing fixes for {}.pot languages: {}'.format(pot, ', '.join(languages))) self.tx(f'push -r calibre.{pot} -t -l ' + ','.join(languages)) def check_group(self, group): files = glob.glob(os.path.join(self.TRANSLATIONS, group, '*.po')) cmd = ['msgfmt', '-o', os.devnull, '--check-format'] # Disabled because too many such errors, and not that critical anyway # if group == 'calibre': # cmd += ['--check-accelerators=&'] def check(f): p = subprocess.Popen(cmd + [f], stderr=subprocess.PIPE) errs = p.stderr.read() p.wait() return errs def check_for_control_chars(f): with open(f, 'rb') as f: raw = f.read().decode('utf-8') pat = re.compile(r'[\0-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]') errs = [] for i, line in enumerate(raw.splitlines()): if pat.search(line) is not None: errs.append(f'There are ASCII control codes on line number: {i + 1}') return '\n'.join(errs) for f in files: errs = check(f) if errs: print(f) print(errs) edit_file(f) if check(f): raise SystemExit('Aborting as not all errors were fixed') errs = check_for_control_chars(f) if errs: print(f, 'has ASCII control codes in it') print(errs) raise SystemExit(1) def check_website(self): errors = os.path.join(tempfile.gettempdir(), 'calibre-translation-errors') if os.path.exists(errors): shutil.rmtree(errors) os.mkdir(errors) tpath = self.j(self.TRANSLATIONS, 'website') pofilter = ('pofilter', '-i', tpath, '-o', errors, '-t', 'xmltags') subprocess.check_call(pofilter) errfiles = glob.glob(errors+os.sep+'*.po') if errfiles: subprocess.check_call([os.environ.get('EDITOR', 'vim'), '-f', '-p', '--']+errfiles) for f in errfiles: with open(f, 'r+b') as f: raw = f.read() raw = re.sub(rb'# \(pofilter\).*', b'', raw) f.seek(0) f.truncate() f.write(raw) subprocess.check_call(['pomerge', '-t', tpath, '-i', errors, '-o', tpath]) def upload_to_vcs(self, msg=None): self.info('Uploading updated translations to version control') cc = partial(subprocess.check_call, cwd=self.TRANSLATIONS) cc('git add */*.po'.split()) cc('git commit -am'.split() + [msg or 'Updated translations']) cc('git push'.split()) # }}} class ISO639(Command): # {{{ description = 'Compile language code maps for performance' sub_commands = ['iso_data'] DEST = os.path.join(os.path.dirname(POT.SRC), 'resources', 'localization', 'iso639.calibre_msgpack') def run(self, opts): dest = self.DEST base = self.d(dest) if not os.path.exists(base): os.makedirs(base) self.info('Packing ISO-639 codes to', dest) root = json.loads(iso_data.db_data('iso_639-3.json')) entries = root['639-3'] by_2 = {} by_3 = {} m2to3 = {} m3to2 = {} nm = {} codes2, codes3 = set(), set() unicode_type = str for x in entries: two = x.get('alpha_2') if two: two = unicode_type(two) threeb = x.get('alpha_3') if threeb: threeb = unicode_type(threeb) if threeb is None: continue name = x.get('inverted_name') or x.get('name') if name: name = unicode_type(name) if not name or name[0] in '!~=/\'"': continue if two is not None: by_2[two] = name codes2.add(two) m2to3[two] = threeb m3to2[threeb] = two codes3.add(threeb) by_3[threeb] = name base_name = name.lower() nm[base_name] = threeb x = {'by_2':by_2, 'by_3':by_3, 'codes2':codes2, 'codes3':codes3, '2to3':m2to3, '3to2':m3to2, 'name_map':nm} from calibre.utils.serialize import msgpack_dumps with open(dest, 'wb') as f: f.write(msgpack_dumps(x)) def clean(self): if os.path.exists(self.DEST): os.remove(self.DEST) # }}} class ISO3166(ISO639): # {{{ description = 'Compile country code maps for performance' sub_commands = ['iso_data'] DEST = os.path.join(os.path.dirname(POT.SRC), 'resources', 'localization', 'iso3166.calibre_msgpack') def run(self, opts): dest = self.DEST base = self.d(dest) if not os.path.exists(base): os.makedirs(base) self.info('Packing ISO-3166 codes to', dest) db = json.loads(iso_data.db_data('iso_3166-1.json')) codes = set() three_map = {} name_map = {} unicode_type = str for x in db['3166-1']: two = x.get('alpha_2') if two: two = unicode_type(two) codes.add(two) name_map[two] = x.get('common_name') or x.get('name') if name_map[two]: name_map[two] = unicode_type(name_map[two]) three = x.get('alpha_3') if three: three_map[unicode_type(three)] = two x = {'names':name_map, 'codes':frozenset(codes), 'three_map':three_map} from calibre.utils.serialize import msgpack_dumps with open(dest, 'wb') as f: f.write(msgpack_dumps(x)) # }}}
34,515
Python
.py
758
33.234828
150
0.535653
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,359
git_pre_commit_hook.py
kovidgoyal_calibre/setup/git_pre_commit_hook.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> import json import os import re import socket import subprocess import sys import urllib.error import urllib.parse import urllib.request from lxml import html ''' Hook to make the commit command automatically close bugs when the commit message contains `Fix #number` or `Implement #number`. Also updates the commit message with the summary of the closed bug. ''' LAUNCHPAD = os.path.expanduser('~/work/env/launchpad.py') LAUNCHPAD_BUG = 'https://bugs.launchpad.net/calibre/+bug/%s' GITHUB_BUG = 'https://api.github.com/repos/kovidgoyal/calibre/issues/%s' BUG_PAT = r'(Fix|Implement|Fixes|Fixed|Implemented|See)\s+#(\d+)' socket.setdefaulttimeout(90) class Bug: def __init__(self): self.seen = set() def __call__(self, match): action, bug = match.group(1), match.group(2) summary = '' if bug in self.seen: return match.group() self.seen.add(bug) if int(bug) > 100000: # Launchpad bug try: raw = urllib.request.urlopen(LAUNCHPAD_BUG % bug).read() h1 = html.fromstring(raw).xpath('//h1[@id="edit-title"]')[0] summary = html.tostring(h1, method='text', encoding=str).strip() except: summary = 'Private bug' else: summary = json.loads(urllib.request.urlopen(GITHUB_BUG % bug).read())['title'] if summary: print('Working on bug:', summary) if int(bug) > 100000 and action != 'See': self.close_bug(bug, action) return match.group() + f' [{summary}]({LAUNCHPAD_BUG % bug})' return match.group() + ' (%s)' % summary return match.group() def close_bug(self, bug, action): print('Closing bug #%s' % bug) suffix = ( 'The fix will be in the next release. ' 'calibre is usually released every alternate Friday.' ) action += 'ed' msg = '{} in branch {}. {}'.format(action, 'master', suffix) msg = msg.replace('Fixesed', 'Fixed') env = dict(os.environ) env['LAUNCHPAD_FIX_BUG'] = msg subprocess.run([sys.executable, LAUNCHPAD], env=env, input=f'Subject: [Bug {bug}]', text=True, check=True) def main(): with open(sys.argv[-1], 'r+b') as f: raw = f.read().decode('utf-8') bug = Bug() msg = re.sub(BUG_PAT, bug, raw) if msg != raw: f.seek(0) f.truncate() f.write(msg.encode('utf-8')) if __name__ == '__main__': main()
2,649
Python
.py
70
30.357143
114
0.598204
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,360
hyphenation.py
kovidgoyal_calibre/setup/hyphenation.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import glob import hashlib import json import os import shutil import tarfile from io import BytesIO from setup.revendor import ReVendor def locales_from_dicts(dicts): ans = {} for path in dicts: name = bname = os.path.basename(path) name = name[len('hyph_'):-len('.dic')] ans[name.replace('-', '_')] = bname return ans def locales_from_xcu(xcu, dicts): from lxml import etree with open(xcu, 'rb') as f: root = etree.fromstring(f.read(), parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False)) ans = {} dicts = {os.path.basename(x) for x in dicts} for value in root.xpath('//*[contains(text(),"DICT_HYPH")]'): node = value.getparent().getparent() locales = path = None for prop in node: name = prop.get('{http://openoffice.org/2001/registry}name') if name == 'Locales': locales = [x.replace('-', '_') for x in prop[0].text.split()] elif name == 'Locations': path = prop[0].text.strip().split('/')[-1] if locales and path in dicts: for locale in locales: ans[locale] = path return ans def process_dictionaries(src, output_dir): locale_data = {} for x in os.listdir(src): q = os.path.join(src, x) if not os.path.isdir(q): continue dicts = tuple(glob.glob(os.path.join(q, 'hyph_*.dic'))) if not dicts: continue xcu = os.path.join(q, 'dictionaries.xcu') locales = ( locales_from_xcu(xcu, dicts) if os.path.exists(xcu) else locales_from_dicts(dicts)) if locales: locale_data.update(locales) for d in dicts: shutil.copyfile( d, os.path.join(output_dir, os.path.basename(d))) data = json.dumps(locale_data, indent=2) if not isinstance(data, bytes): data = data.encode('utf-8') with open(os.path.join(output_dir, 'locales.json'), 'wb') as f: f.write(data) def compress_tar(buf, outf): buf.seek(0) try: from calibre_lzma.xz import compress except ImportError: import lzma outf.write(lzma.compress(buf.getvalue(), preset=9 | lzma.PRESET_EXTREME)) else: compress(buf, outf) class Hyphenation(ReVendor): description = 'Download the hyphenation dictionaries' NAME = 'hyphenation' TAR_NAME = 'hyphenation dictionaries' VERSION = 'master' DOWNLOAD_URL = 'https://github.com/LibreOffice/dictionaries/archive/%s.tar.gz' % VERSION CAN_USE_SYSTEM_VERSION = False def run(self, opts): self.clean() os.makedirs(self.vendored_dir) with self.temp_dir() as dl_src, self.temp_dir() as output_dir: src = opts.path_to_hyphenation or self.download_vendor_release(dl_src, opts.hyphenation_url) process_dictionaries(src, output_dir) dics = sorted(x for x in os.listdir(output_dir) if x.endswith('.dic')) m = hashlib.sha1() for dic in dics: with open(os.path.join(output_dir, dic), 'rb') as f: m.update(f.read()) hsh = str(m.hexdigest()) buf = BytesIO() with tarfile.TarFile(fileobj=buf, mode='w') as tf: for dic in dics: with open(os.path.join(output_dir, dic), 'rb') as df: tinfo = tf.gettarinfo(arcname=dic, fileobj=df) tinfo.mtime = 0 tinfo.uid = tinfo.gid = 1000 tinfo.uname = tinfo.gname = 'kovid' tf.addfile(tinfo, df) with open(os.path.join(self.vendored_dir, 'dictionaries.tar.xz'), 'wb') as f: compress_tar(buf, f) with open(os.path.join(self.vendored_dir, 'sha1sum'), 'w') as f: f.write(hsh) shutil.copy(os.path.join(output_dir, 'locales.json'), self.vendored_dir)
4,128
Python
.py
101
31.29703
120
0.5846
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,361
__init__.py
kovidgoyal_calibre/setup/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import hashlib import os import re import shutil import subprocess import sys import tempfile import time from contextlib import contextmanager from functools import lru_cache iswindows = re.search('win(32|64)', sys.platform) ismacos = 'darwin' in sys.platform isfreebsd = 'freebsd' in sys.platform isnetbsd = 'netbsd' in sys.platform isdragonflybsd = 'dragonfly' in sys.platform isbsd = isnetbsd or isfreebsd or isdragonflybsd ishaiku = 'haiku1' in sys.platform islinux = not ismacos and not iswindows and not isbsd and not ishaiku is_ci = os.environ.get('CI', '').lower() == 'true' sys.setup_dir = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.abspath(os.path.join(os.path.dirname(sys.setup_dir), 'src')) sys.path.insert(0, SRC) sys.resources_location = os.path.join(os.path.dirname(SRC), 'resources') sys.extensions_location = os.path.abspath(os.environ.get('CALIBRE_SETUP_EXTENSIONS_PATH', os.path.join(SRC, 'calibre', 'plugins'))) sys.running_from_setup = True __version__ = __appname__ = modules = functions = basenames = scripts = None _cache_dir_built = False def newer(targets, sources): if hasattr(targets, 'rjust'): targets = [targets] if hasattr(sources, 'rjust'): sources = [sources] for f in targets: if not os.path.exists(f): return True ttimes = map(lambda x: os.stat(x).st_mtime, targets) oldest_target = min(ttimes) try: stimes = map(lambda x: os.stat(x).st_mtime, sources) newest_source = max(stimes) except FileNotFoundError: newest_source = oldest_target +1 return newest_source > oldest_target def dump_json(obj, path, indent=4): import json with open(path, 'wb') as f: data = json.dumps(obj, indent=indent) if not isinstance(data, bytes): data = data.encode('utf-8') f.write(data) @lru_cache def curl_supports_etags(): return '--etag-compare' in subprocess.check_output(['curl', '--help', 'all']).decode('utf-8') def download_securely(url): # We use curl here as on some OSes (OS X) when bootstrapping calibre, # python will be unable to validate certificates until after cacerts is # installed if is_ci and iswindows: # curl is failing for wikipedia urls on CI (used for browser_data) from urllib.request import urlopen return urlopen(url).read() if not curl_supports_etags(): return subprocess.check_output(['curl', '-fsSL', url]) url_hash = hashlib.sha1(url.encode('utf-8')).hexdigest() cache_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.cache', 'download', url_hash) os.makedirs(cache_dir, exist_ok=True) subprocess.check_call( ['curl', '-fsSL', '--etag-compare', 'etag.txt', '--etag-save', 'etag.txt', '-o', 'data.bin', url], cwd=cache_dir ) with open(os.path.join(cache_dir, 'data.bin'), 'rb') as f: return f.read() def build_cache_dir(): global _cache_dir_built ans = os.path.join(os.path.dirname(SRC), '.build-cache') if not _cache_dir_built: _cache_dir_built = True try: os.mkdir(ans) except OSError as err: if err.errno != errno.EEXIST: raise return ans def require_git_master(branch='master'): if subprocess.check_output(['git', 'symbolic-ref', '--short', 'HEAD']).decode('utf-8').strip() != branch: raise SystemExit(f'You must be in the {branch} git branch') def require_clean_git(): c = subprocess.check_call p = subprocess.Popen c('git rev-parse --verify HEAD'.split(), stdout=subprocess.DEVNULL) c('git update-index -q --ignore-submodules --refresh'.split()) if p('git diff-files --quiet --ignore-submodules'.split()).wait() != 0: raise SystemExit('You have unstaged changes in your working tree') if p('git diff-index --cached --quiet --ignore-submodules HEAD --'.split()).wait() != 0: raise SystemExit('Your git index contains uncommitted changes') def initialize_constants(): global __version__, __appname__, modules, functions, basenames, scripts with open(os.path.join(SRC, 'calibre/constants.py'), 'rb') as f: src = f.read().decode('utf-8') nv = re.search(r'numeric_version\s+=\s+\((\d+), (\d+), (\d+)\)', src) __version__ = '%s.%s.%s'%(nv.group(1), nv.group(2), nv.group(3)) __appname__ = re.search(r'__appname__\s+=\s+(u{0,1})[\'"]([^\'"]+)[\'"]', src).group(2) with open(os.path.join(SRC, 'calibre/linux.py'), 'rb') as sf: epsrc = re.compile(r'entry_points = (\{.*?\})', re.DOTALL).\ search(sf.read().decode('utf-8')).group(1) entry_points = eval(epsrc, {'__appname__': __appname__}) def e2b(ep): return re.search(r'\s*(.*?)\s*=', ep).group(1).strip() def e2s(ep, base='src'): return (base+os.path.sep+re.search(r'.*=\s*(.*?):', ep).group(1).replace('.', '/')+'.py').strip() def e2m(ep): return re.search(r'.*=\s*(.*?)\s*:', ep).group(1).strip() def e2f(ep): return ep[ep.rindex(':')+1:].strip() basenames, functions, modules, scripts = {}, {}, {}, {} for x in ('console', 'gui'): y = x + '_scripts' basenames[x] = list(map(e2b, entry_points[y])) functions[x] = list(map(e2f, entry_points[y])) modules[x] = list(map(e2m, entry_points[y])) scripts[x] = list(map(e2s, entry_points[y])) initialize_constants() preferred_encoding = 'utf-8' prints = print warnings = [] def get_warnings(): return list(warnings) def edit_file(path): return subprocess.Popen([ os.environ.get('EDITOR', 'vim'), '-S', os.path.join(SRC, '../session.vim'), '-f', path ]).wait() == 0 class Command: SRC = SRC RESOURCES = os.path.join(os.path.dirname(SRC), 'resources') description = '' sub_commands = [] def __init__(self): self.d = os.path.dirname self.j = os.path.join self.a = os.path.abspath self.b = os.path.basename self.s = os.path.splitext self.e = os.path.exists self.orig_euid = os.geteuid() if hasattr(os, 'geteuid') else None self.real_uid = os.environ.get('SUDO_UID', None) self.real_gid = os.environ.get('SUDO_GID', None) self.real_user = os.environ.get('SUDO_USER', None) def drop_privileges(self): if not islinux or ismacos or isfreebsd: return if self.real_user is not None: self.info('Dropping privileges to those of', self.real_user+':', self.real_uid) if self.real_gid is not None: os.setegid(int(self.real_gid)) if self.real_uid is not None: os.seteuid(int(self.real_uid)) def regain_privileges(self): if not islinux or ismacos or isfreebsd: return if os.geteuid() != 0 and self.orig_euid == 0: self.info('Trying to get root privileges') os.seteuid(0) if os.getegid() != 0: os.setegid(0) def pre_sub_commands(self, opts): pass def running(self, cmd): from setup.commands import command_names if is_ci: self.info('::group::' + command_names[cmd]) self.info('\n*') self.info('* Running', command_names[cmd]) self.info('*\n') def run_cmd(self, cmd, opts): from setup.commands import command_names cmd.pre_sub_commands(opts) for scmd in cmd.sub_commands: self.run_cmd(scmd, opts) st = time.time() self.running(cmd) cmd.run(opts) self.info(f'* {command_names[cmd]} took {time.time() - st:.1f} seconds') if is_ci: self.info('::endgroup::') def run_all(self, opts): self.run_cmd(self, opts) def add_command_options(self, command, parser): import setup.commands as commands command.sub_commands = [getattr(commands, cmd) for cmd in command.sub_commands] for cmd in command.sub_commands: self.add_command_options(cmd, parser) command.add_options(parser) def add_all_options(self, parser): self.add_command_options(self, parser) def run(self, opts): pass def add_options(self, parser): pass def clean(self): pass @classmethod def newer(cls, targets, sources): ''' Return True if sources is newer that targets or if targets does not exist. ''' return newer(targets, sources) def info(self, *args, **kwargs): prints(*args, **kwargs) sys.stdout.flush() def warn(self, *args, **kwargs): print('\n'+'_'*20, 'WARNING','_'*20) prints(*args, **kwargs) print('_'*50) warnings.append((args, kwargs)) sys.stdout.flush() @contextmanager def temp_dir(self, **kw): ans = tempfile.mkdtemp(**kw) try: yield ans finally: shutil.rmtree(ans) def installer_names(include_source=True): base = f'dist/{__appname__}' yield f'{base}-64bit-{__version__}.msi' yield f'{base}-{__version__}.dmg' yield f'{base}-portable-installer-{__version__}.exe' for arch in ('x86_64', 'arm64'): yield f'{base}-{__version__}-{arch}.txz' if include_source: yield f'{base}-{__version__}.tar.xz'
9,584
Python
.py
240
33.108333
131
0.613827
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,362
git_version.py
kovidgoyal_calibre/setup/git_version.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> import re import subprocess from setup import Command class GitVersion(Command): description = 'Update the version from git metadata' def run(self, opts): constants_file = self.j(self.SRC, 'calibre', 'constants.py') with open(constants_file, 'rb') as f: src = f.read().decode('utf-8') try: nv = subprocess.check_output(['git', 'describe']) nv = re.sub(r'([^-]*-g)', r'r\1', nv.decode('utf-8').strip().lstrip('v')) nv = nv.replace('-', '.') except subprocess.CalledProcessError: raise SystemExit('Error: not a git checkout') newsrc = re.sub(r'(git_version = ).*', r'\1%s' % repr(nv), src) self.info('new version is:', nv) with open(constants_file, 'wb') as f: f.write(newsrc.encode('utf-8'))
934
Python
.py
21
36.52381
85
0.598007
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,363
parallel_build.py
kovidgoyal_calibre/setup/parallel_build.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import itertools import json import os import shlex import subprocess import sys from collections import namedtuple from contextlib import closing from functools import partial from multiprocessing.pool import ThreadPool as Pool from threading import Thread from polyglot.builtins import as_bytes, unicode_type Job = namedtuple('Job', 'cmd human_text cwd') cpu_count = min(16, max(1, os.cpu_count())) def run_worker(job, decorate=True): cmd, human_text = job.cmd, job.human_text human_text = human_text or shlex.join(cmd) cwd = job.cwd if cmd[0].lower().endswith('cl.exe'): cwd = os.environ.get('COMPILER_CWD') try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) except Exception as err: return False, human_text, unicode_type(err) stdout, stderr = p.communicate() if stdout: stdout = stdout.decode('utf-8') if stderr: stderr = stderr.decode('utf-8') if decorate: stdout = human_text + '\n' + (stdout or '') ok = p.returncode == 0 return ok, stdout, (stderr or '') def create_job(cmd, human_text=None, cwd=None): return Job(cmd, human_text, cwd) def parallel_build(jobs, log, verbose=True): p = Pool(cpu_count) with closing(p): for ok, stdout, stderr in p.imap(run_worker, jobs): if verbose or not ok: log(stdout) if stderr: log(stderr) if not ok: return False return True def parallel_build_silent(jobs): p = Pool(cpu_count) results = [] failed = False with closing(p): for (ok, stdout, stderr), job in zip(p.imap(partial(run_worker, decorate=False), jobs), jobs): results.append((ok, job.cmd, job.human_text, stdout, stderr)) if not ok: failed = True return failed, results def parallel_check_output(jobs, log): p = Pool(cpu_count) with closing(p): for ok, stdout, stderr in p.imap( partial(run_worker, decorate=False), ((j, '') for j in jobs)): if not ok: log(stdout) if stderr: log(stderr) raise SystemExit(1) yield stdout def get_tasks(it): it = tuple(it) size, extra = divmod(len(it), cpu_count) if extra: size += 1 it = iter(it) while 1: x = tuple(itertools.islice(it, size)) if not x: return yield x def batched_parallel_jobs(cmd, jobs, cwd=None): workers = [] def get_output(p): p.output = p.communicate(as_bytes(json.dumps(p.jobs_batch))) for batch in get_tasks(jobs): p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) p.jobs_batch = batch p.output_thread = t = Thread(target=get_output, args=(p,)) t.daemon = True t.start() workers.append(p) failed = False ans = [] for p in workers: p.output_thread.join() if p.wait() != 0: sys.stderr.buffer.write(p.output[1]) sys.stderr.buffer.flush() failed = True else: ans.extend(json.loads(p.output[0])) if failed: raise SystemExit('Worker process failed') return ans def threaded_func_jobs(func, jobs_args): def f(args): return func(*args) p = Pool(cpu_count) with closing(p): return p.map(f, jobs_args)
3,652
Python
.py
111
25.63964
113
0.609846
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,364
build_environment.py
kovidgoyal_calibre/setup/build_environment.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re import shutil import subprocess from functools import lru_cache from setup import isfreebsd, ishaiku, islinux, ismacos, iswindows NMAKE = RC = msvc = MT = win_inc = win_lib = win_cc = win_ld = None @lru_cache(maxsize=2) def pyqt_sip_abi_version(): import PyQt6 if getattr(PyQt6, '__file__', None): bindings_path = os.path.join(os.path.dirname(PyQt6.__file__), 'bindings', 'QtCore', 'QtCore.toml') if os.path.exists(bindings_path): with open(bindings_path) as f: raw = f.read() m = re.search(r'^sip-abi-version\s*=\s*"(.+?)"', raw, flags=re.MULTILINE) if m is not None: return m.group(1) def merge_paths(a, b): a = [os.path.normcase(os.path.normpath(x)) for x in a.split(os.pathsep)] for q in b.split(os.pathsep): q = os.path.normcase(os.path.normpath(q)) if q not in a: a.append(q) return os.pathsep.join(a) if iswindows: from setup.vcvars import query_vcvarsall env = query_vcvarsall() win_path = env['PATH'] os.environ['PATH'] = merge_paths(env['PATH'], os.environ['PATH']) NMAKE = 'nmake.exe' RC = 'rc.exe' MT = 'mt.exe' win_cc = 'cl.exe' win_ld = 'link.exe' win_inc = [x for x in env['INCLUDE'].split(os.pathsep) if x] win_lib = [x for x in env['LIB'].split(os.pathsep) if x] for key in env: if key != 'PATH': os.environ[key] = env[key] QMAKE = 'qmake' for x in ('qmake6', 'qmake-qt6', 'qt6-qmake', 'qmake'): q = shutil.which(x) if q: QMAKE = q break QMAKE = os.environ.get('QMAKE', QMAKE) if iswindows and not QMAKE.lower().endswith('.exe'): QMAKE += '.exe' CMAKE = 'cmake' CMAKE = os.environ.get('CMAKE', CMAKE) PKGCONFIG = shutil.which('pkg-config') PKGCONFIG = os.environ.get('PKG_CONFIG', PKGCONFIG) if (islinux or ishaiku) and not PKGCONFIG: raise SystemExit('Failed to find pkg-config on your system. You can use the environment variable PKG_CONFIG to point to the pkg-config executable') def run_pkgconfig(name, envvar, default, flag, prefix): ans = [] if envvar: ev = os.environ.get(envvar, None) if ev: ans = [x.strip() for x in ev.split(os.pathsep)] ans = [x for x in ans if x and (prefix=='-l' or os.path.exists(x))] if not ans: try: raw = subprocess.Popen([PKGCONFIG, flag, name], stdout=subprocess.PIPE).stdout.read().decode('utf-8') ans = [x.strip() for x in raw.split(prefix)] ans = [x for x in ans if x and (prefix=='-l' or os.path.exists(x))] except: print('Failed to run pkg-config:', PKGCONFIG, 'for:', name) return ans or ([default] if default else []) def pkgconfig_include_dirs(name, envvar, default): return run_pkgconfig(name, envvar, default, '--cflags-only-I', '-I') def pkgconfig_lib_dirs(name, envvar, default): return run_pkgconfig(name, envvar, default,'--libs-only-L', '-L') def pkgconfig_libs(name, envvar, default): return run_pkgconfig(name, envvar, default,'--libs-only-l', '-l') def consolidate(envvar, default): val = os.environ.get(envvar, default) ans = [x.strip() for x in val.split(os.pathsep)] return [x for x in ans if x and os.path.exists(x)] qraw = subprocess.check_output([QMAKE, '-query']).decode('utf-8') def readvar(name): return re.search('^%s:(.+)$' % name, qraw, flags=re.M).group(1).strip() qt = {x:readvar(y) for x, y in {'libs':'QT_INSTALL_LIBS', 'plugins':'QT_INSTALL_PLUGINS'}.items()} qmakespec = readvar('QMAKE_SPEC') if iswindows else None freetype_lib_dirs = [] freetype_libs = [] freetype_inc_dirs = [] podofo_inc = '/usr/include/podofo' podofo_lib = '/usr/lib' usb_library = 'usb' if isfreebsd else 'usb-1.0' chmlib_inc_dirs = chmlib_lib_dirs = [] sqlite_inc_dirs = [] icu_inc_dirs = [] icu_lib_dirs = [] zlib_inc_dirs = [] zlib_lib_dirs = [] hunspell_inc_dirs = [] hunspell_lib_dirs = [] hyphen_inc_dirs = [] hyphen_lib_dirs = [] ffmpeg_inc_dirs = [] ffmpeg_lib_dirs = [] uchardet_inc_dirs, uchardet_lib_dirs, uchardet_libs = [], [], ['uchardet'] openssl_inc_dirs, openssl_lib_dirs = [], [] ICU = sw = '' if iswindows: prefix = sw = os.environ.get('SW', r'C:\cygwin64\home\kovid\sw') sw_inc_dir = os.path.join(prefix, 'include') sw_lib_dir = os.path.join(prefix, 'lib') icu_inc_dirs = [sw_inc_dir] icu_lib_dirs = [sw_lib_dir] hyphen_inc_dirs = [sw_inc_dir] hyphen_lib_dirs = [sw_lib_dir] openssl_inc_dirs = [sw_inc_dir] openssl_lib_dirs = [sw_lib_dir] uchardet_inc_dirs = [sw_inc_dir] uchardet_lib_dirs = [sw_lib_dir] sqlite_inc_dirs = [sw_inc_dir] chmlib_inc_dirs = [sw_inc_dir] chmlib_lib_dirs = [sw_lib_dir] freetype_lib_dirs = [sw_lib_dir] freetype_libs = ['freetype'] freetype_inc_dirs = [os.path.join(sw_inc_dir, 'freetype2'), sw_inc_dir] hunspell_inc_dirs = [os.path.join(sw_inc_dir, 'hunspell')] hunspell_lib_dirs = [sw_lib_dir] zlib_inc_dirs = [sw_inc_dir] zlib_lib_dirs = [sw_lib_dir] podofo_inc = os.path.join(sw_inc_dir, 'podofo') podofo_lib = sw_lib_dir elif ismacos: sw = os.environ.get('SW', os.path.expanduser('~/sw')) sw_inc_dir = os.path.join(sw, 'include') sw_lib_dir = os.path.join(sw, 'lib') sw_bin_dir = os.path.join(sw, 'bin') podofo_inc = os.path.join(sw_inc_dir, 'podofo') hunspell_inc_dirs = [os.path.join(sw_inc_dir, 'hunspell')] podofo_lib = sw_lib_dir freetype_libs = ['freetype'] freetype_inc_dirs = [sw + '/include/freetype2'] uchardet_inc_dirs = [sw + '/include/uchardet'] SSL = os.environ.get('OPENSSL_DIR', os.path.join(sw, 'private', 'ssl')) openssl_inc_dirs = [os.path.join(SSL, 'include')] openssl_lib_dirs = [os.path.join(SSL, 'lib')] if os.path.exists(os.path.join(sw_bin_dir, 'cmake')): CMAKE = os.path.join(sw_bin_dir, 'cmake') else: freetype_inc_dirs = pkgconfig_include_dirs('freetype2', 'FT_INC_DIR', '/usr/include/freetype2') freetype_lib_dirs = pkgconfig_lib_dirs('freetype2', 'FT_LIB_DIR', '/usr/lib') freetype_libs = pkgconfig_libs('freetype2', '', '') hunspell_inc_dirs = pkgconfig_include_dirs('hunspell', 'HUNSPELL_INC_DIR', '/usr/include/hunspell') hunspell_lib_dirs = pkgconfig_lib_dirs('hunspell', 'HUNSPELL_LIB_DIR', '/usr/lib') sw = os.environ.get('SW', os.path.expanduser('~/sw')) podofo_inc = '/usr/include/podofo' podofo_lib = '/usr/lib' if not os.path.exists(podofo_inc + '/podofo.h'): podofo_inc = os.path.join(sw, 'include', 'podofo') podofo_lib = os.path.join(sw, 'lib') uchardet_inc_dirs = pkgconfig_include_dirs('uchardet', '', '/usr/include/uchardet') uchardet_lib_dirs = pkgconfig_lib_dirs('uchardet', '', '/usr/lib') uchardet_libs = pkgconfig_libs('uchardet', '', '') for x in ('libavcodec', 'libavformat', 'libavdevice', 'libavfilter', 'libavutil', 'libpostproc', 'libswresample', 'libswscale'): for inc in pkgconfig_include_dirs(x, '', '/usr/include'): if inc and inc not in ffmpeg_inc_dirs: ffmpeg_inc_dirs.append(inc) for lib in pkgconfig_lib_dirs(x, '', '/usr/lib'): if lib and lib not in ffmpeg_lib_dirs: ffmpeg_lib_dirs.append(lib) if os.path.exists(os.path.join(sw, 'ffmpeg')): ffmpeg_inc_dirs = [os.path.join(sw, 'ffmpeg', 'include')] + ffmpeg_inc_dirs ffmpeg_lib_dirs = [os.path.join(sw, 'ffmpeg', 'bin' if iswindows else 'lib')] + ffmpeg_lib_dirs if 'PODOFO_PREFIX' in os.environ: os.environ['PODOFO_LIB_DIR'] = os.path.join(os.environ['PODOFO_PREFIX'], 'lib') os.environ['PODOFO_INC_DIR'] = os.path.join(os.environ['PODOFO_PREFIX'], 'include', 'podofo') os.environ['PODOFO_LIB_NAME'] = os.path.join(os.environ['PODOFO_PREFIX'], 'lib', 'libpodofo.so.1') podofo_lib = os.environ.get('PODOFO_LIB_DIR', podofo_lib) podofo_inc = os.environ.get('PODOFO_INC_DIR', podofo_inc) podofo = os.environ.get('PODOFO_LIB_NAME', 'podofo') podofo_error = None if os.path.exists(os.path.join(podofo_inc, 'podofo.h')) else \ ('PoDoFo not found on your system. Various PDF related', ' functionality will not work. Use the PODOFO_INC_DIR and', ' PODOFO_LIB_DIR environment variables.') podofo_inc_dirs = [podofo_inc, os.path.dirname(podofo_inc)] podofo_lib_dirs = [podofo_lib]
8,573
Python
.py
190
39.915789
151
0.639755
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,365
liberation.py
kovidgoyal_calibre/setup/liberation.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import glob import os from setup.revendor import ReVendor class LiberationFonts(ReVendor): description = 'Download the Liberation fonts' NAME = 'liberation_fonts' TAR_NAME = 'liberation-fonts' VERSION = '2.1.5' DOWNLOAD_URL = 'https://github.com/liberationfonts/liberation-fonts/files/7261482/liberation-fonts-ttf-2.1.5.tar.gz' @property def vendored_dir(self): return self.j(self.RESOURCES, 'fonts', 'liberation') @property def version_file(self): return self.j(self.vendored_dir, 'version.txt') def already_present(self): if os.path.exists(self.version_file): with open(self.version_file) as f: return f.read() == self.VERSION return False def run(self, opts): if not opts.system_liberation_fonts and self.already_present(): self.info('Liberation Fonts already present in the resources directory, not downloading') return self.clean() os.makedirs(self.vendored_dir) self.use_symlinks = opts.system_liberation_fonts with self.temp_dir() as dl_src: src = opts.path_to_liberation_fonts or self.download_vendor_release(dl_src, opts.liberation_fonts_url) font_files = glob.glob(os.path.join(src, 'Liberation*.ttf')) if not font_files: raise SystemExit(f'No font files found in {src}') for x in font_files: self.add_file(x, os.path.basename(x)) with open(self.j(self.vendored_dir, 'version.txt'), 'w') as f: f.write(self.VERSION)
1,698
Python
.py
38
36.368421
120
0.655758
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,366
wincross.py
kovidgoyal_calibre/setup/wincross.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> # See https://github.com/mstorsjo/msvc-wine/blob/master/vsdownload.py and # https://github.com/Jake-Shadle/xwin/blob/main/src/lib.rs for the basic logic # used to download and install the needed VisualStudio packages import argparse import concurrent.futures import glob import hashlib import json import os import re import shutil import subprocess import sys from collections import defaultdict from dataclasses import dataclass from functools import partial from pprint import pprint from tempfile import TemporaryDirectory from urllib.parse import unquote from urllib.request import urlopen from zipfile import ZipFile @dataclass class File: filename: str url: str size: int sha256: str def __init__(self, pf, filename=''): self.filename=filename or pf['fileName'] self.url=pf['url'] self.size=pf['size'] self.sha256=pf['sha256'].lower() def package_sort_key(p): chip = 0 if p.get('chip', '').lower() == 'x64' else 1 language = 0 if p.get('language', '').lower().startswith('en-') else 1 return chip, language def llvm_arch_to_ms_arch(arch): return {'x86_64': 'x64', 'aarch64': 'arm64', 'x64': 'x64', 'arm64': 'arm64'}[arch] class Packages: def __init__(self, manifest_raw, crt_variant, arch): arch = llvm_arch_to_ms_arch(arch) self.manifest = json.loads(manifest_raw) self.packages = defaultdict(list) self.cabinet_entries = {} for p in self.manifest['packages']: pid = p['id'].lower() self.packages[pid].append(p) for v in self.packages.values(): v.sort(key=package_sort_key) build_tools = self.packages[ 'Microsoft.VisualStudio.Product.BuildTools'.lower()][0] pat = re.compile(r'Microsoft\.VisualStudio\.Component\.VC\.(.+)\.x86\.x64') latest = (0, 0, 0, 0) self.crt_version = '' for dep in build_tools['dependencies']: m = pat.match(dep) if m is not None: parts = m.group(1).split('.') if len(parts) > 1: q = tuple(map(int, parts)) if q > latest: self.crt_version = m.group(1) latest = q if not self.crt_version: raise KeyError('Failed to find CRT version from build tools deps') self.files_to_download = [] def add_package(key): p = self.packages.get(key.lower()) if not p: raise KeyError(f'No package named {key} found') for pf in p[0]['payloads']: self.files_to_download.append(File(pf)) # CRT headers add_package(f"Microsoft.VC.{self.crt_version}.CRT.Headers.base") # CRT libs prefix = f'Microsoft.VC.{self.crt_version}.CRT.{arch}.'.lower() variants = {} for pid in self.packages: if pid.startswith(prefix): parts = pid[len(prefix):].split('.') if parts[-1] == 'base': variant = parts[0] if variant not in variants or 'spectre' in parts: # spectre variant contains both spectre and regular libs variants[variant] = pid add_package(variants[crt_variant]) # ATL headers add_package(f"Microsoft.VC.{self.crt_version}.ATL.Headers.base") # ATL libs add_package(f'Microsoft.VC.{self.crt_version}.ATL.{arch}.Spectre.base') add_package(f'Microsoft.VC.{self.crt_version}.ATL.{arch}.base') # WinSDK pat = re.compile(r'Win(\d+)SDK_(\d.+)', re.IGNORECASE) latest_sdk = (0, 0, 0) self.sdk_version = '' sdk_pid = '' for pid in self.packages: m = pat.match(pid) if m is not None: ver = tuple(map(int, m.group(2).split('.'))) if ver > latest_sdk: self.sdk_version = m.group(2) latest_sdk = ver sdk_pid = pid if not self.sdk_version: raise KeyError('Failed to find SDK package') # headers are in x86 package and arch specific package for pf in self.packages[sdk_pid][0]['payloads']: fname = pf['fileName'].split('\\')[-1] if fname.startswith('Windows SDK Desktop Headers '): q = fname[len('Windows SDK Desktop Headers '):] if q.lower() == 'x86-x86_en-us.msi': self.files_to_download.append(File( pf, filename=f'{sdk_pid}_headers.msi')) elif q.lower() == f'{arch}-x86_en-us.msi': self.files_to_download.append(File( pf, filename=f'{sdk_pid}_{arch}_headers.msi')) elif fname == 'Windows SDK for Windows Store Apps Headers-x86_en-us.msi': self.files_to_download.append(File( pf, filename=f'{sdk_pid}_store_headers.msi')) elif fname.startswith('Windows SDK Desktop Libs '): q = fname[len('Windows SDK Desktop Libs '):] if q == f'{arch}-x86_en-us.msi': self.files_to_download.append(File( pf, filename=f'{sdk_pid}_libs_x64.msi')) elif fname == 'Windows SDK for Windows Store Apps Libs-x86_en-us.msi': self.files_to_download.append(File( pf, filename=f'{sdk_pid}_store_libs.msi')) elif (fl := fname.lower()).endswith('.cab'): self.cabinet_entries[fl] = File(pf, filename=fl) # UCRT for pf in self.packages[ 'Microsoft.Windows.UniversalCRT.HeadersLibsSources.Msi'.lower()][0]['payloads']: fname = pf['fileName'].split('\\')[-1] if fname == 'Universal CRT Headers Libraries and Sources-x86_en-us.msi': self.files_to_download.append(File(pf)) self.files_to_download[-1].filename = 'ucrt.msi' elif (fl := fname.lower()).endswith('.cab'): self.cabinet_entries[fl] = File(pf, filename=fl) def download_item(dest_dir: str, file: File): dest = os.path.join(dest_dir, file.filename) m = hashlib.sha256() with urlopen(file.url) as src, open(dest, 'wb') as d: with memoryview(bytearray(shutil.COPY_BUFSIZE)) as buf: while True: n = src.readinto(buf) if not n: break elif n < shutil.COPY_BUFSIZE: with buf[:n] as smv: d.write(smv) m.update(smv) else: d.write(buf) m.update(buf) if m.hexdigest() != file.sha256: raise SystemExit(f'The hash for {file.filename} does not match.' f' {m.hexdigest()} != {file.sha256}') def cabinets_in_msi(path): raw = subprocess.check_output(['msiinfo', 'export', path, 'Media']).decode('utf-8') return re.findall(r'\S+\.cab', raw) def download(dest_dir, manifest_version=17, manifest_type='release', manifest_path='', crt_variant='desktop', arch='x86_64'): if manifest_path: manifest = open(manifest_path, 'rb').read() else: url = f'https://aka.ms/vs/{manifest_version}/{manifest_type}/channel' print('Downloading top-level manifest from', url) tm = json.loads(urlopen(url).read()) print("Got toplevel manifest for", (tm["info"]["productDisplayVersion"])) for item in tm["channelItems"]: if item.get('type') == "Manifest": url = item["payloads"][0]["url"] print('Downloading actual manifest...') manifest = urlopen(url).read() pkgs = Packages(manifest, crt_variant, arch) os.makedirs(dest_dir, exist_ok=True) total = sum(x.size for x in pkgs.files_to_download) print('Downloading', int(total/(1024*1024)), 'MB in', len(pkgs.files_to_download), 'files...') with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: for _ in executor.map(partial(download_item, dest_dir), pkgs.files_to_download): pass cabs = [] for x in os.listdir(dest_dir): if x.lower().endswith('.msi'): for cab in cabinets_in_msi(os.path.join(dest_dir, x)): cabs.append(pkgs.cabinet_entries[cab]) total = sum(x.size for x in cabs) print('Downloading', int(total/(1024*1024)), 'MB in', len(cabs), 'files...') with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: for _ in executor.map(partial(download_item, dest_dir), cabs): pass def merge_trees(src, dest): if not os.path.isdir(src): return if not os.path.isdir(dest): shutil.move(src, dest) return destnames = {n.lower():n for n in os.listdir(dest)} for d in os.scandir(src): n = d.name srcname = os.path.join(src, n) destname = os.path.join(dest, n) if d.is_dir(): if os.path.isdir(destname): merge_trees(srcname, destname) elif n.lower() in destnames: merge_trees(srcname, os.path.join(dest, destnames[n.lower()])) else: shutil.move(srcname, destname) else: shutil.move(srcname, destname) def extract_msi(path, dest_dir): print('Extracting', os.path.basename(path), '...') with open(os.path.join(dest_dir, os.path.basename(path) + '.listing'), 'w') as log: subprocess.check_call(['msiextract', '-C', dest_dir, path], stdout=log) def extract_zipfile(zf, dest_dir): tmp = os.path.join(dest_dir, "extract") os.mkdir(tmp) for f in zf.infolist(): name = unquote(f.filename) dest = os.path.join(dest_dir, name) extracted = zf.extract(f, tmp) os.makedirs(os.path.dirname(dest), exist_ok=True) shutil.move(extracted, dest) shutil.rmtree(tmp) def extract_vsix(path, dest_dir): print('Extracting', os.path.basename(path), '...') with TemporaryDirectory(dir=dest_dir) as tdir, ZipFile(path, 'r') as zf: extract_zipfile(zf, tdir) contents = os.path.join(tdir, "Contents") merge_trees(contents, dest_dir) names = zf.namelist() with open(os.path.join(dest_dir, os.path.basename(path) + '.listing'), 'w') as ls: ls.write('\n'.join(names)) def move_unpacked_trees(src_dir, dest_dir): # CRT crt_src = os.path.dirname(glob.glob( os.path.join(src_dir, 'VC/Tools/MSVC/*/include'))[0]) crt_dest = os.path.join(dest_dir, 'crt') os.makedirs(crt_dest) merge_trees(os.path.join(crt_src, 'include'), os.path.join(crt_dest, 'include')) merge_trees(os.path.join(crt_src, 'lib'), os.path.join(crt_dest, 'lib')) merge_trees(os.path.join(crt_src, 'atlmfc', 'include'), os.path.join(crt_dest, 'include')) merge_trees(os.path.join(crt_src, 'atlmfc', 'lib'), os.path.join(crt_dest, 'lib')) # SDK sdk_ver = glob.glob(os.path.join(src_dir, 'win11sdk_*_headers.msi.listing'))[0] sdk_ver = sdk_ver.split('_')[1] for x in glob.glob(os.path.join(src_dir, 'Program Files/Windows Kits/*/Include/*')): if os.path.basename(x).startswith(sdk_ver): sdk_ver = os.path.basename(x) break else: raise SystemExit(f'Failed to find sdk_ver: {sdk_ver}') sdk_include_src = glob.glob(os.path.join( src_dir, f'Program Files/Windows Kits/*/Include/{sdk_ver}'))[0] sdk_dest = os.path.join(dest_dir, 'sdk') os.makedirs(sdk_dest) merge_trees(sdk_include_src, os.path.join(sdk_dest, 'include')) sdk_lib_src = glob.glob(os.path.join( src_dir, f'Program Files/Windows Kits/*/Lib/{sdk_ver}'))[0] merge_trees(sdk_lib_src, os.path.join(sdk_dest, 'lib')) # UCRT if os.path.exists(os.path.join(sdk_include_src, 'ucrt')): return ucrt_include_src = glob.glob(os.path.join( src_dir, 'Program Files/Windows Kits/*/Include/*/ucrt'))[0] merge_trees(ucrt_include_src, os.path.join(sdk_dest, 'include', 'ucrt')) ucrt_lib_src = glob.glob(os.path.join( src_dir, 'Program Files/Windows Kits/*/Lib/*/ucrt'))[0] merge_trees(ucrt_lib_src, os.path.join(sdk_dest, 'lib', 'ucrt')) def unpack(src_dir, dest_dir): if os.path.exists(dest_dir): shutil.rmtree(dest_dir) extract_dir = os.path.join(dest_dir, 'extract') os.makedirs(extract_dir) for x in os.listdir(src_dir): path = os.path.join(src_dir, x) ext = os.path.splitext(x)[1].lower() if ext =='.msi': extract_msi(path, extract_dir) elif ext == '.vsix': extract_vsix(path, extract_dir) elif ext == '.cab': continue else: raise SystemExit(f'Unknown downloaded file type: {x}') move_unpacked_trees(extract_dir, dest_dir) shutil.rmtree(extract_dir) def symlink_transformed(path, transform=str.lower): base, name = os.path.split(path) lname = transform(name) if lname != name: npath = os.path.join(base, lname) if not os.path.lexists(npath): os.symlink(name, npath) def clone_tree(src_dir, dest_dir): os.makedirs(dest_dir) for dirpath, dirnames, filenames in os.walk(src_dir): for d in dirnames: path = os.path.join(dirpath, d) rpath = os.path.relpath(path, src_dir) dpath = os.path.join(dest_dir, rpath) os.makedirs(dpath) symlink_transformed(dpath) for f in filenames: if f.lower().endswith('.pdb'): continue path = os.path.join(dirpath, f) rpath = os.path.relpath(path, src_dir) dpath = os.path.join(dest_dir, rpath) os.link(path, dpath) symlink_transformed(dpath) def files_in(path): for dirpath, _, filenames in os.walk(path): for f in filenames: yield os.path.relpath(os.path.join(dirpath, f), path) def create_include_symlinks(path, include_root, include_files): ' Create symlinks for include entries in header files whose case does not match ' with open(path, 'rb') as f: src = f.read() for m in re.finditer(rb'^#include\s+([<"])(.+?)[>"]', src, flags=re.M): spec = m.group(2).decode().replace('\\', '/') lspec = spec.lower() if spec == lspec: continue is_local = m.group(1).decode() == '"' found = '' lmatches = [] for ir, specs in include_files.items(): if spec in specs: found = ir break if lspec in specs: lmatches.append(ir) if found and (not is_local or found == include_root): continue if lmatches: if is_local and include_root in lmatches: fr = include_root else: fr = lmatches[0] symlink_transformed(os.path.join(fr, lspec), lambda n: os.path.basename(spec)) def setup(splat_dir, root_dir, arch): print('Creating symlinks...') msarch = llvm_arch_to_ms_arch(arch) if os.path.exists(root_dir): shutil.rmtree(root_dir) os.makedirs(root_dir) # CRT clone_tree(os.path.join(splat_dir, 'crt', 'include'), os.path.join(root_dir, 'crt', 'include')) clone_tree(os.path.join(splat_dir, 'crt', 'lib', 'spectre', msarch), os.path.join(root_dir, 'crt', 'lib')) # SDK clone_tree(os.path.join(splat_dir, 'sdk', 'include'), os.path.join(root_dir, 'sdk', 'include')) for x in glob.glob(os.path.join(splat_dir, 'sdk', 'lib', '*', msarch)): clone_tree(x, os.path.join(root_dir, 'sdk', 'lib', os.path.basename(os.path.dirname(x)))) include_roots = [x for x in glob.glob(os.path.join(root_dir, 'sdk', 'include', '*')) if os.path.isdir(x)] include_roots.append(os.path.join(root_dir, 'crt', 'include')) include_files = {x:set(files_in(x)) for x in include_roots} for ir, files in include_files.items(): files_to_check = [] for relpath in files: path = os.path.join(ir, relpath) if not os.path.islink(path): files_to_check.append(path) for path in files_to_check: create_include_symlinks(path, ir, include_files) def main(args=sys.argv[1:]): stages = ('download', 'unpack', 'setup') p = argparse.ArgumentParser( description='Setup the headers and libraries for cross-compilation of windows binaries') p.add_argument( 'stages', metavar='STAGES', nargs='*', help=( f'The stages to run by default all stages are run. Stages are: {" ".join(stages)}')) p.add_argument( '--manifest-version', default=17, type=int, help='The manifest version to use to find the packages to install') p.add_argument( '--manifest-path', default='', help='Path to a local manifest file to use. Causes --manifest-version to be ignored.') p.add_argument( '--crt-variant', default='desktop', choices=('desktop', 'store', 'onecore'), help='The type of CRT to download') p.add_argument( '--arch', default='x86_64', choices=('x86_64', 'aarch64'), help='The architecture to install') p.add_argument('--dest', default='.', help='The directory to install into') args = p.parse_args(args) if args.dest == '.': args.dest = os.getcwd() stages = args.stages or stages dl_dir = os.path.join(args.dest, 'dl') splat_dir = os.path.join(args.dest, 'splat') root_dir = os.path.join(args.dest, 'root') for stage in stages: if stage == 'download': download(dl_dir, manifest_version=args.manifest_version, manifest_path=args.manifest_path, crt_variant=args.crt_variant, arch=args.arch) elif stage == 'unpack': unpack(dl_dir, splat_dir) elif stage == 'setup': setup(splat_dir, root_dir, args.arch) else: raise SystemExit(f'Unknown stage: {stage}') if __name__ == '__main__': pprint main()
18,285
Python
.py
406
35.571429
148
0.590891
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,367
git_post_checkout_hook.py
kovidgoyal_calibre/setup/git_post_checkout_hook.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import os import subprocess import sys prev_rev, current_rev, flags = sys.argv[1:] def get_branch_name(rev): return subprocess.check_output(['git', 'name-rev', '--name-only', '--refs=refs/heads/*', rev]).decode('utf-8').strip() base = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) os.chdir(base) if flags == '1': # A branch checkout prev_branch, cur_branch = list(map(get_branch_name, (prev_rev, current_rev))) rebase_in_progress = os.path.exists('.git/rebase-apply') or os.path.exists('.git/rebase-merge') subprocess.check_call('./setup.py gui --summary'.split()) # Remove .pyc files as some of them might have been orphaned for dirpath, dirnames, filenames in os.walk('.'): for f in filenames: fpath = os.path.join(dirpath, f) if f.endswith('.pyc') and '/chroot/' not in fpath: os.remove(fpath)
1,002
Python
.py
21
42.809524
122
0.662204
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,368
changelog.py
kovidgoyal_calibre/setup/changelog.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from datetime import date def parse(raw, parse_dates=True): entries = [] current_entry = None current_section = 'new features' def normal(linenum, line, stripped_line): nonlocal current_entry, current_section if not stripped_line: return normal if stripped_line.startswith('{' '{' '{'): parts = line.split()[1:] if len(parts) != 2: raise ValueError(f'The entry start line is malformed: {line}') if current_entry is not None: raise ValueError(f'Start of entry while previous entry is still active at line: {linenum}') version, draw = parts if parse_dates: d = date(*map(int, draw.split('-'))) else: d = draw current_entry = {'version': version, 'date': d, 'new features': [], 'bug fixes': [], 'improved recipes': [], 'new recipes': []} current_section = 'new features' return in_entry raise ValueError(f'Invalid content at line {linenum}: {line}') def in_entry(linenum, line, stripped_line): nonlocal current_section, current_entry if stripped_line == '}' '}' '}': if current_entry is None: raise ValueError(f'Entry terminator without active entry at line: {linenum}') entries.append(current_entry) current_entry = None return normal if line.startswith(':: '): current_section = line[3:].strip() if current_section not in ('new features', 'bug fixes', 'new recipes', 'improved recipes'): raise ValueError(f'Unknown section: {current_section}') return in_entry if line.startswith('-'): return start_item(linenum, line, stripped_line) if not stripped_line: return in_entry raise ValueError(f'Invalid content at line {linenum}: {line}') def start_item(linenum, line, stripped_line): line = line[1:].lstrip() items = current_entry[current_section] if current_section == 'improved recipes': items.append(line.rstrip()) return in_entry if current_section == 'new recipes': idx = line.rfind('by ') if idx == -1: items.append({'title': line.strip()}) else: items.append({'title': line[:idx].strip(), 'author': line[idx + 3:].strip()}) return in_entry item = {} if line.startswith('['): idx = line.find(']') if idx == -1: raise ValueError(f'No closing ] found in line: {linenum}') for x in line[1:idx].split(): if x == 'major': item['type'] = x continue num = int(x) item.setdefault('tickets', []).append(num) item['title'] = line[idx+1:].strip() else: item['title'] = line.strip() items.append(item) return in_item def finalize_item(item): if 'description' in item and not item['description']: del item['description'] if 'description' in item: item['description'] = item['description'].strip() return item def in_item(linenum, line, stripped_line): item = current_entry[current_section][-1] if line.startswith('::'): finalize_item(item) return in_entry(linenum, line, stripped_line) if line.startswith('-'): finalize_item(item) return start_item(linenum, line, stripped_line) if line.startswith('}' '}' '}'): return in_entry(linenum, line, stripped_line) if not stripped_line: if 'description' not in item: item['description'] = '' return in_item if 'description' in item: item['description'] += stripped_line + ' ' else: item['title'] += ' ' + stripped_line return in_item state = normal for i, line in enumerate(raw.splitlines()): if line.startswith('#'): continue stripped_line = line.strip() state = state(i + 1, line, stripped_line) return entries def migrate(): from yaml import safe_load def output_item(item, lines): meta = [] if item.get('type') == 'major': meta.append(item['type']) for x in item.get('tickets', ()): meta.append(str(x)) title = item['title'] if meta: meta = ' '.join(meta) title = f'[{meta}] {title}' lines.append(f'- {title}') d = item.get('description') if d: lines.append(''), lines.append(d) lines.append('') for name in ('Changelog.yaml', 'Changelog.old.yaml'): entries = safe_load(open(name).read()) lines = [] for entry in entries: lines.append('') lines.append('{' '{' '{' f' {entry["version"]} {entry["date"]}') for w in ('new features', 'bug fixes'): nf = entry.get(w) if nf: lines.append(f':: {w}'), lines.append('') for x in nf: output_item(x, lines) lines.append('') nr = entry.get('new recipes') if nr: lines.append(':: new recipes'), lines.append('') for r in nr: aut = r.get('author') or r.get('authors') title = r['title'] if title: if aut: lines.append(f'- {title} by {aut}') else: lines.append(f'- {title}') lines.append('') ir = entry.get('improved recipes') if ir: lines.append(':: improved recipes'), lines.append('') for r in ir: lines.append(f'- {r}') lines.append('') with open(name.replace('yaml', 'txt'), 'w') as f: f.write('\n'.join(lines)) lines.append(''), lines.append('}' '}' '}'), lines.append('') if __name__ == '__main__': migrate()
6,448
Python
.py
158
28.626582
139
0.510438
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,369
git_post_rewrite_hook.py
kovidgoyal_calibre/setup/git_post_rewrite_hook.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import subprocess import sys base = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) os.chdir(base) action = [x.decode('utf-8') if isinstance(x, bytes) else x for x in sys.argv[1:]][0] if action == 'rebase': subprocess.check_call(['./setup.py', 'gui', '--summary'])
404
Python
.py
11
34.909091
84
0.688144
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,370
mathjax.py
kovidgoyal_calibre/setup/mathjax.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json import os from hashlib import sha1 from setup.revendor import ReVendor class MathJax(ReVendor): description = 'Create the MathJax bundle' NAME = 'mathjax' TAR_NAME = 'MathJax' VERSION = '3.1.4' DOWNLOAD_URL = 'https://github.com/mathjax/MathJax/archive/%s.tar.gz' % VERSION def add_file_pre(self, name, raw): self.h.update(raw) self.mathjax_files[name] = len(raw) def already_present(self): manifest = self.j(self.vendored_dir, 'manifest.json') if os.path.exists(manifest): with open(manifest, 'rb') as f: return json.load(f).get('version') == self.VERSION return False def run(self, opts): if not opts.system_mathjax and self.already_present(): self.info('MathJax already present in the resources directory, not downloading') return self.use_symlinks = opts.system_mathjax self.h = sha1() self.mathjax_files = {} self.clean() os.mkdir(self.vendored_dir) with self.temp_dir(suffix='-calibre-mathjax-build') as tdir: src = opts.path_to_mathjax or self.download_vendor_release(tdir, opts.mathjax_url) if os.path.isdir(os.path.join(src, 'es5')): src = os.path.join(src, 'es5') self.info('Adding MathJax...') for x in 'core loader startup input/tex-full input/asciimath input/mml input/mml/entities output/chtml'.split(): self.add_file(self.j(src, x + '.js'), x + '.js') self.add_tree( self.j(src, 'output', 'chtml'), 'output/chtml') etag = self.h.hexdigest() with open(self.j(self.RESOURCES, 'mathjax', 'manifest.json'), 'wb') as f: f.write(json.dumps({'etag': etag, 'files': self.mathjax_files, 'version': self.VERSION}, indent=2).encode('utf-8'))
2,043
Python
.py
44
37.75
131
0.617396
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,371
vcvars.py
kovidgoyal_calibre/setup/vcvars.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import ctypes.wintypes import os import re import subprocess import sys from functools import lru_cache from glob import glob CSIDL_PROGRAM_FILES = 38 CSIDL_PROGRAM_FILESX86 = 42 @lru_cache def get_program_files_location(which=CSIDL_PROGRAM_FILESX86): SHGFP_TYPE_CURRENT = 0 buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) ctypes.windll.shell32.SHGetFolderPathW( 0, which, 0, SHGFP_TYPE_CURRENT, buf) return buf.value @lru_cache def find_vswhere(): for which in (CSIDL_PROGRAM_FILESX86, CSIDL_PROGRAM_FILES): root = get_program_files_location(which) vswhere = os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe") if os.path.exists(vswhere): return vswhere raise SystemExit('Could not find vswhere.exe') def get_output(*cmd): return subprocess.check_output(cmd, encoding='mbcs', errors='strict') @lru_cache def find_visual_studio(): path = get_output( find_vswhere(), "-latest", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath", "-products", "*" ).strip() return os.path.join(path, "VC", "Auxiliary", "Build") @lru_cache def find_msbuild(): base_path = get_output( find_vswhere(), "-latest", "-requires", "Microsoft.Component.MSBuild", "-property", 'installationPath' ).strip() return glob(os.path.join( base_path, 'MSBuild', '*', 'Bin', 'MSBuild.exe'))[0] def find_vcvarsall(): productdir = find_visual_studio() vcvarsall = os.path.join(productdir, "vcvarsall.bat") if os.path.isfile(vcvarsall): return vcvarsall raise SystemExit("Unable to find vcvarsall.bat in productdir: " + productdir) def remove_dups(variable): old_list = variable.split(os.pathsep) new_list = [] for i in old_list: if i not in new_list: new_list.append(i) return os.pathsep.join(new_list) def query_process(cmd, is64bit): if is64bit and 'PROGRAMFILES(x86)' not in os.environ: os.environ['PROGRAMFILES(x86)'] = get_program_files_location() result = {} popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: stdout, stderr = popen.communicate() if popen.wait() != 0: raise RuntimeError(stderr.decode("mbcs")) stdout = stdout.decode("mbcs") for line in stdout.splitlines(): if '=' not in line: continue line = line.strip() key, value = line.split('=', 1) key = key.lower() if key == 'path': if value.endswith(os.pathsep): value = value[:-1] value = remove_dups(value) result[key] = value finally: popen.stdout.close() popen.stderr.close() return result @lru_cache def query_vcvarsall(is64bit=True): plat = 'amd64' if is64bit else 'amd64_x86' vcvarsall = find_vcvarsall() env = query_process(f'"{vcvarsall}" {plat} & set', is64bit) pat = re.compile(r'vs(\d+)comntools', re.I) comn_tools = {} for k in env: m = pat.match(k) if m is not None: comn_tools[k] = int(m.group(1)) comntools = sorted(comn_tools, key=comn_tools.__getitem__)[-1] def g(k): try: return env[k] except KeyError: try: return env[k.lower()] except KeyError: for k, v in env.items(): print(f'{k}={v}', file=sys.stderr) raise return { k: g(k) for k in ( 'PATH LIB INCLUDE LIBPATH WINDOWSSDKDIR' f' {comntools} PLATFORM' ' UCRTVERSION UNIVERSALCRTSDKDIR VCTOOLSVERSION WINDOWSSDKDIR' ' WINDOWSSDKVERSION WINDOWSSDKVERBINPATH WINDOWSSDKBINPATH' ' VISUALSTUDIOVERSION VSCMD_ARG_HOST_ARCH VSCMD_ARG_TGT_ARCH' ).split() }
4,259
Python
.py
125
25.864
76
0.600195
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,372
xwin.py
kovidgoyal_calibre/setup/xwin.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> import os import runpy import shutil from setup import Command class XWin(Command): description = 'Install the Windows headers for cross compilation' def run(self, opts): if not shutil.which('msiextract'): raise SystemExit('No msiextract found in PATH you may need to install msitools') base = os.path.dirname(self.SRC) m = runpy.run_path(os.path.join(base, 'setup', 'wincross.py')) cache_dir = os.path.join(base, '.build-cache', 'xwin') if os.path.exists(cache_dir): shutil.rmtree(cache_dir) os.makedirs(cache_dir) m['main'](['--dest', cache_dir]) for x in os.listdir(cache_dir): if x != 'root': shutil.rmtree(os.path.join(cache_dir, x))
863
Python
.py
21
33.904762
92
0.643541
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,373
run-calibre-worker.py
kovidgoyal_calibre/setup/run-calibre-worker.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import os import sys sys.setup_dir = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.abspath(os.path.join(os.path.dirname(sys.setup_dir), 'src')) sys.path.insert(0, SRC) sys.resources_location = os.path.join(os.path.dirname(SRC), 'resources') sys.extensions_location = os.path.join(SRC, 'calibre', 'plugins') sys.running_from_setup = True from calibre.utils.ipc.worker import main sys.exit(main())
506
Python
.py
12
40.75
74
0.756646
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,374
csslint.py
kovidgoyal_calibre/setup/csslint.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import os import shutil import subprocess from setup import Command class CSSLint(Command): description = 'Update the bundled copy of stylelint' NAME = 'stylelint-bundle.min.js' DOWNLOAD_URL = 'https://github.com/openstyles/stylelint-bundle.git' @property def vendored_file(self): return os.path.join(self.RESOURCES, self.NAME) def run(self, opts): self.clean() with self.temp_dir() as dl_src: subprocess.check_call(['git', 'clone', '--depth=1', self.DOWNLOAD_URL], cwd=dl_src) src = self.j(dl_src, 'stylelint-bundle') subprocess.check_call(['npm', 'install'], cwd=src) subprocess.check_call(['npm', 'run', 'build'], cwd=src) shutil.copyfile(self.j(src, 'dist', self.NAME), self.vendored_file) def clean(self): if os.path.exists(self.vendored_file): os.remove(self.vendored_file)
1,015
Python
.py
24
35.458333
95
0.657172
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,375
build.py
kovidgoyal_calibre/setup/build.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import glob import json import os import shlex import shutil import subprocess import sys import sysconfig import textwrap from functools import partial from typing import List, NamedTuple from setup import SRC, Command, isbsd, isfreebsd, ishaiku, islinux, ismacos, iswindows isunix = islinux or ismacos or isbsd or ishaiku py_lib = os.path.join(sys.prefix, 'libs', 'python%d%d.lib' % sys.version_info[:2]) class CompileCommand(NamedTuple): cmd: List[str] src: str dest: str class LinkCommand(NamedTuple): cmd: List[str] objects: List[str] dest: str def walk(path='.'): for dirpath, dirnames, filenames in os.walk(path): for f in filenames: yield os.path.join(dirpath, f) def init_symbol_name(name): prefix = 'PyInit_' return prefix + name def absolutize(paths): return list({x if os.path.isabs(x) else os.path.join(SRC, x.replace('/', os.sep)) for x in paths}) class Extension: def __init__(self, name, sources, **kwargs): self.data = d = {} self.name = d['name'] = name self.sources = d['sources'] = absolutize(sources) self.needs_cxx = d['needs_cxx'] = bool([1 for x in self.sources if os.path.splitext(x)[1] in ('.cpp', '.c++', '.cxx')]) self.needs_py2 = d['needs_py2'] = kwargs.get('needs_py2', False) self.headers = d['headers'] = absolutize(kwargs.get('headers', [])) self.sip_files = d['sip_files'] = absolutize(kwargs.get('sip_files', [])) self.needs_exceptions = d['needs_exceptions'] = kwargs.get('needs_exceptions', False) self.qt_modules = d['qt_modules'] = kwargs.get('qt_modules', ["widgets"]) self.inc_dirs = d['inc_dirs'] = absolutize(kwargs.get('inc_dirs', [])) self.lib_dirs = d['lib_dirs'] = absolutize(kwargs.get('lib_dirs', [])) self.extra_objs = d['extra_objs'] = absolutize(kwargs.get('extra_objs', [])) self.error = d['error'] = kwargs.get('error', None) self.libraries = d['libraries'] = kwargs.get('libraries', []) self.cflags = d['cflags'] = kwargs.get('cflags', []) self.uses_icu = 'icuuc' in self.libraries self.ldflags = d['ldflags'] = kwargs.get('ldflags', []) self.optional = d['options'] = kwargs.get('optional', False) self.needs_cxx_std = kwargs.get('needs_c++') self.needs_c_std = kwargs.get('needs_c') self.only_build_for = kwargs.get('only', '') def lazy_load(name): if name.startswith('!'): name = name[1:] from setup import build_environment try: return getattr(build_environment, name) except AttributeError: raise ImportError('The setup.build_environment module has no symbol named: %s' % name) def expand_file_list(items, is_paths=True, cross_compile_for='native'): if not items: return [] ans = [] for item in items: if item.startswith('!'): if cross_compile_for == 'native' or not item.endswith('_dirs'): item = lazy_load(item) if hasattr(item, 'rjust'): item = [item] items = expand_file_list(item, is_paths=is_paths, cross_compile_for=cross_compile_for) else: pkg, category = item[1:].split('_')[:2] if category == 'inc': category = 'include' items = [f'bypy/b/windows/64/{pkg}/{category}'] items = expand_file_list(item, is_paths=is_paths, cross_compile_for=cross_compile_for) ans.extend(items) else: if '*' in item: ans.extend(expand_file_list(sorted(glob.glob(os.path.join(SRC, item))), is_paths=is_paths, cross_compile_for=cross_compile_for)) else: item = [item] if is_paths: item = absolutize(item) ans.extend(item) return ans def is_ext_allowed(cross_compile_for: str, ext: Extension) -> bool: only = ext.only_build_for if only: if islinux and only == cross_compile_for: return True only = set(only.split()) q = set(filter(lambda x: globals()["is" + x], ["bsd", "freebsd", "haiku", "linux", "macos", "windows"])) return len(q.intersection(only)) > 0 return True def parse_extension(ext, compiling_for='native'): ext = ext.copy() only = ext.pop('only', None) kw = {} name = ext.pop('name') get_key = 'linux_' if iswindows: get_key = 'windows_' elif ismacos: get_key = 'macos_' elif isbsd: get_key = 'bsd_' elif isfreebsd: get_key = 'freebsd_' elif ishaiku: get_key = 'haiku_' if compiling_for == 'windows': get_key = 'windows_' def get(k, default=''): ans = ext.pop(k, default) ans = ext.pop(get_key + k, ans) return ans for k in 'libraries qt_private ldflags cflags error'.split(): kw[k] = expand_file_list(get(k).split(), is_paths=False) defines = get('defines') if defines: if 'cflags' not in kw: kw['cflags'] = [] cflags = kw['cflags'] prefix = '/D' if get_key == 'windows_' else '-D' cflags.extend(prefix + x for x in defines.split()) for k in 'inc_dirs lib_dirs sources headers sip_files'.split(): v = get(k) if v: kw[k] = expand_file_list(v.split()) kw.update(ext) kw['only'] = only return Extension(name, **kw) def read_extensions(): if hasattr(read_extensions, 'extensions'): return read_extensions.extensions with open(os.path.dirname(os.path.abspath(__file__)) + '/extensions.json', 'rb') as f: ans = read_extensions.extensions = json.load(f) return ans def get_python_include_paths(): ans = [] for name in sysconfig.get_path_names(): if 'include' in name: ans.append(name) def gp(x): return sysconfig.get_path(x) return sorted(frozenset(filter(None, map(gp, sorted(ans))))) is_macos_universal_build = ismacos and 'universal2' in sysconfig.get_platform() def basic_windows_flags(debug=False): cflags = '/c /nologo /W3 /EHsc /O2 /utf-8'.split() cflags.append('/Zi' if debug else '/DNDEBUG') suffix = ('d' if debug else '') cflags.append('/MD' + suffix) ldflags = f'/DLL /nologo /INCREMENTAL:NO /NODEFAULTLIB:libcmt{suffix}.lib'.split() if debug: ldflags.append('/DEBUG') # cflags = '/c /nologo /Ox /MD /W3 /EHsc /Zi'.split() # ldflags = '/DLL /nologo /INCREMENTAL:NO /DEBUG'.split() cflags.append('/GS-') return cflags, ldflags class Environment(NamedTuple): cc: str cxx: str linker: str base_cflags: List[str] base_cxxflags: List[str] base_ldflags: List[str] cflags: List[str] ldflags: List[str] make: str internal_inc_prefix: str external_inc_prefix: str libdir_prefix: str lib_prefix: str lib_suffix: str obj_suffix: str cc_input_c_flag: str cc_input_cpp_flag: str cc_output_flag: str platform_name: str dest_ext: str std_prefix: str def inc_dirs_to_cflags(self, dirs) -> List[str]: return [self.external_inc_prefix+x for x in dirs] def lib_dirs_to_ldflags(self, dirs) -> List[str]: return [self.libdir_prefix+x for x in dirs if x] def libraries_to_ldflags(self, libs): def map_name(x): if '/' in x: return x return self.lib_prefix+x+self.lib_suffix return list(map(map_name, libs)) def init_env(debug=False, sanitize=False, compiling_for='native'): from setup.build_environment import NMAKE, win_cc, win_inc, win_ld, win_lib linker = None internal_inc_prefix = external_inc_prefix = '-I' libdir_prefix = '-L' lib_prefix = '-l' lib_suffix = '' std_prefix = '-std=' obj_suffix = '.o' cc_input_c_flag = cc_input_cpp_flag = '-c' cc_output_flag = '-o' platform_name = 'linux' dest_ext = '.so' if isunix: cc = os.environ.get('CC', 'gcc') cxx = os.environ.get('CXX', 'g++') debug = '-ggdb' if debug else '' cflags = os.environ.get('OVERRIDE_CFLAGS', f'-Wall -DNDEBUG {debug} -fno-strict-aliasing -pipe -O3') cflags = shlex.split(cflags) + ['-fPIC'] ldflags = os.environ.get('OVERRIDE_LDFLAGS', '-Wall') ldflags = shlex.split(ldflags) base_cflags = shlex.split(os.environ.get('CFLAGS', '')) base_cxxflags = shlex.split(os.environ.get('CXXFLAGS', '')) base_ldflags = shlex.split(os.environ.get('LDFLAGS', '')) cflags += base_cflags ldflags += base_ldflags cflags += ['-fvisibility=hidden'] if sanitize: cflags.append('-fsanitize=address') if islinux: cflags.append('-pthread') if sys.stdout.isatty(): base_cflags.append('-fdiagnostics-color=always') cflags.append('-fdiagnostics-color=always') ldflags.append('-shared') if isbsd: cflags.append('-pthread') ldflags.append('-shared') if ishaiku: cflags.append('-lpthread') ldflags.append('-shared') if islinux or isbsd or ishaiku: cflags.extend('-I' + x for x in get_python_include_paths()) ldlib = sysconfig.get_config_var('LIBDIR') if ldlib: ldflags += ['-L' + ldlib] ldlib = sysconfig.get_config_var('VERSION') if ldlib: ldflags += ['-lpython' + ldlib + sys.abiflags] ldflags += (sysconfig.get_config_var('LINKFORSHARED') or '').split() if ismacos: platform_name = 'macos' if is_macos_universal_build: cflags.extend(['-arch', 'x86_64', '-arch', 'arm64']) ldflags.extend(['-arch', 'x86_64', '-arch', 'arm64']) cflags.append('-D_OSX') ldflags.extend('-bundle -undefined dynamic_lookup'.split()) cflags.extend(['-fno-common', '-dynamic']) cflags.extend('-I' + x for x in get_python_include_paths()) if iswindows or compiling_for == 'windows': platform_name = 'windows' std_prefix = '/std:' cc = cxx = win_cc linker = win_ld cflags, ldflags = basic_windows_flags(debug) base_cflags, base_cxxflags, base_ldflags = [], [], [] if compiling_for == 'windows': cc = cxx = 'clang-cl' linker = 'lld-link' splat = '.build-cache/xwin/root' cflags.append('-fcolor-diagnostics') cflags.append('-fansi-escape-codes') for I in 'sdk/include/um sdk/include/cppwinrt sdk/include/shared sdk/include/ucrt crt/include'.split(): cflags.append('/external:I') cflags.append(f'{splat}/{I}') for L in 'sdk/lib/um crt/lib sdk/lib/ucrt'.split(): ldflags.append(f'/libpath:{splat}/{L}') else: for p in win_inc: cflags.append('-I'+p) for p in win_lib: if p: ldflags.append('/LIBPATH:'+p) internal_inc_prefix = external_inc_prefix = '/I' libdir_prefix = '/libpath:' lib_prefix = '' lib_suffix = '.lib' cc_input_c_flag = '/Tc' cc_input_cpp_flag = '/Tp' cc_output_flag = '/Fo' obj_suffix = '.obj' dest_ext = '.pyd' if compiling_for == 'windows': external_inc_prefix = '/external:I' dest_ext = '.cross-windows-x64' + dest_ext obj_suffix = '.cross-windows-x64' + obj_suffix cflags.append('/external:I') cflags.append('bypy/b/windows/64/pkg/python/private/python/include') ldflags.append('/libpath:' + 'bypy/b/windows/64/pkg/python/private/python/libs') else: cflags.extend('-I' + x for x in get_python_include_paths()) ldflags.append('/LIBPATH:'+os.path.join(sysconfig.get_config_var('prefix'), 'libs')) return Environment( platform_name=platform_name, dest_ext=dest_ext, std_prefix=std_prefix, base_cflags=base_cflags, base_cxxflags=base_cxxflags, base_ldflags=base_ldflags, cc=cc, cxx=cxx, cflags=cflags, ldflags=ldflags, linker=linker, make=NMAKE if iswindows else 'make', lib_prefix=lib_prefix, obj_suffix=obj_suffix, cc_input_c_flag=cc_input_c_flag, cc_input_cpp_flag=cc_input_cpp_flag, cc_output_flag=cc_output_flag, internal_inc_prefix=internal_inc_prefix, external_inc_prefix=external_inc_prefix, libdir_prefix=libdir_prefix, lib_suffix=lib_suffix) class Build(Command): short_description = 'Build calibre C/C++ extension modules' DEFAULT_OUTPUTDIR = os.path.abspath(os.path.join(SRC, 'calibre', 'plugins')) DEFAULT_BUILDDIR = os.path.abspath(os.path.join(os.path.dirname(SRC), 'build')) description = textwrap.dedent('''\ calibre depends on several python extensions written in C/C++. This command will compile them. You can influence the compile process by several environment variables, listed below: CC - C Compiler defaults to gcc CXX - C++ Compiler, defaults to g++ CFLAGS - Extra compiler flags LDFLAGS - Extra linker flags POPPLER_INC_DIR - poppler header files POPPLER_LIB_DIR - poppler-qt4 library PODOFO_INC_DIR - podofo header files PODOFO_LIB_DIR - podofo library files QMAKE - Path to qmake ''') def add_options(self, parser): choices = [e['name'] for e in read_extensions()]+['all', 'headless'] parser.add_option('-1', '--only', choices=choices, default='all', help=('Build only the named extension. Available: '+ ', '.join(choices)+'. Default:%default')) parser.add_option('--no-compile', default=False, action='store_true', help='Skip compiling all C/C++ extensions.') parser.add_option('--build-dir', default=None, help='Path to directory in which to place object files during the build process, defaults to "build"') parser.add_option('--output-dir', default=None, help='Path to directory in which to place the built extensions. Defaults to src/calibre/plugins') parser.add_option('--debug', default=False, action='store_true', help='Build in debug mode') parser.add_option('--sanitize', default=False, action='store_true', help='Build with sanitization support. Run with LD_PRELOAD=$(gcc -print-file-name=libasan.so)') parser.add_option('--cross-compile-extensions', choices='windows disabled'.split(), default='disabled', help=('Cross compile extensions for other platforms. Useful for development.' ' Currently supports of windows extensions on Linux. Remember to run ./setup.py xwin first to install the Windows SDK locally. ')) def dump_db(self, name, db): os.makedirs('build', exist_ok=True) existing = [] try: with open(f'build/{name}_commands.json', 'rb') as f: existing = json.load(f) except FileNotFoundError: pass combined = {x['output']: x for x in existing} for x in db: combined[x['output']] = x try: with open(f'build/{name}_commands.json', 'w') as f: json.dump(tuple(combined.values()), f, indent=2) except OSError as err: if err.errno != errno.EROFS: raise def run(self, opts): from setup.parallel_build import create_job, parallel_build if opts.no_compile: self.info('--no-compile specified, skipping compilation') return self.compiling_for = 'native' if islinux and opts.cross_compile_extensions == 'windows': self.compiling_for = 'windows' if not os.path.exists('.build-cache/xwin/root'): subprocess.check_call([sys.executable, 'setup.py', 'xwin']) self.env = init_env(debug=opts.debug) self.windows_cross_env = init_env(debug=opts.debug, compiling_for='windows') all_extensions = tuple(map(partial(parse_extension, compiling_for=self.compiling_for), read_extensions())) self.build_dir = os.path.abspath(opts.build_dir or self.DEFAULT_BUILDDIR) self.output_dir = os.path.abspath(opts.output_dir or self.DEFAULT_OUTPUTDIR) self.obj_dir = os.path.join(self.build_dir, 'objects') for x in (self.output_dir, self.obj_dir): os.makedirs(x, exist_ok=True) pyqt_extensions, extensions = [], [] for ext in all_extensions: if opts.only != 'all' and opts.only != ext.name: continue if not is_ext_allowed(self.compiling_for, ext): continue if ext.error: if ext.optional: self.warn(ext.error) continue else: raise Exception(ext.error) (pyqt_extensions if ext.sip_files else extensions).append(ext) jobs = [] objects_map = {} self.info(f'Building {len(extensions)+len(pyqt_extensions)} extensions') ccdb = [] for ext in all_extensions: if ext in pyqt_extensions: continue cmds, objects = self.get_compile_commands(ext, ccdb) objects_map[id(ext)] = objects if ext in extensions: for cmd in cmds: jobs.append(create_job(cmd.cmd)) self.dump_db('compile', ccdb) if jobs: self.info(f'Compiling {len(jobs)} files...') if not parallel_build(jobs, self.info): raise SystemExit(1) jobs, link_commands, lddb = [], [], [] for ext in all_extensions: if ext in pyqt_extensions: continue objects = objects_map[id(ext)] cmd = self.get_link_command(ext, objects, lddb) if ext in extensions and cmd is not None: link_commands.append(cmd) jobs.append(create_job(cmd.cmd)) self.dump_db('link', lddb) if jobs: self.info(f'Linking {len(jobs)} files...') if not parallel_build(jobs, self.info): raise SystemExit(1) for cmd in link_commands: self.post_link_cleanup(cmd) jobs = [] sbf_map = {} for ext in pyqt_extensions: cmd, sbf, cwd = self.get_sip_commands(ext) sbf_map[id(ext)] = sbf if cmd is not None: jobs.append(create_job(cmd, cwd=cwd)) if jobs: self.info(f'SIPing {len(jobs)} files...') if not parallel_build(jobs, self.info): raise SystemExit(1) for ext in pyqt_extensions: sbf = sbf_map[id(ext)] if not os.path.exists(sbf): self.build_pyqt_extension(ext, sbf) if opts.only in {'all', 'headless'}: self.build_headless() def dest(self, ext, env): return os.path.join(self.output_dir, getattr(ext, 'name', ext))+env.dest_ext def env_for_compilation_db(self, ext): if is_ext_allowed('native', ext): return self.env if ext.only_build_for == 'windows': return self.windows_cross_env def get_compile_commands(self, ext, db): obj_dir = self.j(self.obj_dir, ext.name) def get(src: str, env: Environment, for_tooling: bool = False) -> CompileCommand: compiler = env.cxx if ext.needs_cxx else env.cc obj = self.j(obj_dir, os.path.splitext(self.b(src))[0]+env.obj_suffix) inf = env.cc_input_cpp_flag if src.endswith('.cpp') or src.endswith('.cxx') else env.cc_input_c_flag sinc = [inf, src] if env.cc_output_flag.startswith('/'): if for_tooling: # clangd gets confused by cl.exe style source and output flags oinc = ['-o', obj] else: oinc = [env.cc_output_flag + obj] sinc = [inf + src] else: oinc = [env.cc_output_flag, obj] einc = env.inc_dirs_to_cflags(ext.inc_dirs) if env.cc_output_flag.startswith('/'): cflags = ['/DCALIBRE_MODINIT_FUNC=PyMODINIT_FUNC'] else: return_type = 'PyObject*' extern_decl = 'extern "C"' if ext.needs_cxx else '' cflags = [ '-DCALIBRE_MODINIT_FUNC=' '{} __attribute__ ((visibility ("default"))) {}'.format(extern_decl, return_type)] if ext.needs_cxx and ext.needs_cxx_std: if env.cc_output_flag.startswith('/') and ext.needs_cxx == "11": ext.needs_cxx = "14" cflags.append(env.std_prefix + 'c++' + ext.needs_cxx_std) if ext.needs_c_std and not env.std_prefix.startswith('/'): cflags.append(env.std_prefix + 'c' + ext.needs_c_std) cmd = [compiler] + env.cflags + cflags + ext.cflags + einc + sinc + oinc return CompileCommand(cmd, src, obj) objects = [] ans = [] os.makedirs(obj_dir, exist_ok=True) for src in ext.sources: cc = get(src, self.windows_cross_env if self.compiling_for == 'windows' else self.env) objects.append(cc.dest) if self.newer(cc.dest, [src]+ext.headers): ans.append(cc) env = self.env_for_compilation_db(ext) if env is not None: cc = get(src, env, for_tooling=True) db.append({ 'arguments': cc.cmd, 'directory': os.getcwd(), 'file': os.path.relpath(src, os.getcwd()), 'output': os.path.relpath(cc.dest, os.getcwd())}) return ans, objects def get_link_command(self, ext, objects, lddb): def get(env: Environment) -> LinkCommand: dest = self.dest(ext, env) compiler = env.cxx if ext.needs_cxx else env.cc linker = env.linker or compiler cmd = [linker] elib = env.lib_dirs_to_ldflags(ext.lib_dirs) xlib = env.libraries_to_ldflags(ext.libraries) all_objects = sorted(objects + ext.extra_objs) if iswindows or env is self.windows_cross_env: pre_ld_flags = [] if ext.uses_icu: # windows has its own ICU libs that dont work pre_ld_flags = elib cmd += pre_ld_flags + env.ldflags + ext.ldflags + elib + xlib + \ ['/EXPORT:' + init_symbol_name(ext.name)] + all_objects + ['/OUT:'+dest] else: cmd += all_objects + ['-o', dest] + env.ldflags + ext.ldflags + elib + xlib return LinkCommand(cmd, objects, dest) env = self.env_for_compilation_db(ext) if env is not None: ld = get(env) lddb.append({'arguments': ld.cmd, 'directory': os.getcwd(), 'output': os.path.relpath(ld.dest, os.getcwd())}) env = self.windows_cross_env if self.compiling_for == 'windows' else self.env lc = get(env) if self.newer(lc.dest, objects+ext.extra_objs): return lc def post_link_cleanup(self, link_command): if iswindows: dest = link_command.dest for x in ('.exp', '.lib'): x = os.path.splitext(dest)[0]+x if os.path.exists(x): os.remove(x) def check_call(self, *args, **kwargs): """print cmdline if an error occurred If something is missing (cmake e.g.) you get a non-informative error self.check_call(qmc + [ext.name+'.pro']) so you would have to look at the source to see the actual command. """ try: subprocess.check_call(*args, **kwargs) except: cmdline = ' '.join(['"%s"' % (arg) if ' ' in arg else arg for arg in args[0]]) print("Error while executing: %s\n" % (cmdline)) raise def build_headless(self): from setup.parallel_build import cpu_count if iswindows or ishaiku: return # Dont have headless operation on these platforms from setup.build_environment import CMAKE, sw self.info('\n####### Building headless QPA plugin', '#'*7) a = absolutize headers = a([ 'calibre/headless/headless_backingstore.h', 'calibre/headless/headless_integration.h', ]) sources = a([ 'calibre/headless/main.cpp', 'calibre/headless/headless_backingstore.cpp', 'calibre/headless/headless_integration.cpp', ]) others = a(['calibre/headless/headless.json']) target = self.dest('headless', self.env) if not ismacos: target = target.replace('headless', 'libheadless') if not self.newer(target, headers + sources + others): return bdir = self.j(self.build_dir, 'headless') if os.path.exists(bdir): shutil.rmtree(bdir) cmd = [CMAKE] if is_macos_universal_build: cmd += ['-DCMAKE_OSX_ARCHITECTURES=x86_64;arm64'] if sw and os.path.exists(os.path.join(sw, 'qt')): cmd += ['-DCMAKE_SYSTEM_PREFIX_PATH=' + os.path.join(sw, 'qt').replace(os.sep, '/')] os.makedirs(bdir) cwd = os.getcwd() os.chdir(bdir) try: self.check_call(cmd + ['-S', os.path.dirname(sources[0])]) self.check_call([self.env.make] + ['-j%d'%(cpu_count or 1)]) finally: os.chdir(cwd) os.rename(self.j(bdir, 'libheadless.so'), target) def create_sip_build_skeleton(self, src_dir, ext): from setup.build_environment import pyqt_sip_abi_version abi_version = '' if pyqt_sip_abi_version(): abi_version = f'abi-version = "{pyqt_sip_abi_version()}"' sipf = ext.sip_files[0] needs_exceptions = 'true' if ext.needs_exceptions else 'false' with open(os.path.join(src_dir, 'pyproject.toml'), 'w') as f: f.write(f''' [build-system] requires = ["sip >=5.3", "PyQt-builder >=1"] build-backend = "sipbuild.api" [tool.sip] project-factory = "pyqtbuild:PyQtProject" [tool.sip.project] sip-files-dir = "." {abi_version} [project] name = "{ext.name}" [tool.sip.builder] qmake-settings = [ """QMAKE_CC = {self.env.cc}""", """QMAKE_CXX = {self.env.cxx}""", """QMAKE_LINK = {self.env.linker or self.env.cxx}""", """QMAKE_CFLAGS += {shlex.join(self.env.base_cflags)}""", """QMAKE_CXXFLAGS += {shlex.join(self.env.base_cxxflags)}""", """QMAKE_LFLAGS += {shlex.join(self.env.base_ldflags)}""", ] [tool.sip.bindings.{ext.name}] headers = {sorted(ext.headers)} sources = {sorted(ext.sources)} exceptions = {needs_exceptions} include-dirs = {ext.inc_dirs} qmake-QT = {ext.qt_modules} sip-file = {os.path.basename(sipf)!r} ''') shutil.copy2(sipf, src_dir) def get_sip_commands(self, ext): from setup.build_environment import QMAKE pyqt_dir = self.j(self.build_dir, 'pyqt') src_dir = self.j(pyqt_dir, ext.name) # TODO: Handle building extensions with multiple SIP files. sipf = ext.sip_files[0] sbf = self.j(src_dir, self.b(sipf)+'.sbf') cmd = None cwd = None if self.newer(sbf, [sipf] + ext.headers + ext.sources): shutil.rmtree(src_dir, ignore_errors=True) os.makedirs(src_dir) self.create_sip_build_skeleton(src_dir, ext) cwd = src_dir cmd = [ sys.executable, '-m', 'sipbuild.tools.build', '--verbose', '--no-make', '--qmake', QMAKE ] return cmd, sbf, cwd def build_pyqt_extension(self, ext, sbf): self.info(f'\n####### Building {ext.name} extension', '#'*7) src_dir = os.path.dirname(sbf) cwd = os.getcwd() try: os.chdir(os.path.join(src_dir, 'build')) env = os.environ.copy() if is_macos_universal_build: env['ARCHS'] = 'x86_64 arm64' self.check_call([self.env.make] + ([] if iswindows else ['-j%d'%(os.cpu_count() or 1)]), env=env) e = 'pyd' if iswindows else 'so' m = glob.glob(f'{ext.name}/{ext.name}.*{e}') if not m: raise SystemExit(f'No built PyQt extension file in {os.path.join(os.getcwd(), ext.name)}') if len(m) != 1: raise SystemExit(f'Found extra PyQt extension files: {m}') shutil.copy2(m[0], self.dest(ext, self.env)) with open(sbf, 'w') as f: f.write('done') finally: os.chdir(cwd) def clean(self): self.output_dir = self.DEFAULT_OUTPUTDIR extensions = map(parse_extension, read_extensions()) env = init_env() for ext in extensions: dest = self.dest(ext, env) b, d = os.path.basename(dest), os.path.dirname(dest) b = b.split('.')[0] + '.*' for x in glob.glob(os.path.join(d, b)): if os.path.exists(x): os.remove(x) build_dir = self.DEFAULT_BUILDDIR if os.path.exists(build_dir): shutil.rmtree(build_dir)
29,738
Python
.py
672
34.4375
146
0.580121
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,376
install.py
kovidgoyal_calibre/setup/install.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2009, Kovid Goyal <kovid at kovidgoyal.net> import atexit import glob import os import shutil import subprocess import sys import tempfile import textwrap import time from setup import Command, __appname__, __version__, basenames, functions, isbsd, ishaiku, islinux, modules HEADER = '''\ #!/usr/bin/env python{py_major_version} """ This is the standard runscript for all of calibre's tools. Do not modify it unless you know what you are doing. """ import sys, os path = os.environ.get('CALIBRE_PYTHON_PATH', {path!r}) if path not in sys.path: sys.path.insert(0, path) sys.resources_location = os.environ.get('CALIBRE_RESOURCES_PATH', {resources!r}) sys.extensions_location = os.environ.get('CALIBRE_EXTENSIONS_PATH', {extensions!r}) sys.executables_location = os.environ.get('CALIBRE_EXECUTABLES_PATH', {executables!r}) sys.system_plugins_location = {system_plugins_loc!r} ''' TEMPLATE = HEADER+''' from {module} import {func!s} sys.exit({func!s}()) ''' COMPLETE_TEMPLATE = HEADER+''' sys.path.insert(0, os.path.join(path, 'calibre', 'utils')) import complete sys.path = sys.path[1:] sys.exit(complete.main()) ''' class Develop(Command): description = textwrap.dedent('''\ Setup a development environment for calibre. This allows you to run calibre directly from the source tree. Binaries will be installed in <prefix>/bin where <prefix> is the prefix of your python installation. This can be controlled via the --prefix option. ''') short_description = 'Setup a development environment for calibre' MODE = 0o755 sub_commands = ['build', 'resources', 'iso639', 'iso3166', 'gui',] def add_postinstall_options(self, parser): parser.add_option('--make-errors-fatal', action='store_true', default=False, dest='fatal_errors', help='If set die on post install errors.') parser.add_option('--no-postinstall', action='store_false', dest='postinstall', default=True, help='Don\'t run post install actions like creating MAN pages, setting'+ ' up desktop integration and so on') def add_options(self, parser): parser.add_option('--prefix', help='Binaries will be installed in <prefix>/bin') parser.add_option('--system-plugins-location', help='Path to a directory from which the installed calibre will load plugins') self.add_postinstall_options(parser) def consolidate_paths(self): opts = self.opts if not opts.prefix: opts.prefix = sys.prefix for x in ('prefix', 'libdir', 'bindir', 'sharedir', 'staging_root', 'staging_libdir', 'staging_bindir', 'staging_sharedir'): o = getattr(opts, x, None) if o: setattr(opts, x, os.path.abspath(o)) self.libdir = getattr(opts, 'libdir', None) if self.libdir is None: self.libdir = self.j(opts.prefix, 'lib') self.bindir = getattr(opts, 'bindir', None) if self.bindir is None: self.bindir = self.j(opts.prefix, 'bin') self.sharedir = getattr(opts, 'sharedir', None) if self.sharedir is None: self.sharedir = self.j(opts.prefix, 'share') if not getattr(opts, 'staging_root', None): opts.staging_root = opts.prefix self.staging_libdir = getattr(opts, 'staging_libdir', None) if self.staging_libdir is None: self.staging_libdir = opts.staging_libdir = self.j(opts.staging_root, 'lib') self.staging_bindir = getattr(opts, 'staging_bindir', None) if self.staging_bindir is None: self.staging_bindir = opts.staging_bindir = self.j(opts.staging_root, 'bin') self.staging_sharedir = getattr(opts, 'staging_sharedir', None) if self.staging_sharedir is None: self.staging_sharedir = opts.staging_sharedir = self.j(opts.staging_root, 'share') self.staging_libdir = opts.staging_libdir = self.j(self.staging_libdir, 'calibre') self.staging_sharedir = opts.staging_sharedir = self.j(self.staging_sharedir, 'calibre') self.system_plugins_loc = opts.system_plugins_location if self.__class__.__name__ == 'Develop': self.libdir = self.SRC self.sharedir = self.RESOURCES else: self.libdir = self.j(self.libdir, 'calibre') self.sharedir = self.j(self.sharedir, 'calibre') self.info('INSTALL paths:') self.info('\tLIB:', self.staging_libdir) self.info('\tSHARE:', self.staging_sharedir) def pre_sub_commands(self, opts): if not (islinux or isbsd or ishaiku): self.info('\nSetting up a source based development environment is only ' 'supported on linux. On other platforms, see the User Manual' ' for help with setting up a development environment.') raise SystemExit(1) if os.geteuid() == 0: # We drop privileges for security, regaining them when installing # files. Also ensures that any config files created as a side # effect of the build process are not owned by root. self.drop_privileges() # Ensure any config files created as a side effect of importing calibre # during the build process are in /tmp os.environ['CALIBRE_CONFIG_DIRECTORY'] = os.environ.get('CALIBRE_CONFIG_DIRECTORY', '/tmp/calibre-install-config') def run(self, opts): self.manifest = [] self.opts = opts self.regain_privileges() self.consolidate_paths() self.install_files() self.write_templates() self.install_env_module() self.run_postinstall() self.success() def install_env_module(self): import sysconfig libdir = os.path.join( self.opts.staging_root, sysconfig.get_config_var('PLATLIBDIR') or 'lib', os.path.basename(sysconfig.get_config_var('DESTLIB') or sysconfig.get_config_var('LIBDEST') or f'python{sysconfig.get_python_version()}'), 'site-packages') try: if not os.path.exists(libdir): os.makedirs(libdir) except OSError: self.warn('Cannot install calibre environment module to: '+libdir) else: path = os.path.join(libdir, 'init_calibre.py') self.info('Installing calibre environment module: '+path) with open(path, 'wb') as f: f.write(HEADER.format(**self.template_args()).encode('utf-8')) self.manifest.append(path) def install_files(self): pass def run_postinstall(self): if self.opts.postinstall: from calibre.linux import PostInstall PostInstall(self.opts, info=self.info, warn=self.warn, manifest=self.manifest) def success(self): self.info('\nDevelopment environment successfully setup') def write_templates(self): for typ in ('console', 'gui'): for name, mod, func in zip(basenames[typ], modules[typ], functions[typ]): self.write_template(name, mod, func) def template_args(self): return { 'py_major_version': sys.version_info.major, 'path':self.libdir, 'resources':self.sharedir, 'executables':self.bindir, 'extensions':self.j(self.libdir, 'calibre', 'plugins'), 'system_plugins_loc': self.system_plugins_loc, } def write_template(self, name, mod, func): template = COMPLETE_TEMPLATE if name == 'calibre-complete' else TEMPLATE args = self.template_args() args['module'] = mod args['func'] = func script = template.format(**args) path = self.j(self.staging_bindir, name) if not os.path.exists(self.staging_bindir): os.makedirs(self.staging_bindir) self.info('Installing binary:', path) if os.path.lexists(path) and not os.path.exists(path): os.remove(path) with open(path, 'wb') as f: f.write(script.encode('utf-8')) os.chmod(path, self.MODE) self.manifest.append(path) class Install(Develop): description = textwrap.dedent('''\ Install calibre to your system. By default, calibre is installed to <prefix>/bin, <prefix>/lib/calibre, <prefix>/share/calibre. These can all be controlled via options. The default <prefix> is the prefix of your python installation. The .desktop, .mime and icon files are installed using XDG. The location they are installed to can be controlled by setting the environment variables: XDG_DATA_DIRS=/usr/share equivalent XDG_UTILS_INSTALL_MODE=system For staged installs this will be automatically set to: <staging_root>/share ''') short_description = 'Install calibre from source' sub_commands = ['build', 'gui'] def add_options(self, parser): parser.add_option('--prefix', help='Installation prefix.') parser.add_option('--libdir', help='Where to put calibre library files. Default is <prefix>/lib') parser.add_option('--bindir', help='Where to put the calibre binaries. Default is <prefix>/bin') parser.add_option('--sharedir', help='Where to put the calibre data files. Default is <prefix>/share') parser.add_option('--staging-root', '--root', default=None, help=('Use a different installation root (mainly for packaging).' ' The prefix option controls the paths written into ' 'the launcher scripts. This option controls the prefix ' 'to which the install will actually copy files. By default ' 'it is set to the value of --prefix.')) parser.add_option('--staging-libdir', help='Where to put calibre library files. Default is <root>/lib') parser.add_option('--staging-bindir', help='Where to put the calibre binaries. Default is <root>/bin') parser.add_option('--staging-sharedir', help='Where to put the calibre data files. Default is <root>/share') parser.add_option('--system-plugins-location', help='Path to a directory from which the installed calibre will load plugins') self.add_postinstall_options(parser) def install_files(self): dest = self.staging_libdir if os.path.exists(dest): shutil.rmtree(dest) self.info('Installing code to', dest) self.manifest.append(dest) for x in os.walk(self.SRC): reldir = os.path.relpath(x[0], self.SRC) destdir = os.path.join(dest, reldir) for f in x[-1]: if os.path.splitext(f)[1] in ('.py', '.so'): if not os.path.exists(destdir): os.makedirs(destdir) shutil.copy2(self.j(x[0], f), destdir) dest = self.staging_sharedir if os.path.exists(dest): shutil.rmtree(dest) self.info('Installing resources to', dest) shutil.copytree(self.RESOURCES, dest, symlinks=True) self.manifest.append(dest) def success(self): self.info('\n\ncalibre successfully installed. You can start' ' it by running the command calibre') class Sdist(Command): description = 'Create a source distribution' DEST = os.path.join('dist', '%s-%s.tar.xz'%(__appname__, __version__)) def run(self, opts): if not self.e(self.d(self.DEST)): os.makedirs(self.d(self.DEST)) tdir = tempfile.mkdtemp() atexit.register(shutil.rmtree, tdir) tdir = self.j(tdir, 'calibre-%s' % __version__) self.info('\tRunning git export...') os.mkdir(tdir) subprocess.check_call('git archive HEAD | tar -x -C ' + tdir, shell=True) for x in open('.gitignore').readlines(): if not x.startswith('/resources/'): continue x = x[1:] p = x.strip().replace('/', os.sep) for p in glob.glob(p): d = self.j(tdir, os.path.dirname(p)) if not self.e(d): os.makedirs(d) if os.path.isdir(p): shutil.copytree(p, self.j(tdir, p)) else: shutil.copy2(p, d) for x in os.walk(os.path.join(self.SRC, 'calibre')): for f in x[-1]: if not f.endswith('_ui.py'): continue f = os.path.join(x[0], f) f = os.path.relpath(f) dest = os.path.join(tdir, self.d(f)) shutil.copy2(f, dest) tbase = self.j(self.d(self.SRC), 'translations') for x in ('iso_639', 'calibre'): destdir = self.j(tdir, 'translations', x) if not os.path.exists(destdir): os.makedirs(destdir) for y in glob.glob(self.j(tbase, x, '*.po')) + glob.glob(self.j(tbase, x, '*.pot')): dest = self.j(destdir, self.b(y)) if not os.path.exists(dest): shutil.copy2(y, dest) shutil.copytree(self.j(tbase, 'manual'), self.j(tdir, 'translations', 'manual')) self.add_man_pages(self.j(tdir, 'man-pages')) self.info('\tCreating tarfile...') dest = self.DEST.rpartition('.')[0] shutil.rmtree(os.path.join(tdir, '.github')) subprocess.check_call(['tar', '--mtime=now', '-cf', self.a(dest), 'calibre-%s' % __version__], cwd=self.d(tdir)) self.info('\tCompressing tarfile...') if os.path.exists(self.a(self.DEST)): os.remove(self.a(self.DEST)) subprocess.check_call(['xz', '-9', self.a(dest)]) def add_man_pages(self, dest): from setup.commands import man_pages man_pages.build_man_pages(dest) def clean(self): if os.path.exists(self.DEST): os.remove(self.DEST) class Bootstrap(Command): description = 'Bootstrap a fresh checkout of calibre from git to a state where it can be installed. Requires various development tools/libraries/headers' TRANSLATIONS_REPO = 'kovidgoyal/calibre-translations' sub_commands = 'build iso639 iso3166 translations gui resources cacerts recent_uas'.split() def add_options(self, parser): parser.add_option('--ephemeral', default=False, action='store_true', help='Do not download all history for the translations. Speeds up first time download but subsequent downloads will be slower.') parser.add_option('--path-to-translations', help='Path to existing out-of-tree translations checkout. Use this to avoid downloading translations at all.') def pre_sub_commands(self, opts): tdir = self.j(self.d(self.SRC), 'translations') clone_cmd = [ 'git', 'clone', f'https://github.com/{self.TRANSLATIONS_REPO}.git', 'translations'] if opts.path_to_translations: if os.path.exists(tdir): shutil.rmtree(tdir) shutil.copytree(opts.path_to_translations, tdir) # Change permissions for the top-level folder os.chmod(tdir, 0o755) for root, dirs, files in os.walk(tdir): # set perms on sub-directories for momo in dirs: os.chmod(os.path.join(root, momo), 0o755) # set perms on files for momo in files: os.chmod(os.path.join(root, momo), 0o644) elif opts.ephemeral: if os.path.exists(tdir): shutil.rmtree(tdir) st = time.time() clone_cmd.insert(2, '--depth=1') subprocess.check_call(clone_cmd, cwd=self.d(self.SRC)) print('Downloaded translations in %d seconds' % int(time.time() - st)) else: if os.path.exists(tdir): subprocess.check_call(['git', 'pull'], cwd=tdir) else: subprocess.check_call(clone_cmd, cwd=self.d(self.SRC)) def run(self, opts): self.info('\n\nAll done! You should now be able to run "%s setup.py install" to install calibre' % sys.executable)
16,611
Python
.py
342
38.070175
157
0.607698
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,377
commands.py
kovidgoyal_calibre/setup/commands.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' __all__ = [ 'pot', 'translations', 'get_translations', 'iso_data', 'iso639', 'iso3166', 'build', 'mathjax', 'man_pages', 'gui', 'git_version', 'develop', 'install', 'kakasi', 'rapydscript', 'cacerts', 'recent_uas', 'resources', 'check', 'test', 'test_rs', 'upgrade_source_code', 'sdist', 'bootstrap', 'extdev', 'manual', 'tag_release', 'upload_to_server', 'upload_installers', 'upload_user_manual', 'upload_demo', 'reupload', 'stage1', 'stage2', 'stage3', 'stage4', 'stage5', 'publish', 'publish_betas', 'publish_preview', 'linux', 'linux64', 'linuxarm64', 'win', 'win64', 'osx', 'build_dep', 'export_packages', 'hyphenation', 'piper_voices', 'liberation_fonts', 'stylelint', 'xwin', ] from setup.installers import OSX, BuildDep, ExportPackages, ExtDev, Linux, Linux64, LinuxArm64, Win, Win64 linux, linux64, linuxarm64 = Linux(), Linux64(), LinuxArm64() win, win64 = Win(), Win64() osx = OSX() extdev = ExtDev() build_dep = BuildDep() export_packages = ExportPackages() from setup.iso_codes import iso_data from setup.translations import ISO639, ISO3166, POT, GetTranslations, Translations pot = POT() translations = Translations() get_translations = GetTranslations() iso639 = ISO639() iso3166 = ISO3166() from setup.csslint import CSSLint stylelint = CSSLint() from setup.build import Build build = Build() from setup.mathjax import MathJax mathjax = MathJax() from setup.hyphenation import Hyphenation hyphenation = Hyphenation() from setup.piper import PiperVoices piper_voices = PiperVoices() from setup.liberation import LiberationFonts liberation_fonts = LiberationFonts() from setup.git_version import GitVersion git_version = GitVersion() from setup.install import Bootstrap, Develop, Install, Sdist develop = Develop() install = Install() sdist = Sdist() bootstrap = Bootstrap() from setup.gui import GUI gui = GUI() from setup.check import Check, UpgradeSourceCode check = Check() upgrade_source_code = UpgradeSourceCode() from setup.test import Test, TestRS test = Test() test_rs = TestRS() from setup.resources import CACerts, Kakasi, RapydScript, RecentUAs, Resources resources = Resources() kakasi = Kakasi() cacerts = CACerts() recent_uas = RecentUAs() rapydscript = RapydScript() from setup.publish import ManPages, Manual, Publish, PublishBetas, PublishPreview, Stage1, Stage2, Stage3, Stage4, Stage5, TagRelease manual = Manual() tag_release = TagRelease() stage1 = Stage1() stage2 = Stage2() stage3 = Stage3() stage4 = Stage4() stage5 = Stage5() publish = Publish() publish_betas = PublishBetas() publish_preview = PublishPreview() man_pages = ManPages() from setup.upload import ReUpload, UploadDemo, UploadInstallers, UploadToServer, UploadUserManual upload_user_manual = UploadUserManual() upload_demo = UploadDemo() upload_to_server = UploadToServer() upload_installers = UploadInstallers() reupload = ReUpload() from setup.xwin import XWin xwin = XWin() commands = {} for x in __all__: commands[x] = locals()[x] command_names = dict(zip(commands.values(), commands.keys()))
3,248
Python
.py
92
33.173913
133
0.742619
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,378
init_env.py
kovidgoyal_calibre/bypy/init_env.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import json import os import re import subprocess import sys from bypy.constants import LIBDIR, PREFIX, PYTHON, build_dir, islinux, ismacos, worker_env from bypy.constants import SRC as CALIBRE_DIR from bypy.utils import run_shell dlls = [ 'Core', 'Concurrent', 'Gui', 'Network', # 'NetworkAuth', 'PrintSupport', 'WebChannel', # 'WebSockets', # 'WebView', 'Positioning', 'Sensors', 'SpatialAudio', 'Sql', 'Svg', 'TextToSpeech', 'WebChannel', 'WebEngineCore', 'WebEngineWidgets', 'Widgets', 'Multimedia', 'MultimediaWidgets', 'OpenGL', 'OpenGLWidgets', 'Quick', 'QuickWidgets', 'Qml', 'QmlModels', 'Xml', # 'XmlPatterns', ] if islinux: dlls += ['XcbQpa', 'WaylandClient', 'WaylandEglClientHwIntegration', 'DBus'] elif ismacos: dlls += ['DBus'] QT_MAJOR = 6 QT_DLLS = frozenset( f'Qt{QT_MAJOR}' + x for x in dlls ) QT_PLUGINS = [ 'imageformats', 'iconengines', 'tls', 'multimedia', 'texttospeech', # 'mediaservice', 'platforms', # 'playlistformats', 'sqldrivers', # 'webview', # 'audio', 'printsupport', 'bearer', 'position', ] if islinux: QT_PLUGINS += [ 'egldeviceintegrations', 'platforminputcontexts', 'platformthemes', 'wayland-decoration-client', 'wayland-graphics-integration-client', 'wayland-shell-integration', 'xcbglintegrations', ] else: QT_PLUGINS.append('styles') PYQT_MODULES = ( 'Qt', 'QtCore', 'QtGui', 'QtNetwork', 'QtMultimedia', 'QtMultimediaWidgets', 'QtTextToSpeech', 'QtPrintSupport', 'QtSensors', 'QtSvg', 'QtWidgets', 'QtOpenGL', 'QtOpenGLWidgets', 'QtWebEngine', 'QtWebEngineCore', 'QtWebEngineWidgets', 'QtWebChannel', ) del dlls def read_cal_file(name): with open(os.path.join(CALIBRE_DIR, 'src', 'calibre', name), 'rb') as f: return f.read().decode('utf-8') def initialize_constants(): calibre_constants = {} src = read_cal_file('constants.py') nv = re.search(r'numeric_version\s+=\s+\((\d+), (\d+), (\d+)\)', src) calibre_constants['version' ] = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3)) calibre_constants['appname'] = re.search( r'__appname__\s+=\s+(u{0,1})[\'"]([^\'"]+)[\'"]', src ).group(2) epsrc = re.compile(r'entry_points = (\{.*?\})', re.DOTALL).search(read_cal_file('linux.py')).group(1) entry_points = eval(epsrc, {'__appname__': calibre_constants['appname']}) def e2b(ep): return re.search(r'\s*(.*?)\s*=', ep).group(1).strip() def e2s(ep, base='src'): return ( base + os.path.sep + re.search(r'.*=\s*(.*?):', ep).group(1).replace('.', '/') + '.py' ).strip() def e2m(ep): return re.search(r'.*=\s*(.*?)\s*:', ep).group(1).strip() def e2f(ep): return ep[ep.rindex(':') + 1:].strip() calibre_constants['basenames'] = basenames = {} calibre_constants['functions'] = functions = {} calibre_constants['modules'] = modules = {} calibre_constants['scripts'] = scripts = {} for x in ('console', 'gui'): y = x + '_scripts' basenames[x] = list(map(e2b, entry_points[y])) functions[x] = list(map(e2f, entry_points[y])) modules[x] = list(map(e2m, entry_points[y])) scripts[x] = list(map(e2s, entry_points[y])) src = read_cal_file('ebooks/__init__.py') be = re.search( r'^BOOK_EXTENSIONS\s*=\s*(\[.+?\])', src, flags=re.DOTALL | re.MULTILINE ).group(1) calibre_constants['book_extensions'] = json.loads(be.replace("'", '"')) return calibre_constants def run(*args, **extra_env): env = os.environ.copy() env.update(worker_env) env.update(extra_env) env['SW'] = PREFIX env['LD_LIBRARY_PATH'] = LIBDIR env['SIP_BIN'] = os.path.join(PREFIX, 'bin', 'sip') env['QMAKE'] = os.path.join(PREFIX, 'qt', 'bin', 'qmake') return subprocess.call(list(args), env=env, cwd=CALIBRE_DIR) def build_c_extensions(ext_dir, args): bdir = os.path.join(build_dir(), 'calibre-extension-objects') cmd = [ PYTHON, 'setup.py', 'build', '--output-dir', ext_dir, '--build-dir', bdir, ] if args.build_only: cmd.extend(('--only', args.build_only)) if run(*cmd, COMPILER_CWD=bdir) != 0: print('Building of calibre C extensions failed', file=sys.stderr) os.chdir(CALIBRE_DIR) run_shell() raise SystemExit('Building of calibre C extensions failed') return ext_dir def run_tests(path_to_calibre_debug, cwd_on_failure): ret = run(path_to_calibre_debug, '--test-build') if ret != 0: os.chdir(cwd_on_failure) print( 'running calibre build tests failed with return code:', ret, 'and exe:', path_to_calibre_debug, file=sys.stderr) run_shell() raise SystemExit('running calibre build tests failed') if __name__ == 'program': calibre_constants = initialize_constants()
5,246
Python
.py
169
25.526627
124
0.600673
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,379
run-python.h
kovidgoyal_calibre/bypy/run-python.h
/* * Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net> * * Distributed under terms of the GPL3 license. */ #pragma once #define PY_SSIZE_T_CLEAN #include <stdio.h> #include <stdbool.h> #include <time.h> #include <stdlib.h> #include <stdarg.h> #ifdef _WIN32 #include <string.h> #define PATH_MAX MAX_PATH #else #include <strings.h> #endif #include <errno.h> #include <Python.h> #ifdef __APPLE__ #include <os/log.h> #endif #include <bypy-freeze.h> static void pre_initialize_interpreter(bool is_gui_app) { bypy_pre_initialize_interpreter(is_gui_app); } #define decode_char_buf(src, dest) { \ size_t tsz; \ wchar_t* t__ = Py_DecodeLocale(src, &tsz); \ if (!t__) fatal("Failed to decode path: %s", src); \ if (tsz > sizeof(dest) - 1) tsz = sizeof(dest) - 1; \ memcpy(dest, t__, tsz * sizeof(wchar_t)); \ dest[tsz] = 0; \ PyMem_RawFree(t__); \ } #define MAX_SYS_PATHS 3 typedef struct { int argc; wchar_t exe_path[PATH_MAX], python_home_path[PATH_MAX], python_lib_path[PATH_MAX]; wchar_t extensions_path[PATH_MAX], resources_path[PATH_MAX], executables_path[PATH_MAX]; #ifdef __APPLE__ wchar_t bundle_resource_path[PATH_MAX], frameworks_path[PATH_MAX]; #elif defined(_WIN32) wchar_t app_dir[PATH_MAX]; #endif const wchar_t *basename, *module, *function; #ifdef _WIN32 wchar_t* const *argv; #else char* const *argv; #endif } InterpreterData; static InterpreterData interpreter_data = {0}; static void run_interpreter() { bypy_initialize_interpreter( interpreter_data.exe_path, interpreter_data.python_home_path, L"site", interpreter_data.extensions_path, interpreter_data.argc, interpreter_data.argv); set_sys_bool("gui_app", use_os_log); set_sys_bool("frozen", true); set_sys_string("calibre_basename", interpreter_data.basename); set_sys_string("calibre_module", interpreter_data.module); set_sys_string("calibre_function", interpreter_data.function); set_sys_string("extensions_location", interpreter_data.extensions_path); set_sys_string("resources_location", interpreter_data.resources_path); set_sys_string("executables_location", interpreter_data.executables_path); #ifdef __APPLE__ set_sys_string("resourcepath", interpreter_data.bundle_resource_path); set_sys_string("frameworks_dir", interpreter_data.frameworks_path); set_sys_bool("new_app_bundle", true); #elif defined(_WIN32) set_sys_string("app_dir", interpreter_data.app_dir); set_sys_bool("new_app_layout", true); #else set_sys_string("frozen_path", interpreter_data.executables_path); #endif int ret = bypy_run_interpreter(); exit(ret); }
2,641
Python
.py
81
29.962963
116
0.717366
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,380
sign.py
kovidgoyal_calibre/bypy/macos/sign.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import os import plistlib from glob import glob from bypy.macos_sign import codesign, create_entitlements_file, make_certificate_useable, notarize_app, verify_signature from bypy.utils import current_dir entitlements = { # MAP_JIT is used by libpcre which is bundled with Qt 'com.apple.security.cs.allow-jit': True, # v8 and therefore WebEngine need this as they dont use MAP_JIT 'com.apple.security.cs.allow-unsigned-executable-memory': True, # calibre itself does not use DYLD env vars, but dont know about its # dependencies. 'com.apple.security.cs.allow-dyld-environment-variables': True, # Allow loading of unsigned plugins or frameworks # 'com.apple.security.cs.disable-library-validation': True, } def files_in(folder): for record in os.walk(folder): for f in record[-1]: yield os.path.join(record[0], f) def expand_dirs(items, exclude=lambda x: x.endswith('.so')): items = set(items) dirs = set(x for x in items if os.path.isdir(x)) items.difference_update(dirs) for x in dirs: items.update({y for y in files_in(x) if not exclude(y)}) return items def get_executable(info_path): with open(info_path, 'rb') as f: return plistlib.load(f)['CFBundleExecutable'] def find_sub_apps(contents_dir='.'): for app in glob(os.path.join(contents_dir, '*.app')): cdir = os.path.join(app, 'Contents') for sapp in find_sub_apps(cdir): yield sapp yield app def sign_MacOS(contents_dir='.'): # Sign everything in MacOS except the main executable # which will be signed automatically by codesign when # signing the app bundles with current_dir(os.path.join(contents_dir, 'MacOS')): exe = get_executable('../Info.plist') items = {x for x in os.listdir('.') if x != exe and not os.path.islink(x)} if items: codesign(items) def do_sign_app(appdir): appdir = os.path.abspath(appdir) with current_dir(os.path.join(appdir, 'Contents')): sign_MacOS() # Sign the sub application bundles sub_apps = list(find_sub_apps()) sub_apps.append('Frameworks/QtWebEngineCore.framework/Versions/Current/Helpers/QtWebEngineProcess.app') for sa in sub_apps: sign_MacOS(os.path.join(sa, 'Contents')) codesign(sub_apps) # Sign all .so files so_files = {x for x in files_in('.') if x.endswith('.so')} codesign(so_files) # Sign everything in PlugIns with current_dir('PlugIns'): items = set(os.listdir('.')) codesign(expand_dirs(items)) # Sign everything else in Frameworks with current_dir('Frameworks'): fw = set(glob('*.framework')) codesign(fw) items = set(os.listdir('.')) - fw codesign(expand_dirs(items)) # Now sign the main app codesign(appdir) verify_signature(appdir) return 0 def sign_app(appdir, notarize): create_entitlements_file(entitlements) with make_certificate_useable(): do_sign_app(appdir) if notarize: notarize_app(appdir)
3,291
Python
.py
81
33.901235
120
0.662272
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,381
__main__.py
kovidgoyal_calibre/bypy/macos/__main__.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import errno import glob import json import operator import os import plistlib import runpy import shutil import stat import subprocess import sys import tempfile import time import zipfile from functools import partial, reduce from itertools import repeat from bypy.constants import OUTPUT_DIR, PREFIX, PYTHON, python_major_minor_version from bypy.constants import SRC as CALIBRE_DIR from bypy.freeze import extract_extension_modules, fix_pycryptodome, freeze_python, is_package_dir, path_to_freeze_dir from bypy.pkgs.piper import copy_piper_dir from bypy.utils import current_dir, get_arches_in_binary, mkdtemp, py_compile, timeit, walk abspath, join, basename, dirname = os.path.abspath, os.path.join, os.path.basename, os.path.dirname iv = globals()['init_env'] calibre_constants = iv['calibre_constants'] QT_DLLS, QT_PLUGINS, PYQT_MODULES = iv['QT_DLLS'], iv['QT_PLUGINS'], iv['PYQT_MODULES'] QT_MAJOR = iv['QT_MAJOR'] py_ver = '.'.join(map(str, python_major_minor_version())) sign_app = runpy.run_path(join(dirname(abspath(__file__)), 'sign.py'))['sign_app'] QT_PREFIX = join(PREFIX, 'qt') QT_FRAMEWORKS = [x.replace(f'{QT_MAJOR}', '') for x in QT_DLLS] ENV = dict( FONTCONFIG_PATH='@executable_path/../Resources/fonts', FONTCONFIG_FILE='@executable_path/../Resources/fonts/fonts.conf', SSL_CERT_FILE='@executable_path/../Resources/resources/mozilla-ca-certs.pem', OPENSSL_ENGINES='@executable_path/../Frameworks/engines-3', OPENSSL_MODULES='@executable_path/../Frameworks/ossl-modules', ) APPNAME, VERSION = calibre_constants['appname'], calibre_constants['version'] basenames, main_modules, main_functions = calibre_constants['basenames'], calibre_constants['modules'], calibre_constants['functions'] ARCH_FLAGS = '-arch x86_64 -arch arm64'.split() EXPECTED_ARCHES = {'x86_64', 'arm64'} MINIMUM_SYSTEM_VERSION = '13.0.0' def compile_launcher_lib(contents_dir, base, pyver, inc_dir): print('\tCompiling calibre_launcher.dylib') env, env_vals = [], [] for key, val in ENV.items(): env.append(f'"{key}"'), env_vals.append(f'"{val}"') env = ','.join(env) env_vals = ','.join(env_vals) dest = join(contents_dir, 'Frameworks', 'calibre-launcher.dylib') src = join(base, 'util.c') cmd = gcc + ARCH_FLAGS + CFLAGS + '-Wall -dynamiclib -std=gnu99'.split() + [src] + \ ['-I' + base] + '-DPY_VERSION_MAJOR={} -DPY_VERSION_MINOR={}'.format(*pyver.split('.')).split() + \ [f'-I{path_to_freeze_dir()}', f'-I{inc_dir}'] + \ [f'-DENV_VARS={env}', f'-DENV_VAR_VALS={env_vals}'] + \ ['-I%s/python/Python.framework/Versions/Current/Headers' % PREFIX] + \ '-current_version 1.0 -compatibility_version 1.0'.split() + \ '-fvisibility=hidden -o'.split() + [dest] # We need libxml2.dylib linked because Apple's system frameworks link # against a system version. And libxml2 uses global variables so we get # crashes if the system libxml2 is loaded. Loading plugins like the Qt # ones or usbobserver causes it to be loaded. So pre-load our libxml2 # to avoid it. cmd += ['-L', f'{PREFIX}/lib', '-l', 'xml2', '-l', 'xslt',] + \ ['-install_name', '@executable_path/../Frameworks/' + os.path.basename(dest)] + \ [('-F%s/python' % PREFIX), '-framework', 'Python', '-framework', 'CoreFoundation', '-headerpad_max_install_names'] # print('\t'+' '.join(cmd)) sys.stdout.flush() subprocess.check_call(cmd) return dest gcc = os.environ.get('CC', 'clang').split() CFLAGS = os.environ.get('CFLAGS', '-Os').split() def compile_launchers(contents_dir, inc_dir, xprograms, pyver): base = dirname(abspath(__file__)) lib = compile_launcher_lib(contents_dir, base, pyver, inc_dir) src = join(base, 'launcher.c') programs = [lib] for program, x in xprograms.items(): module, func, ptype = x print('\tCompiling', program) out = join(contents_dir, 'MacOS', program) programs.append(out) is_gui = 'true' if ptype == 'gui' else 'false' cmd = gcc + ARCH_FLAGS + CFLAGS + [ '-Wall', f'-DPROGRAM=L"{program}"', f'-DMODULE=L"{module}"', f'-DFUNCTION=L"{func}"', f'-DIS_GUI={is_gui}', '-I' + base, src, lib, '-o', out, '-headerpad_max_install_names', ] # print('\t'+' '.join(cmd)) sys.stdout.flush() subprocess.check_call(cmd) return programs def flipwritable(fn, mode=None): """ Flip the writability of a file and return the old mode. Returns None if the file is already writable. """ if os.access(fn, os.W_OK): return None old_mode = os.stat(fn).st_mode os.chmod(fn, stat.S_IWRITE | old_mode) return old_mode def check_universal(path): arches = get_arches_in_binary(path) if arches != EXPECTED_ARCHES: raise SystemExit(f'The file {path} is not a universal binary, it only has arches: {", ".join(arches)}') STRIPCMD = ['/usr/bin/strip', '-x', '-S', '-'] def strip_files(files, argv_max=(256 * 1024)): """ Strip a list of files """ tostrip = [(fn, flipwritable(fn)) for fn in files if os.path.exists(fn)] while tostrip: cmd = list(STRIPCMD) flips = [] pathlen = reduce(operator.add, [len(s) + 1 for s in cmd]) while pathlen < argv_max: if not tostrip: break added, flip = tostrip.pop() pathlen += len(added) + 1 cmd.append(added) flips.append((added, flip)) else: cmd.pop() tostrip.append(flips.pop()) os.spawnv(os.P_WAIT, cmd[0], cmd) for args in flips: flipwritable(*args) def flush(func): def ff(*args, **kwargs): sys.stdout.flush() sys.stderr.flush() ret = func(*args, **kwargs) sys.stdout.flush() sys.stderr.flush() return ret return ff class Freeze: FID = '@executable_path/../Frameworks' def __init__(self, build_dir, ext_dir, inc_dir, test_runner, test_launchers=False, dont_strip=False, sign_installers=False, notarize=False): self.build_dir = os.path.realpath(build_dir) self.inc_dir = os.path.realpath(inc_dir) self.sign_installers = sign_installers self.notarize = notarize self.ext_dir = os.path.realpath(ext_dir) self.test_runner = test_runner self.dont_strip = dont_strip self.contents_dir = join(self.build_dir, 'Contents') self.resources_dir = join(self.contents_dir, 'Resources') self.frameworks_dir = join(self.contents_dir, 'Frameworks') self.exe_dir = join(self.contents_dir, 'MacOS') self.helpers_dir = join(self.contents_dir, 'utils.app', 'Contents', 'MacOS') self.site_packages = join(self.resources_dir, 'Python', 'site-packages') self.to_strip = [] self.warnings = [] self.run(test_launchers) def run(self, test_launchers): ret = 0 self.ext_map = {} if not test_launchers: if os.path.exists(self.build_dir): shutil.rmtree(self.build_dir) os.makedirs(self.build_dir) self.create_skeleton() self.create_plist() self.add_python_framework() self.add_site_packages() self.add_stdlib() self.add_qt_frameworks() self.add_calibre_plugins() self.add_podofo() self.add_poppler() self.add_imaging_libs() self.add_fontconfig() self.add_misc_libraries() self.add_resources() self.copy_site() self.compile_py_modules() self.create_exe() if not test_launchers and not self.dont_strip: self.strip_files() if not test_launchers: self.create_gui_apps() self.run_tests() ret = self.makedmg(self.build_dir, APPNAME + '-' + VERSION) return ret @flush def run_tests(self): self.test_runner(join(self.contents_dir, 'MacOS', 'calibre-debug'), self.contents_dir) @flush def add_resources(self): shutil.copytree('resources', join(self.resources_dir, 'resources')) @flush def strip_files(self): print('\nStripping files...') strip_files(self.to_strip) @flush def create_exe(self): print('\nCreating launchers') programs = {} progs = [] for x in ('console', 'gui'): progs += list(zip(basenames[x], main_modules[x], main_functions[x], repeat(x))) for program, module, func, ptype in progs: programs[program] = (module, func, ptype) programs = compile_launchers(self.contents_dir, self.inc_dir, programs, py_ver) for out in programs: self.fix_dependencies_in_lib(out) @flush def set_id(self, path_to_lib, new_id): old_mode = flipwritable(path_to_lib) subprocess.check_call(['install_name_tool', '-id', new_id, path_to_lib]) if old_mode is not None: flipwritable(path_to_lib, old_mode) @flush def get_dependencies(self, path_to_lib): install_name = subprocess.check_output(['otool', '-D', path_to_lib]).splitlines()[-1].strip() raw = subprocess.check_output(['otool', '-L', path_to_lib]).decode('utf-8') for line in raw.splitlines(): if 'compatibility' not in line or line.strip().endswith(':'): continue idx = line.find('(') path = line[:idx].strip() yield path, path == install_name @flush def get_local_dependencies(self, path_to_lib): for x, is_id in self.get_dependencies(path_to_lib): if x in ('libunrar.dylib', 'libstemmer.0.dylib', 'libstemmer.dylib', 'libjbig.2.1.dylib') and not is_id: yield x, x, is_id else: for y in ('@rpath/', PREFIX + '/lib/', PREFIX + '/python/Python.framework/', PREFIX + '/ffmpeg/lib/'): if x.startswith(y): if y == PREFIX + '/python/Python.framework/': y = PREFIX + '/python/' yield x, x[len(y):], is_id break @flush def change_dep(self, old_dep, new_dep, is_id, path_to_lib): cmd = ['-id', new_dep] if is_id else ['-change', old_dep, new_dep] subprocess.check_call(['install_name_tool'] + cmd + [path_to_lib]) @flush def fix_dependencies_in_lib(self, path_to_lib): check_universal(path_to_lib) self.to_strip.append(path_to_lib) old_mode = flipwritable(path_to_lib) for dep, bname, is_id in self.get_local_dependencies(path_to_lib): ndep = self.FID + '/' + bname self.change_dep(dep, ndep, is_id, path_to_lib) ldeps = list(self.get_local_dependencies(path_to_lib)) if ldeps: print('\nFailed to fix dependencies in', path_to_lib) print('Remaining local dependencies:', ldeps) raise SystemExit(1) if old_mode is not None: flipwritable(path_to_lib, old_mode) @flush def add_python_framework(self): print('\nAdding Python framework') src = join(PREFIX + '/python', 'Python.framework') x = join(self.frameworks_dir, 'Python.framework') curr = os.path.realpath(join(src, 'Versions', 'Current')) currd = join(x, 'Versions', basename(curr)) rd = join(currd, 'Resources') os.makedirs(rd) shutil.copy2(join(curr, 'Resources', 'Info.plist'), rd) shutil.copy2(join(curr, 'Python'), currd) self.set_id(join(currd, 'Python'), self.FID + '/Python.framework/Versions/%s/Python' % basename(curr)) # The following is needed for codesign in OS X >= 10.9.5 with current_dir(x): os.symlink(basename(curr), 'Versions/Current') for y in ('Python', 'Resources'): os.symlink('Versions/Current/%s' % y, y) @flush def add_qt_frameworks(self): print('\nAdding Qt Frameworks') # First add FFMPEG for x in os.listdir(join(PREFIX, 'ffmpeg', 'lib')): if x.endswith('.dylib') and x.count('.') == 2: src = join(PREFIX, 'ffmpeg', 'lib', x) shutil.copy2(src, self.frameworks_dir) dest = join(self.frameworks_dir, os.path.basename(src)) self.set_id(dest, self.FID + '/' + os.path.basename(src)) self.fix_dependencies_in_lib(dest) for f in QT_FRAMEWORKS: self.add_qt_framework(f) pdir = join(QT_PREFIX, 'plugins') ddir = join(self.contents_dir, 'PlugIns') os.mkdir(ddir) for x in QT_PLUGINS: shutil.copytree(join(pdir, x), join(ddir, x)) for l in glob.glob(join(ddir, '*/*.dylib')): self.fix_dependencies_in_lib(l) x = os.path.relpath(l, ddir) self.set_id(l, '@executable_path/' + x) webengine_process = os.path.realpath(join( self.frameworks_dir, 'QtWebEngineCore.framework/Versions/Current/Helpers/QtWebEngineProcess.app/Contents/MacOS/QtWebEngineProcess')) self.fix_dependencies_in_lib(webengine_process) cdir = dirname(dirname(webengine_process)) dest = join(cdir, 'Frameworks') os.symlink(os.path.relpath(self.frameworks_dir, cdir), dest) def add_qt_framework(self, f): libname = f f = f + '.framework' src = join(PREFIX, 'qt', 'lib', f) ignore = shutil.ignore_patterns('Headers', '*.h', 'Headers/*') dest = join(self.frameworks_dir, f) shutil.copytree(src, dest, symlinks=True, ignore=ignore) lib = os.path.realpath(join(dest, libname)) rpath = os.path.relpath(lib, self.frameworks_dir) self.set_id(lib, self.FID + '/' + rpath) self.fix_dependencies_in_lib(lib) # The following is needed for codesign in OS X >= 10.9.5 # The presence of the .prl file in the root of the framework causes # codesign to fail. with current_dir(dest): for x in os.listdir('.'): if x != 'Versions' and not os.path.islink(x): os.remove(x) @flush def create_skeleton(self): c = join(self.build_dir, 'Contents') for x in ('Frameworks', 'MacOS', 'Resources'): os.makedirs(join(c, x)) icons = glob.glob(join(CALIBRE_DIR, 'icons', 'icns', '*.iconset')) if not icons: raise SystemExit('Failed to find icns format icons') for x in icons: subprocess.check_call([ 'iconutil', '-c', 'icns', x, '-o', join( self.resources_dir, basename(x).partition('.')[0] + '.icns')]) for helpers in (self.helpers_dir,): os.makedirs(helpers) cdir = dirname(helpers) dest = join(cdir, 'Frameworks') src = self.frameworks_dir os.symlink(os.path.relpath(src, cdir), dest) dest = join(cdir, 'Resources') src = self.resources_dir os.symlink(os.path.relpath(src, cdir), dest) pl = dict( CFBundleDevelopmentRegion='English', CFBundleDisplayName=APPNAME + ' - utils', CFBundleName=APPNAME + '-utils', CFBundleIdentifier='com.calibre-ebook.utils', LSBackgroundOnly='1', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION, CFBundlePackageType='APPL', CFBundleSignature='????', CFBundleExecutable='pdftohtml', LSMinimumSystemVersion=MINIMUM_SYSTEM_VERSION, LSRequiresNativeExecution=True, NSAppleScriptEnabled=False, CFBundleIconFile='', ) with open(join(cdir, 'Info.plist'), 'wb') as p: plistlib.dump(pl, p) @flush def add_calibre_plugins(self): dest = join(self.frameworks_dir, 'plugins') os.mkdir(dest) print('Extracting extension modules from:', self.ext_dir, 'to', dest) self.ext_map = extract_extension_modules(self.ext_dir, dest) plugins = glob.glob(dest + '/*.so') if not plugins: raise SystemExit('No calibre plugins found in: ' + self.ext_dir) for f in plugins: self.fix_dependencies_in_lib(f) @flush def create_plist(self): BOOK_EXTENSIONS = calibre_constants['book_extensions'] env = dict(**ENV) env['CALIBRE_LAUNCHED_FROM_BUNDLE'] = '1' docs = [{ 'CFBundleTypeName': 'E-book', 'CFBundleTypeExtensions': list(BOOK_EXTENSIONS), 'CFBundleTypeIconFile': 'book.icns', 'CFBundleTypeRole': 'Viewer', }] url_handlers = [dict( CFBundleTypeRole='Viewer', CFBundleURLIconFile='calibre', CFBundleURLName='com.calibre-ebook.calibre-url', CFBundleURLSchemes=['calibre'] )] pl = dict( CFBundleDevelopmentRegion='English', CFBundleDisplayName=APPNAME, CFBundleName=APPNAME, CFBundleIdentifier='net.kovidgoyal.calibre', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION, CFBundlePackageType='APPL', CFBundleSignature='????', CFBundleExecutable='calibre', CFBundleDocumentTypes=docs, CFBundleURLTypes=url_handlers, LSMinimumSystemVersion=MINIMUM_SYSTEM_VERSION, LSRequiresNativeExecution=True, NSAppleScriptEnabled=False, NSSupportsAutomaticGraphicsSwitching=True, NSHumanReadableCopyright=time.strftime('Copyright %Y, Kovid Goyal'), CFBundleGetInfoString=('calibre, an E-book management ' 'application. Visit https://calibre-ebook.com for details.'), CFBundleIconFile='calibre.icns', NSHighResolutionCapable=True, LSApplicationCategoryType='public.app-category.productivity', LSEnvironment=env ) with open(join(self.contents_dir, 'Info.plist'), 'wb') as p: plistlib.dump(pl, p) @flush def install_dylib(self, path, set_id=True, dest=None): dest = dest or self.frameworks_dir os.makedirs(dest, exist_ok=True) shutil.copy2(path, dest) if set_id: self.set_id(join(dest, basename(path)), self.FID + '/' + basename(path)) self.fix_dependencies_in_lib(join(dest, basename(path))) @flush def add_podofo(self): print('\nAdding PoDoFo') pdf = join(PREFIX, 'lib', 'libpodofo.2.dylib') self.install_dylib(pdf) @flush def add_poppler(self): print('\nAdding poppler') for x in ('libopenjp2.7.dylib', 'libpoppler.130.dylib',): self.install_dylib(join(PREFIX, 'lib', x)) for x in ('pdftohtml', 'pdftoppm', 'pdfinfo', 'pdftotext'): self.install_dylib( join(PREFIX, 'bin', x), set_id=False, dest=self.helpers_dir) @flush def add_imaging_libs(self): print('\nAdding libjpeg, libpng, libwebp, optipng and mozjpeg') for x in ('jpeg.8', 'png16.16', 'webp.7', 'webpmux.3', 'webpdemux.2', 'sharpyuv.0'): self.install_dylib(join(PREFIX, 'lib', 'lib%s.dylib' % x)) for x in 'optipng', 'JxrDecApp', 'cwebp': self.install_dylib(join(PREFIX, 'bin', x), set_id=False, dest=self.helpers_dir) for x in ('jpegtran', 'cjpeg'): self.install_dylib( join(PREFIX, 'private', 'mozjpeg', 'bin', x), set_id=False, dest=self.helpers_dir) @flush def add_fontconfig(self): print('\nAdding fontconfig') for x in ('fontconfig.1', 'freetype.6', 'expat.1'): src = join(PREFIX, 'lib', 'lib' + x + '.dylib') self.install_dylib(src) dst = join(self.resources_dir, 'fonts') if os.path.exists(dst): shutil.rmtree(dst) src = join(PREFIX, 'etc', 'fonts') shutil.copytree(src, dst, symlinks=False) fc = join(dst, 'fonts.conf') with open(fc, 'rb') as f: raw = f.read().decode('utf-8') raw = raw.replace('<dir>/usr/share/fonts</dir>', '''\ <dir>/Library/Fonts</dir> <dir>/System/Library/Fonts</dir> <dir>/usr/X11R6/lib/X11/fonts</dir> <dir>/usr/share/fonts</dir> <dir>/var/root/Library/Fonts</dir> <dir>/usr/share/fonts</dir> ''') open(fc, 'wb').write(raw.encode('utf-8')) @flush def add_misc_libraries(self): def add_lib(src): x = os.path.basename(src) print('\nAdding', x) shutil.copy2(src, self.frameworks_dir) dest = join(self.frameworks_dir, x) self.set_id(dest, self.FID + '/' + x) self.fix_dependencies_in_lib(dest) for x in ( 'usb-1.0.0', 'mtp.9', 'chm.0', 'sqlite3.0', 'hunspell-1.7.0', 'icudata.73', 'icui18n.73', 'icuio.73', 'icuuc.73', 'hyphen.0', 'uchardet.0', 'stemmer.0', 'xslt.1', 'exslt.0', 'xml2.2', 'z.1', 'unrar', 'lzma.5', 'brotlicommon.1', 'brotlidec.1', 'brotlienc.1', 'zstd.1', 'jbig.2.1', 'tiff.6', 'crypto.3', 'ssl.3', 'iconv.2', # 'ltdl.7' ): x = 'lib%s.dylib' % x src = join(PREFIX, 'lib', x) add_lib(src) # OpenSSL modules and engines for x in ('ossl-modules', 'engines-3'): dest = join(self.frameworks_dir, x) shutil.copytree(join(PREFIX, 'lib', x), dest) for dylib in os.listdir(dest): if dylib.endswith('.dylib'): dylib = join(dest, dylib) self.set_id(dylib, self.FID + '/' + x + '/' + os.path.basename(dylib)) self.fix_dependencies_in_lib(dylib) # Piper TTS copy_piper_dir(PREFIX, self.frameworks_dir) @flush def add_site_packages(self): print('\nAdding site-packages') os.makedirs(self.site_packages) sys_path = json.loads(subprocess.check_output([ PYTHON, '-c', 'import sys, json; json.dump(sys.path, sys.stdout)'])) paths = reversed(tuple(map(abspath, [x for x in sys_path if x.startswith('/') and not x.startswith('/Library/')]))) upaths = [] for x in paths: if x not in upaths and (x.endswith('.egg') or x.endswith('/site-packages')): upaths.append(x) upaths.append(join(CALIBRE_DIR, 'src')) for x in upaths: print('\t', x) tdir = None try: if not os.path.isdir(x): zf = zipfile.ZipFile(x) tdir = tempfile.mkdtemp() zf.extractall(tdir) x = tdir self.add_modules_from_dir(x) self.add_packages_from_dir(x) finally: if tdir is not None: shutil.rmtree(tdir) fix_pycryptodome(self.site_packages) try: shutil.rmtree(join(self.site_packages, 'calibre', 'plugins')) except OSError as err: if err.errno != errno.ENOENT: raise sp = join(self.resources_dir, 'Python', 'site-packages') self.remove_bytecode(sp) @flush def add_modules_from_dir(self, src): for x in glob.glob(join(src, '*.py')) + glob.glob(join(src, '*.so')): dest = join(self.site_packages, os.path.basename(x)) shutil.copy2(x, dest) if x.endswith('.so'): self.fix_dependencies_in_lib(dest) @flush def add_packages_from_dir(self, src): for x in os.listdir(src): x = join(src, x) if os.path.isdir(x) and is_package_dir(x): if self.filter_package(basename(x)): continue self.add_package_dir(x) @flush def add_package_dir(self, x, dest=None): def ignore(root, files): ans = [] for y in files: ext = os.path.splitext(y)[1] if ext not in ('', '.py', '.so') or \ (not ext and not os.path.isdir(join(root, y))): ans.append(y) return ans if dest is None: dest = self.site_packages dest = join(dest, basename(x)) shutil.copytree(x, dest, symlinks=True, ignore=ignore) self.postprocess_package(x, dest) for x in os.walk(dest): for f in x[-1]: if f.endswith('.so'): f = join(x[0], f) self.fix_dependencies_in_lib(f) @flush def filter_package(self, name): return name in ('Cython', 'modulegraph', 'macholib', 'py2app', 'bdist_mpkg', 'altgraph') @flush def postprocess_package(self, src_path, dest_path): pass @flush def add_stdlib(self): print('\nAdding python stdlib') src = PREFIX + '/python/Python.framework/Versions/Current/lib/python' src += py_ver dest = join(self.resources_dir, 'Python', 'lib', 'python') dest += py_ver os.makedirs(dest) for x in os.listdir(src): if x in ('site-packages', 'config', 'test', 'lib2to3', 'lib-tk', 'lib-old', 'idlelib', 'plat-mac', 'plat-darwin', 'site.py'): continue x = join(src, x) if os.path.isdir(x): self.add_package_dir(x, dest) elif os.path.splitext(x)[1] in ('.so', '.py'): shutil.copy2(x, dest) dest2 = join(dest, basename(x)) if dest2.endswith('.so'): self.fix_dependencies_in_lib(dest2) target = join(self.resources_dir, 'Python', 'lib') self.remove_bytecode(target) for path in walk(target): if path.endswith('.so'): self.fix_dependencies_in_lib(path) @flush def remove_bytecode(self, dest): for x in os.walk(dest): root = x[0] for f in x[-1]: if os.path.splitext(f) in ('.pyc', '.pyo'): os.remove(join(root, f)) @flush def compile_py_modules(self): print('\nCompiling Python modules') base = join(self.resources_dir, 'Python') pydir = join(base, f'lib/python{py_ver}') src = join(pydir, 'lib-dynload') dest = join(self.frameworks_dir, 'plugins') print('Extracting extension modules from:', src, 'to', dest) self.ext_map.update(extract_extension_modules(src, dest)) os.rmdir(src) src = join(base, 'site-packages') print('Extracting extension modules from:', src, 'to', dest) self.ext_map.update(extract_extension_modules(src, dest)) for x in os.listdir(src): os.rename(join(src, x), join(pydir, x)) os.rmdir(src) py_compile(pydir) freeze_python( pydir, dest, self.inc_dir, self.ext_map, develop_mode_env_var='CALIBRE_DEVELOP_FROM', path_to_user_env_vars='~/Library/Preferences/calibre/macos-env.txt' ) shutil.rmtree(pydir) def create_app_clone(self, name, specialise_plist, remove_doc_types=False, base_dir=None): print('\nCreating ' + name) base_dir = base_dir or self.contents_dir cc_dir = join(base_dir, name, 'Contents') exe_dir = join(cc_dir, 'MacOS') rel_path = os.path.relpath(join(self.contents_dir, 'MacOS'), exe_dir) os.makedirs(exe_dir) for x in os.listdir(self.contents_dir): if x.endswith('.app'): continue if x == 'Info.plist': with open(join(self.contents_dir, x), 'rb') as r: plist = plistlib.load(r) specialise_plist(plist) if remove_doc_types: plist.pop('CFBundleDocumentTypes') exe = plist['CFBundleExecutable'] # We cannot symlink the bundle executable as if we do, # codesigning fails plist['CFBundleExecutable'] = exe + '-placeholder-for-codesigning' nexe = join(exe_dir, plist['CFBundleExecutable']) base = os.path.dirname(abspath(__file__)) cmd = gcc + ARCH_FLAGS + CFLAGS + [ '-Wall', '-Werror', '-DEXE_NAME="%s"' % exe, '-DREL_PATH="%s"' % rel_path, join(base, 'placeholder.c'), '-o', nexe, '-headerpad_max_install_names' ] subprocess.check_call(cmd) with open(join(cc_dir, x), 'wb') as p: plistlib.dump(plist, p) elif x == 'MacOS': for item in os.listdir(join(self.contents_dir, 'MacOS')): src = join(self.contents_dir, x, item) os.symlink(os.path.relpath(src, exe_dir), join(exe_dir, item)) else: src = join(self.contents_dir, x) os.symlink(os.path.relpath(src, cc_dir), join(cc_dir, x)) @flush def create_gui_apps(self): def get_data(cmd): return json.loads(subprocess.check_output([join(self.contents_dir, 'MacOS', 'calibre-debug'), '-c', cmd])) data = get_data( 'from calibre.customize.ui import all_input_formats; import sys, json; from calibre.ebooks.oeb.polish.main import SUPPORTED;' 'sys.stdout.write(json.dumps({"i": tuple(all_input_formats()), "e": tuple(SUPPORTED)}))' ) input_formats = sorted(set(data['i'])) edit_formats = sorted(set(data['e'])) def specialise_plist(launcher, formats, plist): plist['CFBundleDisplayName'] = plist['CFBundleName'] = { 'ebook-viewer': 'E-book Viewer', 'ebook-edit': 'Edit Book', }[launcher] plist['CFBundleExecutable'] = launcher plist['CFBundleIdentifier'] = 'com.calibre-ebook.' + launcher plist['CFBundleIconFile'] = launcher + '.icns' e = plist['CFBundleDocumentTypes'][0] e['CFBundleTypeExtensions'] = [x.lower() for x in formats] def headless_plist(plist): plist['CFBundleDisplayName'] = 'calibre worker process' plist['CFBundleExecutable'] = 'calibre-parallel' plist['CFBundleIdentifier'] = 'com.calibre-ebook.calibre-parallel' plist['LSBackgroundOnly'] = '1' plist.pop('CFBundleDocumentTypes') self.create_app_clone('ebook-viewer.app', partial(specialise_plist, 'ebook-viewer', input_formats)) self.create_app_clone('ebook-edit.app', partial(specialise_plist, 'ebook-edit', edit_formats), base_dir=join(self.contents_dir, 'ebook-viewer.app', 'Contents')) self.create_app_clone('headless.app', headless_plist, base_dir=join(self.contents_dir, 'ebook-viewer.app', 'Contents', 'ebook-edit.app', 'Contents')) # We need to move the webengine resources into the deepest sub-app # because the sandbox gets set to the nearest enclosing app which # means that WebEngine will fail to access its resources when running # in the sub-apps unless they are present inside the sub app bundle # somewhere base_dest = join(self.contents_dir, 'ebook-viewer.app', 'Contents', 'ebook-edit.app', 'Contents', 'headless.app', 'Contents', 'SharedSupport') os.mkdir(base_dest) base_src = os.path.realpath(join(self.frameworks_dir, 'QtWebEngineCore.framework/Resources')) items = [join(base_src, 'qtwebengine_locales')] + glob.glob(join(base_src, '*.pak')) + glob.glob(join(base_src, '*.dat')) for src in items: dest = join(base_dest, os.path.basename(src)) os.rename(src, dest) os.symlink(os.path.relpath(dest, base_src), src) @flush def copy_site(self): base = os.path.dirname(abspath(__file__)) shutil.copy2(join(base, 'site.py'), join(self.resources_dir, 'Python', 'lib', 'python' + py_ver)) @flush def makedmg(self, d, volname): ''' Copy a directory d into a dmg named volname ''' print('\nSigning...') sys.stdout.flush() destdir = OUTPUT_DIR try: shutil.rmtree(destdir) except EnvironmentError as err: if err.errno != errno.ENOENT: raise os.mkdir(destdir) dmg = join(destdir, volname + '.dmg') if os.path.exists(dmg): os.unlink(dmg) tdir = tempfile.mkdtemp() appdir = join(tdir, os.path.basename(d)) shutil.copytree(d, appdir, symlinks=True) if self.sign_installers or self.notarize: with timeit() as times: sign_app(appdir, self.notarize) print('Signing completed in %d minutes %d seconds' % tuple(times)) os.symlink('/Applications', join(tdir, 'Applications')) size_in_mb = int(subprocess.check_output(['du', '-s', '-k', tdir]).decode('utf-8').split()[0]) / 1024. # ULMO (10.15+) gives the best compression, better than ULFO and better+faster than UDBZ cmd = ['/usr/bin/hdiutil', 'create', '-srcfolder', tdir, '-volname', volname, '-format', 'ULMO'] if 190 < size_in_mb < 250: # We need -size 255m because of a bug in hdiutil. When the size of # srcfolder is close to 200MB hdiutil fails with # diskimages-helper: resize request is above maximum size allowed. cmd += ['-size', '255m'] print('\nCreating dmg...') with timeit() as times: subprocess.check_call(cmd + [dmg]) print('dmg created in %d minutes and %d seconds' % tuple(times)) shutil.rmtree(tdir) size = os.stat(dmg).st_size / (1024 * 1024.) print('\nInstaller size: %.2fMB\n' % size) return dmg def main(args, ext_dir, test_runner): build_dir = abspath(join(mkdtemp('frozen-'), APPNAME + '.app')) inc_dir = abspath(mkdtemp('include')) if args.skip_tests: def test_runner(*a): return None Freeze(build_dir, ext_dir, inc_dir, test_runner, dont_strip=args.dont_strip, sign_installers=args.sign_installers, notarize=args.notarize) if __name__ == '__main__': args = globals()['args'] ext_dir = globals()['ext_dir'] run_tests = iv['run_tests'] main(args, ext_dir, run_tests)
35,114
Python
.py
769
35.275683
150
0.579838
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,382
site.py
kovidgoyal_calibre/bypy/macos/site.py
import builtins import os import sys import _sitebuiltins USER_SITE = None def nuke_stdout(): # Redirect stdout, stdin and stderr to /dev/null from calibre_extensions.speedup import detach detach(os.devnull) def set_helper(): builtins.help = _sitebuiltins._Helper() def set_quit(): eof = 'Ctrl-D (i.e. EOF)' builtins.quit = _sitebuiltins.Quitter('quit', eof) builtins.exit = _sitebuiltins.Quitter('exit', eof) def main(): sys.argv[0] = sys.calibre_basename set_helper() set_quit() mod = __import__(sys.calibre_module, fromlist=[1]) func = getattr(mod, sys.calibre_function) if sys.gui_app and not ( sys.stdout.isatty() or sys.stderr.isatty() or sys.stdin.isatty() ): # this has to be done after calibre is imported and therefore # calibre_extensions is available. nuke_stdout() return func() if __name__ == '__main__': main()
934
Python
.py
30
26.533333
72
0.670404
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,383
__main__.py
kovidgoyal_calibre/bypy/windows/__main__.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import contextlib import errno import glob import os import re import runpy import shutil import stat import subprocess import sys import zipfile from bypy.constants import CL, LINK, MT, PREFIX, RC, SIGNTOOL, SW, build_dir, python_major_minor_version, worker_env from bypy.constants import SRC as CALIBRE_DIR from bypy.freeze import cleanup_site_packages, extract_extension_modules, freeze_python, path_to_freeze_dir from bypy.pkgs.piper import copy_piper_dir from bypy.utils import mkdtemp, py_compile, run, walk iv = globals()['init_env'] calibre_constants = iv['calibre_constants'] QT_PREFIX = os.path.join(PREFIX, 'qt') QT_DLLS, QT_PLUGINS, PYQT_MODULES = iv['QT_DLLS'], iv['QT_PLUGINS'], iv['PYQT_MODULES'] APPNAME, VERSION = calibre_constants['appname'], calibre_constants['version'] WINVER = VERSION + '.0' machine = 'X64' j, d, a, b = os.path.join, os.path.dirname, os.path.abspath, os.path.basename create_installer = runpy.run_path( j(d(a(__file__)), 'wix.py'), {'calibre_constants': calibre_constants} )['create_installer'] DESCRIPTIONS = { 'calibre': 'The main calibre program', 'ebook-viewer': 'The calibre e-book viewer', 'ebook-edit': 'The calibre e-book editor', 'lrfviewer': 'Viewer for LRF files', 'ebook-convert': 'Command line interface to the conversion/news download system', 'ebook-meta': 'Command line interface for manipulating e-book metadata', 'calibredb': 'Command line interface to the calibre database', 'calibre-launcher': 'Utility functions common to all executables', 'calibre-debug': 'Command line interface for calibre debugging/development', 'calibre-customize': 'Command line interface to calibre plugin system', 'calibre-server': 'Standalone calibre content server', 'calibre-parallel': 'calibre worker process', 'calibre-smtp': 'Command line interface for sending books via email', 'calibre-eject': 'Helper program for ejecting connected reader devices', 'calibre-file-dialog': 'Helper program to show file open/save dialogs', } EXE_MANIFEST = '''\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> </windowsSettings> </application> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /> </application> </compatibility> </assembly> ''' def printf(*args, **kw): print(*args, **kw) sys.stdout.flush() def run_compiler(env, *cmd): run(*cmd, cwd=env.obj_dir) class Env: def __init__(self, build_dir): self.python_base = os.path.join(PREFIX, 'private', 'python') self.portable_uncompressed_size = 0 self.src_root = CALIBRE_DIR self.base = j(build_dir, 'winfrozen') self.app_base = j(self.base, 'app') self.rc_template = j(d(a(__file__)), 'template.rc') self.py_ver = '.'.join(map(str, python_major_minor_version())) self.lib_dir = j(self.app_base, 'Lib') self.pylib = j(self.app_base, 'pylib.zip') self.dll_dir = j(self.app_base, 'bin') self.portable_base = j(d(self.base), 'Calibre Portable') self.obj_dir = j(build_dir, 'launcher') self.installer_dir = j(build_dir, 'wix') self.dist = j(SW, 'dist') def initbase(env): os.makedirs(env.app_base) os.mkdir(env.dll_dir) try: shutil.rmtree(env.dist) except EnvironmentError as err: if err.errno != errno.ENOENT: raise os.mkdir(env.dist) def freeze(env, ext_dir, incdir): shutil.copy2(j(env.src_root, 'LICENSE'), env.base) printf('Adding resources...') tgt = j(env.app_base, 'resources') if os.path.exists(tgt): shutil.rmtree(tgt) shutil.copytree(j(env.src_root, 'resources'), tgt) printf('\tAdding misc binary deps') def copybin(x, dest=env.dll_dir): shutil.copy2(x, dest) with contextlib.suppress(FileNotFoundError): shutil.copy2(x + '.manifest', dest) bindir = os.path.join(PREFIX, 'bin') for x in ('pdftohtml', 'pdfinfo', 'pdftoppm', 'pdftotext', 'jpegtran-calibre', 'cjpeg-calibre', 'optipng-calibre', 'cwebp-calibre', 'JXRDecApp-calibre'): copybin(os.path.join(bindir, x + '.exe')) for f in glob.glob(os.path.join(bindir, '*.dll')): if re.search(r'(easylzma|icutest)', f.lower()) is None: copybin(f) ossm = os.path.join(env.dll_dir, 'ossl-modules') os.mkdir(ossm) for f in glob.glob(os.path.join(PREFIX, 'lib', 'ossl-modules', '*.dll')): copybin(f, ossm) for f in glob.glob(os.path.join(PREFIX, 'ffmpeg', 'bin', '*.dll')): copybin(f) copy_piper_dir(PREFIX, env.dll_dir) copybin(os.path.join(env.python_base, 'python%s.dll' % env.py_ver.replace('.', ''))) copybin(os.path.join(env.python_base, 'python%s.dll' % env.py_ver[0])) for x in glob.glob(os.path.join(env.python_base, 'DLLs', '*.dll')): # dlls needed by python copybin(x) for f in walk(os.path.join(env.python_base, 'Lib')): q = f.lower() if q.endswith('.dll') and 'scintilla' not in q and 'pyqtbuild' not in q: copybin(f) ext_map = extract_extension_modules(ext_dir, env.dll_dir) ext_map.update(extract_extension_modules(j(env.python_base, 'DLLs'), env.dll_dir, move=False)) printf('Adding Qt...') for x in QT_DLLS: copybin(os.path.join(QT_PREFIX, 'bin', x + '.dll')) copybin(os.path.join(QT_PREFIX, 'bin', 'QtWebEngineProcess.exe')) plugdir = j(QT_PREFIX, 'plugins') tdir = j(env.app_base, 'plugins') for d in QT_PLUGINS: imfd = os.path.join(plugdir, d) tg = os.path.join(tdir, d) if os.path.exists(tg): shutil.rmtree(tg) shutil.copytree(imfd, tg) for f in walk(tdir): if not f.lower().endswith('.dll'): os.remove(f) for data_file in os.listdir(j(QT_PREFIX, 'resources')): shutil.copy2(j(QT_PREFIX, 'resources', data_file), j(env.app_base, 'resources')) shutil.copytree(j(QT_PREFIX, 'translations'), j(env.app_base, 'translations')) printf('Adding python...') def ignore_lib(root, items): ans = [] for x in items: ext = os.path.splitext(x)[1].lower() if ext in ('.dll', '.chm', '.htm', '.txt'): ans.append(x) return ans shutil.copytree(r'%s\Lib' % env.python_base, env.lib_dir, ignore=ignore_lib) install_site_py(env) sp_dir = j(env.lib_dir, 'site-packages') printf('Adding calibre sources...') for x in glob.glob(j(CALIBRE_DIR, 'src', '*')): if os.path.isdir(x): if os.path.exists(os.path.join(x, '__init__.py')): shutil.copytree(x, j(sp_dir, b(x)), ignore=shutil.ignore_patterns('*.pyc', '*.pyo')) else: shutil.copy(x, j(sp_dir, b(x))) ext_map.update(cleanup_site_packages(sp_dir)) for x in os.listdir(sp_dir): os.rename(j(sp_dir, x), j(env.lib_dir, x)) os.rmdir(sp_dir) printf('Extracting extension modules from', env.lib_dir, 'to', env.dll_dir) ext_map.update(extract_extension_modules(env.lib_dir, env.dll_dir)) printf('Byte-compiling all python modules...') py_compile(env.lib_dir.replace(os.sep, '/')) # from bypy.utils import run_shell # run_shell(cwd=env.lib_dir) freeze_python(env.lib_dir, env.dll_dir, incdir, ext_map, develop_mode_env_var='CALIBRE_DEVELOP_FROM') shutil.rmtree(env.lib_dir) def embed_manifests(env): printf('Embedding remaining manifests...') for manifest in walk(env.base): dll, ext = os.path.splitext(manifest) if ext != '.manifest': continue res = 2 if os.path.splitext(dll)[1] == '.exe': res = 1 if os.path.exists(dll) and open(manifest, 'rb').read().strip(): run(MT, '-manifest', manifest, '-outputresource:%s;%d' % (dll, res)) os.remove(manifest) def embed_resources(env, module, desc=None, extra_data=None, product_description=None): icon_base = j(env.src_root, 'icons') icon_map = { 'calibre': 'library', 'ebook-viewer': 'viewer', 'ebook-edit': 'ebook-edit', 'lrfviewer': 'viewer', } file_type = 'DLL' if module.endswith('.dll') else 'APP' with open(env.rc_template, 'rb') as f: template = f.read().decode('utf-8') bname = b(module) internal_name = os.path.splitext(bname)[0] icon = icon_map.get(internal_name.replace('-portable', ''), 'command-prompt') if internal_name.startswith('calibre-portable-'): icon = 'install' icon = j(icon_base, icon + '.ico') if desc is None: defdesc = 'A dynamic link library' if file_type == 'DLL' else \ 'An executable program' desc = DESCRIPTIONS.get(internal_name, defdesc) license = 'GNU GPL v3.0' def e(val): return val.replace('"', r'\"') if product_description is None: product_description = APPNAME + ' - E-book management' rc = template.format( icon=icon.replace('\\', '/'), file_type=e(file_type), file_version=e(WINVER.replace('.', ',')), file_version_str=e(WINVER), file_description=e(desc), internal_name=e(internal_name), original_filename=e(bname), product_version=e(WINVER.replace('.', ',')), product_version_str=e(VERSION), product_name=e(APPNAME), product_description=e(product_description), legal_copyright=e(license), legal_trademarks=e(APPNAME + ' is a registered U.S. trademark number 3,666,525') ) if extra_data: rc += '\nextra extra "%s"' % extra_data tdir = env.obj_dir rcf = j(tdir, bname + '.rc') with open(rcf, 'w') as f: f.write(rc) res = j(tdir, bname + '.res') run(RC, '/n', '/fo' + res, rcf) return res def install_site_py(env): if not os.path.exists(env.lib_dir): os.makedirs(env.lib_dir) shutil.copy2(j(d(__file__), 'site.py'), env.lib_dir) def build_portable_installer(env): zf = a(j(env.dist, 'calibre-portable-%s.zip.lz' % VERSION)).replace(os.sep, '/') usz = env.portable_uncompressed_size or os.path.getsize(zf) def cc(src, obj): cflags = '/c /EHsc /MT /W4 /Ox /nologo /D_UNICODE /DUNICODE /DPSAPI_VERSION=1'.split() cflags.append(r'/I%s\include' % PREFIX) cflags.append('/DUNCOMPRESSED_SIZE=%d' % usz) printf('Compiling', obj) cmd = [CL] + cflags + ['/Fo' + obj, src] run_compiler(env, *cmd) base = d(a(__file__)) src = j(base, 'portable-installer.cpp') obj = j(env.obj_dir, b(src) + '.obj') xsrc = j(base, 'XUnzip.cpp') xobj = j(env.obj_dir, b(xsrc) + '.obj') cc(src, obj) cc(xsrc, xobj) exe = j(env.dist, 'calibre-portable-installer-%s.exe' % VERSION) printf('Linking', exe) manifest = exe + '.manifest' with open(manifest, 'wb') as f: f.write(EXE_MANIFEST.encode('utf-8')) cmd = [LINK] + [ '/INCREMENTAL:NO', '/MACHINE:' + machine, '/LIBPATH:' + env.obj_dir, '/SUBSYSTEM:WINDOWS', '/LIBPATH:' + (PREFIX + r'\lib'), '/RELEASE', '/MANIFEST:EMBED', '/MANIFESTINPUT:' + manifest, '/ENTRY:wWinMainCRTStartup', '/OUT:' + exe, embed_resources( env, exe, desc='Calibre Portable Installer', extra_data=zf, product_description='Calibre Portable Installer'), xobj, obj, 'User32.lib', 'Shell32.lib', 'easylzma_s.lib', 'Ole32.lib', 'Shlwapi.lib', 'Kernel32.lib', 'Psapi.lib'] run(*cmd) os.remove(zf) os.remove(manifest) def build_portable(env): base = env.portable_base if os.path.exists(base): shutil.rmtree(base) os.makedirs(base) root = d(a(__file__)) src = j(root, 'portable.cpp') obj = j(env.obj_dir, b(src) + '.obj') cflags = '/c /EHsc /MT /W3 /Ox /nologo /D_UNICODE /DUNICODE'.split() for exe_name in ('calibre.exe', 'ebook-viewer.exe', 'ebook-edit.exe'): exe = j(base, exe_name.replace('.exe', '-portable.exe')) printf('Compiling', exe) cmd = [CL] + cflags + ['/Fo' + obj, '/Tp' + src] run_compiler(env, *cmd) printf('Linking', exe) desc = { 'calibre.exe': 'Calibre Portable', 'ebook-viewer.exe': 'Calibre Portable Viewer', 'ebook-edit.exe': 'Calibre Portable Editor' }[exe_name] cmd = [LINK] + [ '/INCREMENTAL:NO', '/MACHINE:' + machine, '/LIBPATH:' + env.obj_dir, '/SUBSYSTEM:WINDOWS', '/RELEASE', '/ENTRY:wWinMainCRTStartup', '/OUT:' + exe, embed_resources(env, exe, desc=desc, product_description=desc), obj, 'User32.lib', 'Shell32.lib'] run(*cmd) printf('Creating portable installer') shutil.copytree(env.base, j(base, 'Calibre')) os.mkdir(j(base, 'Calibre Library')) os.mkdir(j(base, 'Calibre Settings')) name = '%s-portable-%s.zip' % (APPNAME, VERSION) name = j(env.dist, name) with zipfile.ZipFile(name, 'w', zipfile.ZIP_STORED) as zf: add_dir_to_zip(zf, base, 'Calibre Portable') env.portable_uncompressed_size = os.path.getsize(name) subprocess.check_call([PREFIX + r'\bin\elzma.exe', '-9', '--lzip', name]) def sign_files(env, files): with open(os.path.expandvars(r'${HOMEDRIVE}${HOMEPATH}\code-signing\cert-cred')) as f: pw = f.read().strip() CODESIGN_CERT = os.path.abspath(os.path.expandvars(r'${HOMEDRIVE}${HOMEPATH}\code-signing\authenticode.pfx')) args = [SIGNTOOL, 'sign', '/a', '/fd', 'sha256', '/td', 'sha256', '/d', 'calibre - E-book management', '/du', 'https://calibre-ebook.com', '/f', CODESIGN_CERT, '/p', pw, '/tr'] def runcmd(cmd): # See https://gist.github.com/Manouchehri/fd754e402d98430243455713efada710 for list of timestamp servers for timeserver in ( 'http://timestamp.acs.microsoft.com/', # this is Microsoft Azure Code Signing 'http://rfc3161.ai.moda/windows', # this is a load balancer 'http://timestamp.comodoca.com/rfc3161', 'http://timestamp.sectigo.com' ): try: subprocess.check_call(cmd + [timeserver] + list(files)) break except subprocess.CalledProcessError: print(f'Signing failed with timestamp server {timeserver}, retrying with different timestamp server') else: raise SystemExit('Signing failed') runcmd(args) def sign_installers(env): printf('Signing installers...') installers = set() for f in glob.glob(j(env.dist, '*')): if f.rpartition('.')[-1].lower() in {'exe', 'msi'}: installers.add(f) else: os.remove(f) if not installers: raise ValueError('No installers found') sign_files(env, installers) def add_dir_to_zip(zf, path, prefix=''): ''' Add a directory recursively to the zip file with an optional prefix. ''' if prefix: zi = zipfile.ZipInfo(prefix + '/') zi.external_attr = 16 zf.writestr(zi, '') cwd = os.path.abspath(os.getcwd()) try: os.chdir(path) fp = (prefix + ('/' if prefix else '')).replace('//', '/') for f in os.listdir('.'): arcname = fp + f if os.path.isdir(f): add_dir_to_zip(zf, f, prefix=arcname) else: zf.write(f, arcname) finally: os.chdir(cwd) def build_utils(env): def build(src, name, subsys='CONSOLE', libs='setupapi.lib'.split()): printf('Building ' + name) obj = j(env.obj_dir, os.path.basename(src) + '.obj') cflags = '/c /EHsc /MD /W3 /Ox /nologo /D_UNICODE'.split() ftype = '/T' + ('c' if src.endswith('.c') else 'p') cmd = [CL] + cflags + ['/Fo' + obj, ftype + src] run_compiler(env, *cmd) exe = j(env.dll_dir, name) mf = exe + '.manifest' with open(mf, 'wb') as f: f.write(EXE_MANIFEST.encode('utf-8')) cmd = [LINK] + [ '/MACHINE:' + machine, '/SUBSYSTEM:' + subsys, '/RELEASE', '/MANIFEST:EMBED', '/MANIFESTINPUT:' + mf, '/OUT:' + exe] + [embed_resources(env, exe), obj] + libs run(*cmd) base = d(a(__file__)) build(j(base, 'file_dialogs.cpp'), 'calibre-file-dialog.exe', 'WINDOWS', 'Ole32.lib Shell32.lib'.split()) build(j(base, 'eject.c'), 'calibre-eject.exe') def build_launchers(env, incdir, debug=False): if not os.path.exists(env.obj_dir): os.makedirs(env.obj_dir) dflags = (['/Zi'] if debug else []) dlflags = (['/DEBUG'] if debug else ['/INCREMENTAL:NO']) base = d(a(__file__)) sources = [j(base, x) for x in ['util.c', ]] objects = [j(env.obj_dir, b(x) + '.obj') for x in sources] cflags = '/c /EHsc /W3 /Ox /nologo /D_UNICODE'.split() cflags += ['/DPYDLL="python%s.dll"' % env.py_ver.replace('.', ''), '/I%s/include' % env.python_base] cflags += [f'/I{path_to_freeze_dir()}', f'/I{incdir}'] for src, obj in zip(sources, objects): cmd = [CL] + cflags + dflags + ['/MD', '/Fo' + obj, '/Tc' + src] run_compiler(env, *cmd) dll = j(env.obj_dir, 'calibre-launcher.dll') ver = '.'.join(VERSION.split('.')[:2]) cmd = [LINK, '/DLL', '/VERSION:' + ver, '/LTCG', '/OUT:' + dll, '/nologo', '/MACHINE:' + machine] + dlflags + objects + \ [embed_resources(env, dll), '/LIBPATH:%s/libs' % env.python_base, 'delayimp.lib', 'user32.lib', 'shell32.lib', 'python%s.lib' % env.py_ver.replace('.', ''), '/delayload:python%s.dll' % env.py_ver.replace('.', '')] printf('Linking calibre-launcher.dll') run(*cmd) src = j(base, 'main.c') shutil.copy2(dll, env.dll_dir) basenames, modules, functions = calibre_constants['basenames'], calibre_constants['modules'], calibre_constants['functions'] for typ in ('console', 'gui', ): printf('Processing %s launchers' % typ) subsys = 'WINDOWS' if typ == 'gui' else 'CONSOLE' for mod, bname, func in zip(modules[typ], basenames[typ], functions[typ]): cflags = '/c /EHsc /MT /W3 /O1 /nologo /D_UNICODE /DUNICODE /GS-'.split() if typ == 'gui': cflags += ['/DGUI_APP='] cflags += ['/DMODULE=L"%s"' % mod, '/DBASENAME=L"%s"' % bname, '/DFUNCTION=L"%s"' % func] dest = j(env.obj_dir, bname + '.obj') printf('Compiling', bname) cmd = [CL] + cflags + dflags + ['/Tc' + src, '/Fo' + dest] run_compiler(env, *cmd) exe = j(env.base, bname + '.exe') lib = dll.replace('.dll', '.lib') u32 = ['user32.lib'] printf('Linking', bname) mf = dest + '.manifest' with open(mf, 'wb') as f: f.write(EXE_MANIFEST.encode('utf-8')) cmd = [LINK] + [ '/MACHINE:' + machine, '/NODEFAULTLIB', '/ENTRY:start_here', '/LIBPATH:' + env.obj_dir, '/SUBSYSTEM:' + subsys, '/LIBPATH:%s/libs' % env.python_base, '/RELEASE', '/MANIFEST:EMBED', '/MANIFESTINPUT:' + mf, '/STACK:2097152', # Set stack size to 2MB which is what python expects. Default on windows is 1MB 'user32.lib', 'kernel32.lib', '/OUT:' + exe] + u32 + dlflags + [embed_resources(env, exe), dest, lib] run(*cmd) def copy_crt_and_d3d(env): printf('Copying CRT and D3D...') plat = 'x64' for key, val in worker_env.items(): if 'COMNTOOLS' in key.upper(): redist_dir = os.path.dirname(os.path.dirname(val.rstrip(os.sep))) redist_dir = os.path.join(redist_dir, 'VC', 'Redist', 'MSVC') vc_path = glob.glob(os.path.join(redist_dir, '*', plat, '*.CRT'))[0] break else: raise SystemExit('Could not find Visual Studio redistributable CRT') sdk_path = os.path.join( worker_env['UNIVERSALCRTSDKDIR'], 'Redist', worker_env['WINDOWSSDKVERSION'], 'ucrt', 'DLLs', plat) if not os.path.exists(sdk_path): raise SystemExit('Windows 10 Universal CRT redistributable not found at: %r' % sdk_path) d3d_path = os.path.join( worker_env['WINDOWSSDKDIR'], 'Redist', 'D3D', plat) if not os.path.exists(d3d_path): raise SystemExit('Windows 10 D3D redistributable not found at: %r' % d3d_path) mesa_path = os.path.join(os.environ['MESA'], '64', 'opengl32sw.dll') if not os.path.exists(mesa_path): raise SystemExit('Mesa DLLs (opengl32sw.dll) not found at: %r' % mesa_path) def copy_dll(dll): shutil.copy2(dll, env.dll_dir) os.chmod(os.path.join(env.dll_dir, b(dll)), stat.S_IRWXU) for dll in glob.glob(os.path.join(d3d_path, '*.dll')): if os.path.basename(dll).lower().startswith('d3dcompiler_'): copy_dll(dll) copy_dll(mesa_path) for dll in glob.glob(os.path.join(sdk_path, '*.dll')): copy_dll(dll) for dll in glob.glob(os.path.join(vc_path, '*.dll')): bname = os.path.basename(dll) if not bname.startswith('vccorlib') and not bname.startswith('concrt'): # Those two DLLs are not required vccorlib is for the CORE CLR # I think concrt is the concurrency runtime for C++ which I believe # nothing in calibre currently uses copy_dll(dll) def sign_executables(env): files_to_sign = [] for path in walk(env.base): if path.lower().endswith('.exe') or path.lower().endswith('.dll'): files_to_sign.append(path) printf('Signing {} exe/dll files'.format(len(files_to_sign))) sign_files(env, files_to_sign) def main(): ext_dir = globals()['ext_dir'] args = globals()['args'] run_tests = iv['run_tests'] env = Env(build_dir()) incdir = mkdtemp('include') initbase(env) freeze(env, ext_dir, incdir) build_launchers(env, incdir) build_utils(env) embed_manifests(env) copy_crt_and_d3d(env) if not args.skip_tests: run_tests(os.path.join(env.base, 'calibre-debug.exe'), env.base) if args.sign_installers: sign_executables(env) create_installer(env, args.compression_level) build_portable(env) build_portable_installer(env) if args.sign_installers: sign_installers(env) def develop_launcher(): import subprocess def r(*a): subprocess.check_call(list(a)) r( 'cl.EXE', '/c', '/EHsc', '/MT', '/W3', '/O1', '/nologo', '/D_UNICODE', '/DUNICODE', '/GS-', '/DMODULE="calibre.debug"', '/DBASENAME="calibre-debug"', '/DFUNCTION="main"', r'/TcC:\r\src\bypy\windows\main.c', r'/Fo..\launcher\calibre-debug.obj' ) r( 'link.EXE', '/MACHINE:X86', '/NODEFAULTLIB', '/ENTRY:start_here', r'/LIBPATH:..\launcher', '/SUBSYSTEM:CONSOLE', r'/LIBPATH:C:\r\sw32\sw\private\python/libs', '/RELEASE', '/MANIFEST:EMBED', r'/MANIFESTINPUT:..\launcher\calibre-debug.obj.manifest', 'user32.lib', 'kernel32.lib', r'/OUT:calibre-debug.exe', 'user32.lib', '/INCREMENTAL:NO', r'..\launcher\calibre-debug.exe.res', r'..\launcher\calibre-debug.obj', r'..\launcher\calibre-launcher.lib' ) if __name__ == '__main__': main()
24,040
Python
.py
535
37.564486
157
0.607018
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,384
site.py
kovidgoyal_calibre/bypy/windows/site.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import builtins import os import sys from importlib import import_module from importlib.machinery import EXTENSION_SUFFIXES from importlib.util import spec_from_file_location import _sitebuiltins pyd_items = None extension_suffixes = sorted(EXTENSION_SUFFIXES, key=len, reverse=True) USER_SITE = None def remove_extension_suffix(name): for q in extension_suffixes: if name.endswith(q): return name[:-len(q)] class PydImporter: def find_spec(self, fullname, path, target=None): global pyd_items if pyd_items is None: pyd_items = {} dlls_dir = os.path.join(sys.app_dir, 'app', 'bin') for x in os.listdir(dlls_dir): lx = x.lower() if lx.endswith('.pyd'): pyd_items[remove_extension_suffix(lx)] = os.path.abspath(os.path.join(dlls_dir, x)) q = fullname.lower() path = pyd_items.get(q) if path is not None: return spec_from_file_location(fullname, path) def invalidate_caches(self): global pyd_items pyd_items = None def run_entry_point(): bname, mod, func = sys.calibre_basename, sys.calibre_module, sys.calibre_function sys.argv[0] = bname + '.exe' pmod = import_module(mod) return getattr(pmod, func)() def set_helper(): builtins.help = _sitebuiltins._Helper() def set_quit(): eof = 'Ctrl-Z plus Return' builtins.quit = _sitebuiltins.Quitter('quit', eof) builtins.exit = _sitebuiltins.Quitter('exit', eof) def main(): sys.meta_path.insert(0, PydImporter()) os.add_dll_directory(os.path.abspath(os.path.join(sys.app_dir, 'app', 'bin'))) import linecache def fake_getline(filename, lineno, module_globals=None): return '' linecache.orig_getline = linecache.getline linecache.getline = fake_getline set_helper() set_quit() return run_entry_point() if __name__ == '__main__': try: main() except Exception: if sys.gui_app and sys.excepthook == sys.__excepthook__: import traceback import calibre_os_module calibre_os_module.gui_error_message( f"Unhandled exception running {sys.calibre_basename}", traceback.format_exc()) raise
2,455
Python
.py
67
29.835821
103
0.651291
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,385
wix.py
kovidgoyal_calibre/bypy/windows/wix.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import os import shutil from itertools import count from bypy.constants import is64bit from bypy.utils import run WIX = os.path.expanduser('~/.dotnet/tools/wix.exe') if is64bit: UPGRADE_CODE = '5DD881FF-756B-4097-9D82-8C0F11D521EA' else: UPGRADE_CODE = 'BEB2A80D-E902-4DAD-ADF9-8BD2DA42CFE1' calibre_constants = globals()['calibre_constants'] j, d, a, b = os.path.join, os.path.dirname, os.path.abspath, os.path.basename def add_wix_extension(name): if not os.path.exists(os.path.expanduser(f'~/.wix/extensions/{name}')): run(WIX, 'extension', 'add', '-g', name) def create_installer(env, compression_level='9'): cl = int(compression_level) if cl > 4: dcl = 'high' else: dcl = {1: 'none', 2: 'low', 3: 'medium', 4: 'mszip'}[cl] if os.path.exists(env.installer_dir): shutil.rmtree(env.installer_dir) os.makedirs(env.installer_dir) with open(j(d(__file__), 'wix-template.xml'), 'rb') as f: template = f.read().decode('utf-8') cmd = [WIX, '--version'] WIXVERSION = run(*cmd, get_output=True).decode('utf-8').split('.')[0] if int(WIXVERSION) >= 5: # Virtual Symbol "WixUISupportPerUser" needs to be overridden in WIX V5 https://wixtoolset.org/docs/fivefour/ template = template.replace('WixUISupportPerUser', 'override WixUISupportPerUser') components, smap = get_components_from_files(env) wxs = template.format( app=calibre_constants['appname'], version=calibre_constants['version'], upgrade_code=UPGRADE_CODE, x64=' 64bit' if is64bit else '', compression='high', app_components=components, exe_map=smap, main_icon=j(env.src_root, 'icons', 'library.ico'), viewer_icon=j(env.src_root, 'icons', 'viewer.ico'), editor_icon=j(env.src_root, 'icons', 'ebook-edit.ico'), web_icon=j(env.src_root, 'icons', 'web.ico'), license=j(env.src_root, 'LICENSE.rtf'), banner=j(env.src_root, 'icons', 'wix-banner.bmp'), dialog=j(env.src_root, 'icons', 'wix-dialog.bmp'), ) with open(j(d(__file__), 'en-us.xml'), 'rb') as f: template = f.read().decode('utf-8') enus = template.format(app=calibre_constants['appname']) enusf = j(env.installer_dir, 'en-us.wxl') wxsf = j(env.installer_dir, calibre_constants['appname'] + '.wxs') with open(wxsf, 'wb') as f: f.write(wxs.encode('utf-8')) with open(enusf, 'wb') as f: f.write(enus.encode('utf-8')) arch = 'x64' if is64bit else 'x86' installer = j(env.dist, '%s%s-%s.msi' % ( calibre_constants['appname'], ('-64bit' if is64bit else ''), calibre_constants['version'])) add_wix_extension('WixToolset.Util.wixext') add_wix_extension( 'WixToolset.UI.wixext') cmd = [WIX, 'build', '-arch', arch, '-culture', 'en-us', '-loc', enusf, '-dcl', dcl, '-ext', 'WixToolset.Util.wixext', '-ext', 'WixToolset.UI.wixext', '-o', installer, wxsf] run(*cmd) pdb = installer.rpartition('.')[0] + '.wixpdb' os.remove(pdb) def get_components_from_files(env): file_idc = count() file_id_map = {} def process_dir(path): components = [] for x in os.listdir(path): f = os.path.join(path, x) file_id_map[f] = fid = next(file_idc) if os.path.isdir(f): components.append( '<Directory Id="file_%s" FileSource="%s" Name="%s">' % (file_id_map[f], f, x)) c = process_dir(f) components.extend(c) components.append('</Directory>') else: checksum = 'Checksum="yes"' if x.endswith('.exe') else '' c = [ ('<Component Id="component_%s" Feature="MainApplication" ' 'Guid="*">') % (fid,), ('<File Id="file_%s" Source="%s" Name="%s" ReadOnly="yes" ' 'KeyPath="yes" %s/>') % (fid, f, x, checksum), '</Component>' ] if x.endswith('.exe') and not x.startswith('pdf'): # Add the executable to app paths so that users can # launch it from the run dialog even if it is not on # the path. See http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx c[-1:-1] = [ ('<RegistryValue Root="HKLM" ' r'Key="SOFTWARE\Microsoft\Windows\CurrentVersion\App ' r'Paths\%s" Value="[#file_%d]" Type="string" />' % (x, fid)), ('<RegistryValue Root="HKLM" ' r'Key="SOFTWARE\Microsoft\Windows\CurrentVersion\App ' r'Paths\{0}" Name="Path" Value="[APPLICATIONFOLDER]" ' 'Type="string" />'.format(x)), ] components.append('\n'.join(c)) return components components = process_dir(a(env.base)) smap = {} for x in calibre_constants['basenames']['gui']: smap[x] = 'file_%d' % file_id_map[a(j(env.base, x + '.exe'))] return '\t\t\t\t' + '\n\t\t\t\t'.join(components), smap
5,418
Python
.py
115
36.947826
117
0.563399
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,386
__main__.py
kovidgoyal_calibre/bypy/linux/__main__.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import errno import glob import os import shutil import stat import subprocess import tarfile import time from functools import partial from bypy.constants import LIBDIR, OUTPUT_DIR, PREFIX, python_major_minor_version from bypy.constants import SRC as CALIBRE_DIR from bypy.freeze import extract_extension_modules, fix_pycryptodome, freeze_python, is_package_dir, path_to_freeze_dir from bypy.pkgs.piper import copy_piper_dir from bypy.utils import create_job, get_dll_path, mkdtemp, parallel_build, py_compile, run, walk j = os.path.join self_dir = os.path.dirname(os.path.abspath(__file__)) machine = (os.uname()[4] or '').lower() py_ver = '.'.join(map(str, python_major_minor_version())) QT_PREFIX = os.path.join(PREFIX, 'qt') FFMPEG_PREFIX = os.path.join(PREFIX, 'ffmpeg', 'lib') iv = globals()['init_env'] calibre_constants = iv['calibre_constants'] QT_DLLS, QT_PLUGINS, PYQT_MODULES = iv['QT_DLLS'], iv['QT_PLUGINS'], iv['PYQT_MODULES'] qt_get_dll_path = partial(get_dll_path, loc=os.path.join(QT_PREFIX, 'lib')) ffmpeg_get_dll_path = partial(get_dll_path, loc=FFMPEG_PREFIX) def binary_includes(): ffmpeg_dlls = tuple(os.path.basename(x).partition('.')[0][3:] for x in glob.glob(os.path.join(FFMPEG_PREFIX, '*.so'))) return [ j(PREFIX, 'bin', x) for x in ('pdftohtml', 'pdfinfo', 'pdftoppm', 'pdftotext', 'optipng', 'cwebp', 'JxrDecApp')] + [ j(PREFIX, 'private', 'mozjpeg', 'bin', x) for x in ('jpegtran', 'cjpeg')] + [ ] + list(map( get_dll_path, ('usb-1.0 mtp expat sqlite3 ffi z lzma openjp2 poppler dbus-1 iconv xml2 xslt jpeg png16' ' webp webpmux webpdemux sharpyuv exslt ncursesw readline chm hunspell-1.7 hyphen' ' icudata icui18n icuuc icuio stemmer gcrypt gpg-error uchardet graphite2' ' brotlicommon brotlidec brotlienc zstd podofo ssl crypto deflate tiff' ' gobject-2.0 glib-2.0 gthread-2.0 gmodule-2.0 gio-2.0 dbus-glib-1').split() )) + [ # debian/ubuntu for for some typical stupid reason use libpcre.so.3 # instead of libpcre.so.0 like other distros. And Qt's idiotic build # system links against this pcre library despite being told to use # the bundled pcre. Since libpcre doesn't depend on anything other # than libc and libpthread we bundle the Ubuntu one here glob.glob('/usr/lib/*/libpcre.so.3')[0], get_dll_path('bz2', 2), j(PREFIX, 'lib', 'libunrar.so'), get_dll_path('python' + py_ver, 2), get_dll_path('jbig', 2), # We dont include libstdc++.so as the OpenGL dlls on the target # computer fail to load in the QPA xcb plugin if they were compiled # with a newer version of gcc than the one on the build computer. # libstdc++, like glibc is forward compatible and I dont think any # distros do not have libstdc++.so.6, so it should be safe to leave it out. # https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html (The current # debian stable libstdc++ is libstdc++.so.6.0.17) ] + list(map(qt_get_dll_path, QT_DLLS)) + list(map(ffmpeg_get_dll_path, ffmpeg_dlls)) class Env: def __init__(self): self.src_root = CALIBRE_DIR self.base = mkdtemp('frozen-') self.lib_dir = j(self.base, 'lib') self.py_dir = j(self.lib_dir, 'python' + py_ver) os.makedirs(self.py_dir) self.bin_dir = j(self.base, 'bin') os.mkdir(self.bin_dir) self.SRC = j(self.src_root, 'src') self.obj_dir = mkdtemp('launchers-') def ignore_in_lib(base, items, ignored_dirs=None): ans = [] if ignored_dirs is None: ignored_dirs = {'.svn', '.bzr', '.git', 'test', 'tests', 'testing'} for name in items: path = j(base, name) if os.path.isdir(path): if name != 'plugins' and (name in ignored_dirs or not is_package_dir(path)): ans.append(name) else: if name.rpartition('.')[-1] not in ('so', 'py'): ans.append(name) return ans def import_site_packages(srcdir, dest): if not os.path.exists(dest): os.mkdir(dest) for x in os.listdir(srcdir): ext = x.rpartition('.')[-1] f = j(srcdir, x) if ext in ('py', 'so'): shutil.copy2(f, dest) elif ext == 'pth' and x != 'setuptools.pth': for line in open(f, 'rb').read().decode('utf-8').splitlines(): src = os.path.abspath(j(srcdir, line)) if os.path.exists(src) and os.path.isdir(src): import_site_packages(src, dest) elif is_package_dir(f): shutil.copytree(f, j(dest, x), ignore=ignore_in_lib) def copy_piper(env): print('Copying piper...') copy_piper_dir(PREFIX, env.bin_dir) def copy_libs(env): print('Copying libs...') for x in binary_includes(): dest = env.bin_dir if '/bin/' in x else env.lib_dir shutil.copy2(x, dest) os.chmod(j( dest, os.path.basename(x)), stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) for x in ('ossl-modules',): shutil.copytree(os.path.join(LIBDIR, x), os.path.join(env.lib_dir, x)) base = j(QT_PREFIX, 'plugins') dest = j(env.lib_dir, '..', 'plugins') os.mkdir(dest) for x in QT_PLUGINS: if x not in ('audio', 'printsupport'): shutil.copytree(j(base, x), j(dest, x)) dest = j(env.lib_dir, '..', 'libexec') os.mkdir(dest) shutil.copy2(os.path.join(QT_PREFIX, 'libexec', 'QtWebEngineProcess'), dest) def copy_python(env, ext_dir): print('Copying python...') srcdir = j(PREFIX, 'lib/python' + py_ver) for x in os.listdir(srcdir): y = j(srcdir, x) ext = os.path.splitext(x)[1] if os.path.isdir(y) and x not in ('test', 'hotshot', 'site-packages', 'idlelib', 'dist-packages'): shutil.copytree(y, j(env.py_dir, x), ignore=ignore_in_lib) if os.path.isfile(y) and ext in ('.py', '.so'): shutil.copy2(y, env.py_dir) srcdir = j(srcdir, 'site-packages') dest = j(env.py_dir, 'site-packages') import_site_packages(srcdir, dest) for x in os.listdir(env.SRC): c = j(env.SRC, x) if os.path.exists(j(c, '__init__.py')): shutil.copytree(c, j(dest, x), ignore=partial(ignore_in_lib, ignored_dirs={})) elif os.path.isfile(c): shutil.copy2(c, j(dest, x)) shutil.copytree(j(env.src_root, 'resources'), j(env.base, 'resources')) for pak in glob.glob(j(QT_PREFIX, 'resources', '*')): shutil.copy2(pak, j(env.base, 'resources')) os.mkdir(j(env.base, 'translations')) shutil.copytree(j(QT_PREFIX, 'translations', 'qtwebengine_locales'), j(env.base, 'translations', 'qtwebengine_locales')) sitepy = j(self_dir, 'site.py') shutil.copy2(sitepy, j(env.py_dir, 'site.py')) pdir = j(env.lib_dir, 'calibre-extensions') if not os.path.exists(pdir): os.mkdir(pdir) fix_pycryptodome(j(env.py_dir, 'site-packages')) for x in os.listdir(j(env.py_dir, 'site-packages')): os.rename(j(env.py_dir, 'site-packages', x), j(env.py_dir, x)) os.rmdir(j(env.py_dir, 'site-packages')) print('Extracting extension modules from', ext_dir, 'to', pdir) ext_map = extract_extension_modules(ext_dir, pdir) shutil.rmtree(j(env.py_dir, 'calibre', 'plugins')) print('Extracting extension modules from', env.py_dir, 'to', pdir) ext_map.update(extract_extension_modules(env.py_dir, pdir)) py_compile(env.py_dir) freeze_python(env.py_dir, pdir, env.obj_dir, ext_map, develop_mode_env_var='CALIBRE_DEVELOP_FROM') shutil.rmtree(env.py_dir) def build_launchers(env): base = self_dir sources = [j(base, x) for x in ['util.c']] objects = [j(env.obj_dir, os.path.basename(x) + '.o') for x in sources] cflags = '-fno-strict-aliasing -W -Wall -c -O2 -pipe -DPY_VERSION_MAJOR={} -DPY_VERSION_MINOR={}'.format(*py_ver.split('.')) cflags = cflags.split() + ['-I%s/include/python%s' % (PREFIX, py_ver)] cflags += [f'-I{path_to_freeze_dir()}', f'-I{env.obj_dir}'] for src, obj in zip(sources, objects): cmd = ['gcc'] + cflags + ['-fPIC', '-o', obj, src] run(*cmd) dll = j(env.lib_dir, 'libcalibre-launcher.so') cmd = ['gcc', '-O2', '-Wl,--rpath=$ORIGIN/../lib', '-fPIC', '-o', dll, '-shared'] + objects + \ ['-L%s/lib' % PREFIX, '-lpython' + py_ver] run(*cmd) src = j(base, 'main.c') modules, basenames, functions = calibre_constants['modules'].copy(), calibre_constants['basenames'].copy(), calibre_constants['functions'].copy() modules['console'].append('calibre.linux') basenames['console'].append('calibre_postinstall') functions['console'].append('main') c_launcher = '/tmp/calibre-c-launcher' lsrc = os.path.join(base, 'launcher.c') cmd = ['gcc', '-O2', '-o', c_launcher, lsrc, ] run(*cmd) jobs = [] for typ in ('console', 'gui', ): for mod, bname, func in zip(modules[typ], basenames[typ], functions[typ]): xflags = list(cflags) xflags.remove('-c') xflags += ['-DGUI_APP=' + ('1' if typ == 'gui' else '0')] xflags += ['-DMODULE=L"%s"' % mod, '-DBASENAME=L"%s"' % bname, '-DFUNCTION=L"%s"' % func] exe = j(env.bin_dir, bname) cmd = ['gcc'] + xflags + [src, '-o', exe, '-L' + env.lib_dir, '-lcalibre-launcher'] jobs.append(create_job(cmd)) sh = j(env.base, bname) shutil.copy2(c_launcher, sh) os.chmod(sh, stat.S_IREAD | stat.S_IEXEC | stat.S_IWRITE | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) if jobs: if not parallel_build(jobs, verbose=False): raise SystemExit(1) def is_elf(path): with open(path, 'rb') as f: return f.read(4) == b'\x7fELF' STRIPCMD = ['strip'] def strip_files(files, argv_max=(256 * 1024)): """ Strip a list of files """ while files: cmd = list(STRIPCMD) pathlen = sum(len(s) + 1 for s in cmd) while pathlen < argv_max and files: f = files.pop() cmd.append(f) pathlen += len(f) + 1 if len(cmd) > len(STRIPCMD): all_files = cmd[len(STRIPCMD):] unwritable_files = tuple(filter(None, (None if os.access(x, os.W_OK) else (x, os.stat(x).st_mode) for x in all_files))) [os.chmod(x, stat.S_IWRITE | old_mode) for x, old_mode in unwritable_files] subprocess.check_call(cmd) [os.chmod(x, old_mode) for x, old_mode in unwritable_files] def strip_binaries(env): files = {j(env.bin_dir, x) for x in os.listdir(env.bin_dir) if x != 'piper'} | { x for x in { j(os.path.dirname(env.bin_dir), x) for x in os.listdir(env.bin_dir)} if os.path.exists(x)} for x in walk(env.lib_dir): x = os.path.realpath(x) if x not in files and is_elf(x): files.add(x) files.add(j(env.lib_dir, '..', 'libexec', 'QtWebEngineProcess')) print('Stripping %d files...' % len(files)) before = sum(os.path.getsize(x) for x in files) strip_files(files) after = sum(os.path.getsize(x) for x in files) print('Stripped %.1f MB' % ((before - after) / (1024 * 1024.))) def create_tarfile(env, compression_level='9'): print('Creating archive...') base = OUTPUT_DIR arch = 'arm64' if 'arm64' in os.environ['BYPY_ARCH'] else ('i686' if 'i386' in os.environ['BYPY_ARCH'] else 'x86_64') try: shutil.rmtree(base) except EnvironmentError as err: if err.errno not in (errno.ENOENT, errno.EBUSY): raise os.makedirs(base, exist_ok=True) # when base is a mount point deleting it fails with EBUSY dist = os.path.join(base, '%s-%s-%s.tar' % (calibre_constants['appname'], calibre_constants['version'], arch)) with tarfile.open(dist, mode='w', format=tarfile.PAX_FORMAT) as tf: cwd = os.getcwd() os.chdir(env.base) try: for x in os.listdir('.'): tf.add(x) finally: os.chdir(cwd) print('Compressing archive...') ans = dist.rpartition('.')[0] + '.txz' start_time = time.time() subprocess.check_call(['xz', '--verbose', '--threads=0', '-f', '-' + compression_level, dist]) secs = time.time() - start_time print('Compressed in %d minutes %d seconds' % (secs // 60, secs % 60)) os.rename(dist + '.xz', ans) print('Archive %s created: %.2f MB' % ( os.path.basename(ans), os.stat(ans).st_size / (1024.**2))) def main(): args = globals()['args'] ext_dir = globals()['ext_dir'] run_tests = iv['run_tests'] env = Env() copy_libs(env) copy_python(env, ext_dir) copy_piper(env) build_launchers(env) if not args.skip_tests: run_tests(j(env.base, 'calibre-debug'), env.base) if not args.dont_strip: strip_binaries(env) create_tarfile(env, args.compression_level) if __name__ == '__main__': main()
13,337
Python
.py
278
40.363309
149
0.60518
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,387
site.py
kovidgoyal_calibre/bypy/linux/site.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import builtins import os import sys import _sitebuiltins USER_SITE = None def set_quit(): eof = 'Ctrl-D (i.e. EOF)' builtins.quit = _sitebuiltins.Quitter('quit', eof) builtins.exit = _sitebuiltins.Quitter('exit', eof) def setup_openssl_environment(): # Workaround for Linux distros that have still failed to get their heads # out of their asses and implement a common location for SSL certificates. # It's not that hard people, there exists a wonderful tool called the symlink # See http://www.mobileread.com/forums/showthread.php?t=256095 if 'SSL_CERT_FILE' not in os.environ and 'SSL_CERT_DIR' not in os.environ: if os.access('/etc/pki/tls/certs/ca-bundle.crt', os.R_OK): os.environ['SSL_CERT_FILE'] = '/etc/pki/tls/certs/ca-bundle.crt' elif os.path.isdir('/etc/ssl/certs'): os.environ['SSL_CERT_DIR'] = '/etc/ssl/certs' def set_helper(): builtins.help = _sitebuiltins._Helper() def main(): sys.argv[0] = sys.calibre_basename set_helper() setup_openssl_environment() set_quit() mod = __import__(sys.calibre_module, fromlist=[1]) func = getattr(mod, sys.calibre_function) return func() if __name__ == '__main__': main()
1,362
Python
.py
34
35.5
81
0.686692
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,388
make_ico_files.py
kovidgoyal_calibre/icons/make_ico_files.py
#!/usr/bin/env python # vim:fileencoding=utf-8 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import shutil import subprocess import sys d, j, a = (getattr(os.path, x) for x in ('dirname', 'join', 'abspath')) base = d(a(__file__)) os.chdir(base) imgsrc = j(d(base), 'imgsrc') sources = {'library':j(imgsrc, 'calibre.svg'), 'ebook-edit':j(imgsrc, 'tweak.svg'), 'viewer':j(imgsrc, 'viewer.svg'), 'favicon':j(imgsrc, 'calibre.svg')} if sys.argv[-1] == 'only-logo': sources = {'library':sources['library']} for name, src in sources.items(): os.mkdir('ico_temp') try: names = [] for sz in (16, 24, 32, 48, 64, 256): iname = os.path.join('ico_temp', '{0}x{0}.png'.format(sz)) subprocess.check_call(['rsvg-convert', src, '-w', str(sz), '-h', str(sz), '-o', iname]) subprocess.check_call(['optipng', '-o7', '-strip', 'all', iname]) if sz >= 128: names.append('-r') # store as raw PNG to reduce size else: names.extend(['-t', '0']) # see https://bugzilla.gnome.org/show_bug.cgi?id=755200 names.append(iname) subprocess.check_call(['icotool', '-c', '--output=' + name+'.ico'] + names) finally: shutil.rmtree('ico_temp')
1,318
Python
.py
31
36.419355
153
0.581577
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,389
make_iconsets.py
kovidgoyal_calibre/icons/icns/make_iconsets.py
#!/usr/bin/env python # vim:fileencoding=utf-8 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import shutil import subprocess import sys d, j, a = (getattr(os.path, x) for x in ('dirname', 'join', 'abspath')) base = d(a(__file__)) os.chdir(base) imgsrc = j(d(d(base)), 'imgsrc') sources = {'calibre':j(imgsrc, 'calibre.svg'), 'ebook-edit':j(imgsrc, 'tweak.svg'), 'ebook-viewer':j(imgsrc, 'viewer.svg'), 'book':j(imgsrc, 'book.svg')} if sys.argv[-1] == 'only-logo': sources = {'calibre':sources['calibre']} for name, src in sources.items(): iconset = name + '.iconset' if os.path.exists(iconset): shutil.rmtree(iconset) os.mkdir(iconset) os.chdir(iconset) try: for sz in (16, 32, 128, 256, 512, 1024): iname = 'icon_{0}x{0}.png'.format(sz) iname2x = 'icon_{0}x{0}@2x.png'.format(sz // 2) if src.endswith('.svg'): subprocess.check_call(['rsvg-convert', src, '-w', str(sz), '-h', str(sz), '-o', iname]) else: # We have a 512x512 png image if sz == 512: shutil.copy2(src, iname) else: subprocess.check_call(['convert', src, '-resize', '{0}x{0}'.format(sz), iname]) if sz > 16: shutil.copy2(iname, iname2x) if sz > 512: os.remove(iname) for name in (iname, iname2x): if os.path.exists(name): subprocess.check_call(['optipng', '-o7', '-strip', 'all', name]) finally: os.chdir('..')
1,638
Python
.py
42
30.52381
153
0.544025
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,390
template_ref_generate.py
kovidgoyal_calibre/manual/template_ref_generate.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' import re from collections import defaultdict PREAMBLE = '''\ .. _templaterefcalibre-{}: Reference for all built-in template language functions ======================================================== Here, we document all the built-in functions available in the calibre template language. Every function is implemented as a class in python and you can click the source links to see the source code, in case the documentation is insufficient. The functions are arranged in logical groups by type. .. contents:: :depth: 2 :local: .. module:: calibre.utils.formatter_functions ''' CATEGORY_TEMPLATE = '''\ {category} {dashes} ''' FUNCTION_TEMPLATE = '''\ {fs} {hats} .. autoclass:: {cn} ''' POSTAMBLE = '''\ API of the Metadata objects ---------------------------- The python implementation of the template functions is passed in a Metadata object. Knowing it's API is useful if you want to define your own template functions. .. module:: calibre.ebooks.metadata.book.base .. autoclass:: Metadata :members: :member-order: bysource .. data:: STANDARD_METADATA_FIELDS The set of standard metadata fields. .. literalinclude:: ../../../src/calibre/ebooks/metadata/book/__init__.py :lines: 7- ''' def generate_template_language_help(language): from calibre.utils.formatter_functions import formatter_functions pat = re.compile(r'\)`{0,2}\s*-{1,2}') funcs = defaultdict(dict) for func in formatter_functions().get_builtins().values(): class_name = func.__class__.__name__ func_sig = getattr(func, 'doc') m = pat.search(func_sig) if m is None: print('No signature for template function ', class_name) continue func_sig = func_sig[:m.start()+1].strip('`') func_cat = getattr(func, 'category') funcs[func_cat][func_sig] = class_name output = PREAMBLE.format(language) cats = sorted(funcs.keys()) for cat in cats: output += CATEGORY_TEMPLATE.format(category=cat, dashes='-'*len(cat)) entries = [k for k in sorted(funcs[cat].keys())] for entry in entries: output += FUNCTION_TEMPLATE.format(fs=entry, cn=funcs[cat][entry], hats='^'*len(entry)) output += POSTAMBLE return output if __name__ == '__main__': generate_template_language_help()
2,539
Python
.py
69
32.130435
78
0.65383
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,391
conf.py
kovidgoyal_calibre/manual/conf.py
# -*- coding: utf-8 -*- # # calibre documentation build configuration file, created by # sphinx-quickstart.py on Sun Mar 23 01:23:55 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import errno import os import sys from datetime import date # If your extensions are in another directory, add it here. base = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(base)) from setup import __appname__, __version__ sys.path.append(base) import calibre.utils.img as cimg import custom from calibre.utils.localization import localize_website_link del sys.path[0] custom, cimg # General configuration # --------------------- needs_sphinx = '1.2' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'custom', 'sidebar_toc', 'sphinx.ext.viewcode', 'sphinx.ext.extlinks'] # Add any paths that contain templates here, relative to this directory. templates_path = ['templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' if tags.has('online') else 'simple_index' # noqa # kill the warning about index/simple_index not being in a toctree exclude_patterns = ['simple_index.rst'] if master_doc == 'index' else ['index.rst'] exclude_patterns.append('cli-options-header.rst') if tags.has('gettext'): # noqa # Do not exclude anything as the strings must be translated. This will # generate a warning about the documents not being in a toctree, just ignore # it. exclude_patterns = [] # The language language = os.environ.get('CALIBRE_OVERRIDE_LANG', 'en') def generated_langs(): try: return os.listdir(os.path.join(base, 'generated')) except EnvironmentError as e: if e.errno != errno.ENOENT: raise return () # ignore generated files in languages other than the language we are building for ge = {'generated/' + x for x in generated_langs()} | { 'generated/' + x for x in os.environ.get('ALL_USER_MANUAL_LANGUAGES', '').split()} ge.discard('generated/' + language) exclude_patterns += list(ge) del ge # General substitutions. project = __appname__ copyright = 'Kovid Goyal' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = __version__ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. unused_docs = ['global', 'cli/global'] locale_dirs = ['locale/'] title = '%s User Manual' % __appname__ needs_localization = language not in {'en', 'eng'} if needs_localization: import gettext try: t = gettext.translation('simple_index', locale_dirs[0], [language]) except IOError: pass else: title = t.gettext(title) # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_theme = 'alabaster' html_sidebars = { '**': [ 'about.html', 'searchbox.html', 'localtoc.html', 'relations.html', ] } html_theme_options = { 'logo': 'logo.png', 'show_powered_by': False, 'fixed_sidebar': True, 'sidebar_collapse': True, 'github_button': False, } # The favicon html_favicon = '../icons/favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the built-in static files, # so a file named "default.css" will overwrite the built-in "default.css". html_static_path = ['resources', '../icons/favicon.ico'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Overall title of the documentation # html_title = title html_short_title = _('Start') from calibre.utils.localization import get_language html_context = {} html_context['other_languages'] = [ (lc, get_language(lc)) for lc in os.environ.get('ALL_USER_MANUAL_LANGUAGES', '').split() if lc != language] def sort_languages(x): from calibre.utils.icu import sort_key lc, name = x if lc == language: return '' return sort_key(type(u'')(name)) website = 'https://calibre-ebook.com' html_context['other_languages'].sort(key=sort_languages) html_context['support_text'] = _('Support calibre') html_context['support_tooltip'] = _('Contribute to support calibre development') html_context['homepage_url'] = website if needs_localization: html_context['homepage_url'] = localize_website_link(html_context['homepage_url']) extlinks = { 'website_base': (f'{website}/%s', None), 'website': (html_context['homepage_url'] + '/%s', None), 'download_file': (f'{website}/downloads/%s', '%s'), } del sort_languages, get_language epub_author = u'Kovid Goyal' epub_publisher = u'Kovid Goyal' epub_copyright = u'© {} Kovid Goyal'.format(date.today().year) epub_description = u'Comprehensive documentation for calibre' epub_identifier = u'https://manual.calibre-ebook.com' epub_scheme = u'url' epub_uid = u'S54a88f8e9d42455e9c6db000e989225f' epub_tocdepth = 4 epub_tocdup = True epub_cover = ('epub_cover.jpg', 'epub_cover_template.html') suppress_warnings = ['epub.duplicated_toc_entry'] # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} html_use_modindex = False html_use_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'calibredoc' html_use_opensearch = 'https://manual.calibre-ebook.com' html_show_sphinx = False # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [(master_doc, 'calibre.tex', title, 'Kovid Goyal', 'manual', False)] # Additional stuff for the LaTeX preamble. # latex_preamble = '' # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_use_modindex = True # we use lualatex as it is actively maintained and pdflatex and xelatex fail # to render smart quotes and dashes latex_engine = 'lualatex' latex_logo = 'resources/logo.png' latex_show_pagerefs = True latex_show_urls = 'footnote' latex_elements = { 'papersize':'letterpaper', 'preamble': r'\renewcommand{\pageautorefname}{%s}' % _('page'), }
8,063
Python
.py
204
37.220588
111
0.716592
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,392
sidebar_toc.py
kovidgoyal_calibre/manual/sidebar_toc.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from itertools import count from docutils import nodes from sphinx.environment.adapters.toctree import TocTree id_counter = count() ID = 'sidebar-collapsible-toc' CSS = r''' ID li { list-style: none; margin-left: 0; padding-left: 0.2em; text-indent: -0.7em; } ID li.leaf-node { text-indent: 0; } ID li input[type=checkbox] { display: none; } ID li > label { cursor: pointer; } ID li > input[type=checkbox] ~ ul > li { display: none; } ID li > input[type=checkbox]:checked ~ ul > li { display: block; } ID li > input[type=checkbox]:checked + label:before { content: "\025bf"; } ID li > input[type=checkbox]:not(:checked) + label:before { content: "\025b8"; } '''.replace('ID', 'ul#' + ID) class checkbox(nodes.Element): pass def visit_checkbox(self, node): cid = node['ids'][0] node['classes'] = [] self.body.append('<input id="{0}" type="checkbox" />' '<label for="{0}">&nbsp;</label>'.format(cid)) def modify_li(li): sublist = li.first_child_matching_class(nodes.bullet_list) if sublist is None or li[sublist].first_child_matching_class(nodes.list_item) is None: if not li.get('classes'): li['classes'] = [] li['classes'].append('leaf-node') else: c = checkbox() c['ids'] = ['collapse-checkbox-{}'.format(next(id_counter))] li.insert(0, c) def create_toc(app, pagename): tt = TocTree(app.env) toctree = tt.get_toc_for(pagename, app.builder) if toctree is not None: subtree = toctree[toctree.first_child_matching_class(nodes.list_item)] bl = subtree.first_child_matching_class(nodes.bullet_list) if bl is None: return # Empty ToC subtree = subtree[bl] for li in subtree.traverse(nodes.list_item): modify_li(li) subtree['ids'] = [ID] return '<style>' + CSS + '</style>' + app.builder.render_partial( subtree)['fragment'] def add_html_context(app, pagename, templatename, context, *args): if 'toc' in context: context['toc'] = create_toc(app, pagename) or context['toc'] def setup(app): app.add_node(checkbox, html=(visit_checkbox, lambda *x: None)) app.connect('html-page-context', add_html_context)
2,365
Python
.py
73
27.39726
90
0.638167
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,393
custom.py
kovidgoyal_calibre/manual/custom.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> import os import re from functools import partial from calibre.linux import cli_index_strings, entry_points from epub import EPUBHelpBuilder from sphinx.util.console import bold from sphinx.util.logging import getLogger def info(*a): getLogger(__name__).info(*a) include_pat = re.compile(r'^.. include:: (\S+.rst)', re.M) def source_read_handler(app, docname, source): src = source[0] if app.builder.name != 'gettext' and app.config.language != 'en': src = re.sub(r'(\s+generated/)en/', r'\1' + app.config.language + '/', src) # Sphinx does not call source_read_handle for the .. include directive for m in reversed(tuple(include_pat.finditer(src))): included_doc_name = m.group(1).lstrip('/') ss = [open(included_doc_name, 'rb').read().decode('utf-8')] source_read_handler(app, included_doc_name.partition('.')[0], ss) src = src[:m.start()] + ss[0] + src[m.end():] source[0] = src CLI_INDEX=''' .. _cli: %s ========================================================= .. image:: ../../images/cli.png .. note:: %s %s -------------------------------------- .. toctree:: :maxdepth: 1 {documented} %s ---------------------------------------- {undocumented} %s ''' CLI_PREAMBLE='''\ .. _{cmdref}: .. raw:: html <style>code {{font-size: 1em; background-color: transparent; font-family: sans-serif }}</style> ``{cmd}`` =================================================================== .. code-block:: none {cmdline} {usage} ''' def titlecase(language, x): if x and language == 'en': from calibre.utils.titlecase import titlecase as tc x = tc(x) return x def generate_calibredb_help(preamble, language): from calibre.db.cli.main import COMMANDS, get_parser, option_parser_for preamble = preamble[:preamble.find('\n\n\n', preamble.find('code-block'))] preamble += '\n\n' preamble += _('''\ :command:`calibredb` is the command line interface to the calibre database. It has several sub-commands, documented below. :command:`calibredb` can be used to manipulate either a calibre database specified by path or a calibre :guilabel:`Content server` running either on the local machine or over the internet. You can start a calibre :guilabel:`Content server` using either the :command:`calibre-server` program or in the main calibre program click :guilabel:`Connect/share -> Start Content server`. Since :command:`calibredb` can make changes to your calibre libraries, you must setup authentication on the server first. There are two ways to do that: * If you plan to connect only to a server running on the same computer, you can simply use the ``--enable-local-write`` option of the Content server, to allow any program, including calibredb, running on the local computer to make changes to your calibre data. When running the server from the main calibre program, this option is in :guilabel:`Preferences->Sharing over the net->Advanced`. * If you want to enable access over the internet, then you should setup user accounts on the server and use the :option:`--username` and :option:`--password` options to :command:`calibredb` to give it access. You can setup user authentication for :command:`calibre-server` by using the ``--enable-auth`` option and using ``--manage-users`` to create the user accounts. If you are running the server from the main calibre program, use :guilabel:`Preferences->Sharing over the net->Require username/password`. To connect to a running Content server, pass the URL of the server to the :option:`--with-library` option, see the documentation of that option for details and examples. ''') global_parser = get_parser('') groups = [] for grp in global_parser.option_groups: groups.append((titlecase(language, grp.title), grp.description, grp.option_list)) global_options = '\n'.join(render_options('calibredb', groups, False, False)) lines = [] for cmd in COMMANDS: parser = option_parser_for(cmd)() lines += ['.. _calibredb-%s-%s:' % (language, cmd), ''] lines += [cmd, '~'*20, ''] usage = parser.usage.strip() usage = [i for i in usage.replace('%prog', 'calibredb').splitlines()] cmdline = ' '+usage[0] usage = usage[1:] usage = [re.sub(r'(%s)([^a-zA-Z0-9])'%cmd, r':command:`\1`\2', i) for i in usage] lines += ['.. code-block:: none', '', cmdline, ''] lines += usage groups = [(None, None, parser.option_list)] lines += [''] lines += render_options('calibredb '+cmd, groups, False) lines += [''] for group in parser.option_groups: if not getattr(group, 'is_global_options', False): lines.extend(render_options( 'calibredb_' + cmd, [[titlecase(language, group.title), group.description, group.option_list]], False, False, header_level='^')) lines += [''] raw = preamble + '\n\n'+'.. contents::\n :local:'+ '\n\n' + global_options+'\n\n'+'\n'.join(lines) update_cli_doc('calibredb', raw, language) def generate_ebook_convert_help(preamble, app): from calibre.customize.ui import input_format_plugins, output_format_plugins from calibre.ebooks.conversion.cli import create_option_parser, manual_index_strings from calibre.utils.logging import default_log preamble = re.sub(r'http.*\.html', ':ref:`conversion`', preamble) raw = preamble + '\n\n' + manual_index_strings() % 'ebook-convert myfile.input_format myfile.output_format -h' parser, plumber = create_option_parser(['ebook-convert', 'dummyi.mobi', 'dummyo.epub', '-h'], default_log) groups = [(None, None, parser.option_list)] for grp in parser.option_groups: if grp.title not in {'INPUT OPTIONS', 'OUTPUT OPTIONS'}: groups.append((titlecase(app, grp.title), grp.description, grp.option_list)) options = '\n'.join(render_options('ebook-convert', groups, False)) raw += '\n\n.. contents::\n :local:' raw += '\n\n' + options for pl in sorted(input_format_plugins(), key=lambda x: x.name): parser, plumber = create_option_parser(['ebook-convert', 'dummyi.'+sorted(pl.file_types)[0], 'dummyo.epub', '-h'], default_log) groups = [(pl.name+ ' Options', '', g.option_list) for g in parser.option_groups if g.title == "INPUT OPTIONS"] prog = 'ebook-convert-'+(pl.name.lower().replace(' ', '-')) raw += '\n\n' + '\n'.join(render_options(prog, groups, False, True)) for pl in sorted(output_format_plugins(), key=lambda x: x.name): parser, plumber = create_option_parser(['ebook-convert', 'd.epub', 'dummyi.'+pl.file_type, '-h'], default_log) groups = [(pl.name+ ' Options', '', g.option_list) for g in parser.option_groups if g.title == "OUTPUT OPTIONS"] prog = 'ebook-convert-'+(pl.name.lower().replace(' ', '-')) raw += '\n\n' + '\n'.join(render_options(prog, groups, False, True)) update_cli_doc('ebook-convert', raw, app) def update_cli_doc(name, raw, language): if isinstance(raw, bytes): raw = raw.decode('utf-8') path = 'generated/%s/%s.rst' % (language, name) old_raw = open(path, encoding='utf-8').read() if os.path.exists(path) else '' if not os.path.exists(path) or old_raw != raw: import difflib print(path, 'has changed') if old_raw: lines = difflib.unified_diff(old_raw.splitlines(), raw.splitlines(), path, path) for line in lines: print(line) info('creating '+os.path.splitext(os.path.basename(path))[0]) p = os.path.dirname(path) if p and not os.path.exists(p): os.makedirs(p) open(path, 'wb').write(raw.encode('utf-8')) def render_options(cmd, groups, options_header=True, add_program=True, header_level='~'): lines = [''] if options_header: lines = [_('[options]'), '-'*40, ''] if add_program: lines += ['.. program:: '+cmd, ''] for title, desc, options in groups: if title: lines.extend([title, header_level * (len(title) + 4)]) lines.append('') if desc: lines.extend([desc, '']) for opt in sorted(options, key=lambda x: x.get_opt_string()): help = opt.help or '' help = help.replace('\n', ' ').replace('*', '\\*').replace('%default', str(opt.default)) help = help.replace('"', r'\ ``"``\ ') help = help.replace("'", r"\ ``'``\ ") help = mark_options(help) opt_strings = (x.strip() for x in tuple(opt._long_opts or ()) + tuple(opt._short_opts or ())) opt = '.. option:: ' + ', '.join(opt_strings) lines.extend([opt, '', ' '+help, '']) return lines def mark_options(raw): raw = re.sub(r'(\s+)--(\s+)', u'\\1``--``\\2', raw) def sub(m): opt = m.group() a, b = opt.partition('=')[::2] if a in ('--option1', '--option2'): return '``' + m.group() + '``' a = ':option:`' + a + '`' b = (' = ``' + b + '``') if b else '' return a + b raw = re.sub(r'(--[|()a-zA-Z0-9_=,-]+)', sub, raw) return raw def get_cli_docs(): documented_cmds = [] undocumented_cmds = [] for script in entry_points['console_scripts'] + entry_points['gui_scripts']: module = script[script.index('=')+1:script.index(':')].strip() cmd = script[:script.index('=')].strip() if cmd in ('calibre-complete', 'calibre-parallel'): continue module = __import__(module, fromlist=[module.split('.')[-1]]) if hasattr(module, 'option_parser'): try: documented_cmds.append((cmd, getattr(module, 'option_parser')())) except TypeError: documented_cmds.append((cmd, getattr(module, 'option_parser')(cmd))) else: undocumented_cmds.append(cmd) return documented_cmds, undocumented_cmds def cli_docs(language): info(bold('creating CLI documentation...')) documented_cmds, undocumented_cmds = get_cli_docs() documented_cmds.sort(key=lambda x: x[0]) undocumented_cmds.sort() documented = [' '*4 + c[0] for c in documented_cmds] undocumented = [' * ' + c for c in undocumented_cmds] raw = (CLI_INDEX % cli_index_strings()[:5]).format(documented='\n'.join(documented), undocumented='\n'.join(undocumented)) if not os.path.exists('cli'): os.makedirs('cli') update_cli_doc('cli-index', raw, language) for cmd, parser in documented_cmds: usage = [mark_options(i) for i in parser.usage.replace('%prog', cmd).splitlines()] cmdline = usage[0] usage = usage[1:] usage = [i.replace(cmd, ':command:`%s`'%cmd) for i in usage] usage = '\n'.join(usage) preamble = CLI_PREAMBLE.format(cmd=cmd, cmdref=cmd + '-' + language, cmdline=cmdline, usage=usage) if cmd == 'ebook-convert': generate_ebook_convert_help(preamble, language) elif cmd == 'calibredb': generate_calibredb_help(preamble, language) else: groups = [(None, None, parser.option_list)] for grp in parser.option_groups: groups.append((grp.title, grp.description, grp.option_list)) raw = preamble lines = render_options(cmd, groups) raw += '\n'+'\n'.join(lines) update_cli_doc(cmd, raw, language) def generate_docs(language): cli_docs(language) template_docs(language) def template_docs(language): from template_ref_generate import generate_template_language_help raw = generate_template_language_help(language) update_cli_doc('template_ref', raw, language) def localized_path(app, langcode, pagename): href = app.builder.get_target_uri(pagename) href = re.sub(r'generated/[a-z]+/', 'generated/%s/' % langcode, href) prefix = '/' if langcode != 'en': prefix += langcode + '/' return prefix + href def add_html_context(app, pagename, templatename, context, *args): context['localized_path'] = partial(localized_path, app) context['change_language_text'] = cli_index_strings()[5] context['search_box_text'] = cli_index_strings()[6] def guilabel_role(typ, rawtext, text, *args, **kwargs): from sphinx.roles import GUILabel text = text.replace(u'->', u'\N{THIN SPACE}\N{RIGHTWARDS ARROW}\N{THIN SPACE}') return GUILabel()(typ, rawtext, text, *args, **kwargs) def setup_man_pages(app): documented_cmds = get_cli_docs()[0] man_pages = [] for cmd, option_parser in documented_cmds: path = 'generated/%s/%s' % (app.config.language, cmd) man_pages.append(( path, cmd, cmd, 'Kovid Goyal', 1 )) app.config['man_pages'] = man_pages def setup(app): from docutils.parsers.rst import roles setup_man_pages(app) generate_docs(app.config.language) app.add_css_file('custom.css') app.add_builder(EPUBHelpBuilder) app.connect('source-read', source_read_handler) app.connect('html-page-context', add_html_context) app.connect('build-finished', finished) roles.register_local_role('guilabel', guilabel_role) def finished(app, exception): pass
13,611
Python
.py
289
40.33564
148
0.616441
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,394
epub.py
kovidgoyal_calibre/manual/epub.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from calibre.ebooks.oeb.base import OPF from calibre.ebooks.oeb.polish.check.links import UnreferencedResource, check_links from calibre.ebooks.oeb.polish.container import OEB_DOCS, get_container from calibre.ebooks.oeb.polish.pretty import pretty_html_tree, pretty_opf from calibre.utils.imghdr import identify from sphinx.builders.epub3 import Epub3Builder as EpubBuilder from polyglot.builtins import iteritems class EPUBHelpBuilder(EpubBuilder): name = 'myepub' def build_epub(self, outdir=None, outname=None): if outdir: EpubBuilder.build_epub(self, outdir, outname) else: EpubBuilder.build_epub(self) outdir = self.outdir outname = self.config.epub_basename + '.epub' container = get_container(os.path.join(outdir, outname)) self.fix_epub(container) container.commit() def fix_epub(self, container): ' Fix all the brokenness that sphinx\'s epub builder creates ' for name, mt in iteritems(container.mime_map): if mt in OEB_DOCS: self.workaround_ade_quirks(container, name) pretty_html_tree(container, container.parsed(name)) container.dirty(name) self.fix_opf(container) def workaround_ade_quirks(self, container, name): root = container.parsed(name) # ADE blows up floating images if their sizes are not specified for img in root.xpath('//*[local-name() = "img" and (@class = "float-right-img" or @class = "float-left-img")]'): if 'style' not in img.attrib: imgname = container.href_to_name(img.get('src'), name) fmt, width, height = identify(container.raw_data(imgname)) if width == -1: raise ValueError('Failed to read size of: %s' % imgname) img.set('style', 'width: %dpx; height: %dpx' % (width, height)) def fix_opf(self, container): spine_names = {n for n, l in container.spine_names} spine = container.opf_xpath('//opf:spine')[0] rmap = {v:k for k, v in iteritems(container.manifest_id_map)} # Add unreferenced text files to the spine for name, mt in iteritems(container.mime_map): if mt in OEB_DOCS and name not in spine_names: spine_names.add(name) container.insert_into_xml(spine, spine.makeelement(OPF('itemref'), idref=rmap[name])) # Remove duplicate entries from spine seen = set() for item, name, linear in container.spine_iter: if name in seen: container.remove_from_xml(item) seen.add(name) # Remove the <guide> which is not needed in EPUB 3 for guide in container.opf_xpath('//*[local-name()="guide"]'): guide.getparent().remove(guide) # Ensure that the cover-image property is set cover_id = rmap['_static/' + self.config.epub_cover[0]] for item in container.opf_xpath('//opf:item[@id="{}"]'.format(cover_id)): item.set('properties', 'cover-image') for item in container.opf_xpath('//opf:item[@href="epub-cover.xhtml"]'): item.set('properties', 'svg calibre:title-page') for item in container.opf_xpath('//opf:package'): prefix = item.get('prefix') or '' if prefix: prefix += ' ' item.set('prefix', prefix + 'calibre: https://calibre-ebook.com') # Remove any <meta cover> tag as it is not needed in epub 3 for meta in container.opf_xpath('//opf:meta[@name="cover"]'): meta.getparent().remove(meta) # Remove unreferenced files for error in check_links(container): if error.__class__ is UnreferencedResource: container.remove_item(error.name) # Pretty print the OPF pretty_opf(container.parsed(container.opf_name)) container.dirty(container.opf_name)
4,196
Python
.py
82
41.426829
121
0.631926
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,395
build.py
kovidgoyal_calibre/manual/build.py
#!/usr/bin/env python # vim:fileencoding=utf-8 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import shutil import subprocess import sys import tempfile from functools import partial j, d, a = os.path.join, os.path.dirname, os.path.abspath BASE = d(a(__file__)) SPHINX_BUILD = ['sphinx-build'] sys.path.insert(0, d(BASE)) from setup import __appname__, __version__ sys.path.remove(d(BASE)) from calibre.ebooks.oeb.polish.container import epub_to_azw3 def sphinx_build(language, base, builder='html', bdir='html', t=None, quiet=True, very_quiet=False): destdir = j(base, bdir) if not os.path.exists(destdir): os.makedirs(destdir) ans = SPHINX_BUILD + ['-D', ('language=' + language), '-b', builder] if quiet: ans.append('-q') if very_quiet: ans.append('-Q') if builder == 'html': ans += ['-w', j(destdir, 'sphinx-build-warnings.txt')] if t: ans += ['-t', t] ans += ['-d', j(base, 'doctrees'), BASE, destdir] print(' '.join(ans)) subprocess.check_call(ans) return destdir def build_manual(language, base): sb = partial(sphinx_build, language, base) onlinedir = sb(t='online') epubdir = sb('myepub', 'epub') pdf_ok = language not in ('ja',) if pdf_ok: latexdir = sb('latex', 'latex') pwd = os.getcwd() os.chdir(latexdir) def run_cmd(cmd): p = subprocess.Popen(cmd, stdout=open(os.devnull, 'wb'), stdin=subprocess.PIPE) p.stdin.close() return p.wait() try: for i in range(3): run_cmd(['xelatex', '-interaction=nonstopmode', 'calibre.tex']) run_cmd(['makeindex', '-s', 'python.ist', 'calibre.idx']) for i in range(2): run_cmd(['xelatex', '-interaction=nonstopmode', 'calibre.tex']) if not os.path.exists('calibre.pdf'): print('Failed to build pdf file, see calibre.log in the latex directory', file=sys.stderr) raise SystemExit(1) finally: os.chdir(pwd) pdf_dest = j(onlinedir, 'calibre.pdf') shutil.copyfile(j(latexdir, 'calibre.pdf'), pdf_dest) epub_dest = j(onlinedir, 'calibre.epub') shutil.copyfile(j(epubdir, 'calibre.epub'), epub_dest) epub_to_azw3(epub_dest) def build_pot(base): cmd = SPHINX_BUILD + ['-b', 'gettext', '-t', 'online', '-t', 'gettext', '.', base] print(' '.join(cmd)) subprocess.check_call(cmd) os.remove(j(base, 'generated.pot')) return base def build_linkcheck(base): cmd = SPHINX_BUILD + ['-b', 'linkcheck', '-t', 'online', '-t', 'linkcheck', '.', base] print(' '.join(cmd)) subprocess.check_call(cmd) return base def build_man_pages(language, base): os.environ['CALIBRE_BUILD_MAN_PAGES'] = '1' sphinx_build(language, base, builder='man', bdir=language, very_quiet=True) if __name__ == '__main__': import argparse os.chdir(d(a(__file__))) os.environ['__appname__'] = __appname__ os.environ['__version__'] = __version__ if len(sys.argv) == 1: base = j(tempfile.gettempdir(), 'manual') os.environ['CALIBRE_OVERRIDE_LANG'] = language = 'en' if 'ALL_USER_MANUAL_LANGUAGES' not in os.environ: import json os.environ['ALL_USER_MANUAL_LANGUAGES'] = ' '.join(json.load(open('locale/completed.json', 'rb'))) sphinx_build(language, base, t='online', quiet=False) print('Manual built in', j(base, 'html')) else: p = argparse.ArgumentParser() p.add_argument('language', help='The language to build for') p.add_argument('base', help='The destination directory') p.add_argument('--man-pages', default=False, action='store_true', help='Build man pages') p.add_argument('--quiet', default=False, action='store_true', help='Suppress warnings') args = p.parse_args() language, base = args.language, args.base if language == 'gettext': build_pot(base) elif language == 'linkcheck': build_linkcheck(base) elif args.man_pages: os.environ['CALIBRE_OVERRIDE_LANG'] = language build_man_pages(language, base) else: os.environ['CALIBRE_OVERRIDE_LANG'] = language build_manual(language, base) print('Manual for', language, 'built in', j(base, 'html'))
4,459
Python
.py
109
33.825688
110
0.607019
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,396
__init__.py
kovidgoyal_calibre/manual/plugin_examples/helloworld/__init__.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from calibre.customize import FileTypePlugin class HelloWorld(FileTypePlugin): name = 'Hello World Plugin' # Name of the plugin description = 'Set the publisher to Hello World for all new conversions' supported_platforms = ['windows', 'osx', 'linux'] # Platforms this plugin will run on author = 'Acme Inc.' # The author of this plugin version = (1, 0, 0) # The version number of this plugin file_types = {'epub', 'mobi'} # The file types that this plugin will be applied to on_postprocess = True # Run this plugin after conversion is complete minimum_calibre_version = (0, 7, 53) def run(self, path_to_ebook): from calibre.ebooks.metadata.meta import get_metadata, set_metadata with open(path_to_ebook, 'r+b') as file: ext = os.path.splitext(path_to_ebook)[-1][1:].lower() mi = get_metadata(file, ext) mi.publisher = 'Hello World' set_metadata(file, mi, ext) return path_to_ebook
1,267
Python
.py
24
46.958333
95
0.639676
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,397
__init__.py
kovidgoyal_calibre/manual/plugin_examples/editor_demo/__init__.py
#!/usr/bin/env python # vim:fileencoding=utf-8 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from calibre.customize import EditBookToolPlugin class DemoPlugin(EditBookToolPlugin): name = 'Edit Book plugin demo' version = (1, 0, 0) author = 'Kovid Goyal' supported_platforms = ['windows', 'osx', 'linux'] description = 'A demonstration of the plugin interface for the ebook editor' minimum_calibre_version = (1, 46, 0)
487
Python
.py
12
37.083333
80
0.712154
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,398
main.py
kovidgoyal_calibre/manual/plugin_examples/editor_demo/main.py
#!/usr/bin/env python # vim:fileencoding=utf-8 __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re from calibre import force_unicode from calibre.ebooks.oeb.polish.container import OEB_DOCS, OEB_STYLES, serialize from calibre.gui2 import error_dialog # The base class that all tools must inherit from from calibre.gui2.tweak_book.plugin import Tool from css_parser.css import CSSRule from qt.core import QAction, QInputDialog class DemoTool(Tool): #: Set this to a unique name it will be used as a key name = 'demo-tool' #: If True the user can choose to place this tool in the plugins toolbar allowed_in_toolbar = True #: If True the user can choose to place this tool in the plugins menu allowed_in_menu = True def create_action(self, for_toolbar=True): # Create an action, this will be added to the plugins toolbar and # the plugins menu ac = QAction(get_icons('images/icon.png'), 'Magnify fonts', self.gui) # noqa if not for_toolbar: # Register a keyboard shortcut for this toolbar action. We only # register it for the action created for the menu, not the toolbar, # to avoid a double trigger self.register_shortcut(ac, 'magnify-fonts-tool', default_keys=('Ctrl+Shift+Alt+D',)) ac.triggered.connect(self.ask_user) return ac def ask_user(self): # Ask the user for a factor by which to multiply all font sizes factor, ok = QInputDialog.getDouble( self.gui, 'Enter a magnification factor', 'Allow font sizes in the book will be multiplied by the specified factor', value=2, min=0.1, max=4 ) if ok: # Ensure any in progress editing the user is doing is present in the container self.boss.commit_all_editors_to_container() try: self.magnify_fonts(factor) except Exception: # Something bad happened report the error to the user import traceback error_dialog(self.gui, _('Failed to magnify fonts'), _( 'Failed to magnify fonts, click "Show details" for more info'), det_msg=traceback.format_exc(), show=True) # Revert to the saved restore point self.boss.revert_requested(self.boss.global_undo.previous_container) else: # Show the user what changes we have made, allowing her to # revert them if necessary self.boss.show_current_diff() # Update the editor UI to take into account all the changes we # have made self.boss.apply_container_update_to_gui() def magnify_fonts(self, factor): # Magnify all font sizes defined in the book by the specified factor # First we create a restore point so that the user can undo all changes # we make. self.boss.add_savepoint('Before: Magnify fonts') container = self.current_container # The book being edited as a container object # Iterate over all style declarations in the book, this means css # stylesheets, <style> tags and style="" attributes for name, media_type in container.mime_map.items(): if media_type in OEB_STYLES: # A stylesheet. Parsed stylesheets are css_parser CSSStylesheet # objects. self.magnify_stylesheet(container.parsed(name), factor) container.dirty(name) # Tell the container that we have changed the stylesheet elif media_type in OEB_DOCS: # A HTML file. Parsed HTML files are lxml elements for style_tag in container.parsed(name).xpath('//*[local-name="style"]'): if style_tag.text and style_tag.get('type', None) in {None, 'text/css'}: # We have an inline CSS <style> tag, parse it into a # stylesheet object sheet = container.parse_css(style_tag.text) self.magnify_stylesheet(sheet, factor) style_tag.text = serialize(sheet, 'text/css', pretty_print=True) container.dirty(name) # Tell the container that we have changed the stylesheet for elem in container.parsed(name).xpath('//*[@style]'): # Process inline style attributes block = container.parse_css(elem.get('style'), is_declaration=True) self.magnify_declaration(block, factor) elem.set('style', force_unicode(block.getCssText(separator=' '), 'utf-8')) def magnify_stylesheet(self, sheet, factor): # Magnify all fonts in the specified stylesheet by the specified # factor. for rule in sheet.cssRules.rulesOfType(CSSRule.STYLE_RULE): self.magnify_declaration(rule.style, factor) def magnify_declaration(self, style, factor): # Magnify all fonts in the specified style declaration by the specified # factor val = style.getPropertyValue('font-size') if not val: return # see if the font-size contains a number num = re.search(r'[0-9.]+', val) if num is not None: num = num.group() val = val.replace(num, '%f' % (float(num) * factor)) style.setProperty('font-size', val) # We should also be dealing with the font shorthand property and # font sizes specified as non numbers, but those are left as exercises # for the reader
5,704
Python
.py
105
42.714286
128
0.625515
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,399
ui.py
kovidgoyal_calibre/manual/plugin_examples/interface_demo/ui.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' if False: # This is here to keep my python error checker from complaining about # the builtin functions that will be defined by the plugin loading system # You do not need this code in your plugins get_icons = get_resources = None # The class that all interface action plugins must inherit from from calibre.gui2.actions import InterfaceAction from calibre_plugins.interface_demo.main import DemoDialog class InterfacePlugin(InterfaceAction): name = 'Interface Plugin Demo' # Declare the main action associated with this plugin # The keyboard shortcut can be None if you dont want to use a keyboard # shortcut. Remember that currently calibre has no central management for # keyboard shortcuts, so try to use an unusual/unused shortcut. action_spec = ('Interface Plugin Demo', None, 'Run the Interface Plugin Demo', 'Ctrl+Shift+F1') def genesis(self): # This method is called once per plugin, do initial setup here # Set the icon for this interface action # The get_icons function is a builtin function defined for all your # plugin code. It loads icons from the plugin zip file. It returns # QIcon objects, if you want the actual data, use the analogous # get_resources builtin function. # # Note that if you are loading more than one icon, for performance, you # should pass a list of names to get_icons. In this case, get_icons # will return a dictionary mapping names to QIcons. Names that # are not found in the zip file will result in null QIcons. icon = get_icons('images/icon.png', 'Interface Demo Plugin') # The qaction is automatically created from the action_spec defined # above self.qaction.setIcon(icon) self.qaction.triggered.connect(self.show_dialog) def show_dialog(self): # The base plugin object defined in __init__.py base_plugin_object = self.interface_action_base_plugin # Show the config dialog # The config dialog can also be shown from within # Preferences->Plugins, which is why the do_user_config # method is defined on the base plugin class do_user_config = base_plugin_object.do_user_config # self.gui is the main calibre GUI. It acts as the gateway to access # all the elements of the calibre user interface, it should also be the # parent of the dialog d = DemoDialog(self.gui, self.qaction.icon(), do_user_config) d.show() def apply_settings(self): from calibre_plugins.interface_demo.config import prefs # In an actual non trivial plugin, you would probably need to # do something based on the settings in prefs prefs
2,980
Python
.py
56
46.25
79
0.701718
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)