def testAllowedSizes(self): # test the defaults # for readability, pep8 is not applied to the dict below self.assertEqual(getAllowedSizes(), dict( large=(768, 768), preview=(400, 400), mini=(200, 200), thumb=(128, 128), tile=(64, 64), icon=(32, 32), listing=(16, 16))) # override and test again settings = getSettings() settings.allowed_sizes = [u'foo bar 23:23'] self.assertEqual(getAllowedSizes(), dict(foo_bar=(23, 23)))
def __call__(self, context): from plone.app.imaging.utils import getAllowedSizes #importing here should prevent from erros when using w/o plone.app.imaging terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): terms.append( SimpleTerm(scale, scale, "%s (%dx%d)" % (scale, width, height)) ) return SimpleVocabulary(terms)
def __call__(self, context): terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): terms.append(SimpleTerm(scale, scale, "%s (%dx%d)" % ( scale, width, height))) return SimpleVocabulary(terms)
def testAllowedSizes(self): # test the defaults # for readability, pep8 is not applied to the dict below self.assertEqual( getAllowedSizes(), dict(large=(768, 768), preview=(400, 400), mini=(200, 200), thumb=(128, 128), tile=(64, 64), icon=(32, 32), listing=(16, 16))) # override and test again settings = getSettings() settings.allowed_sizes = [u'foo bar 23:23'] self.assertEqual(getAllowedSizes(), dict(foo_bar=(23, 23)))
def availablePloneAppImagingScalesVocabulary(context): terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): terms.append(SimpleTerm(scale, scale, \ "%s (%dx%d)" % (scale, width, height))) return SimpleVocabulary(terms)
def ImageScaleVocabulary(context): allowed_sizes = getAllowedSizes() items = [ ("%s(%s, %s)" % (key, value[0], value[1]), key) for key, value in allowed_sizes.items() if allowed_sizes ] return SimpleVocabulary.fromItems(items)
def __call__(self, context): sizes = utils.getAllowedSizes() values = sorted(sizes.items(), key=lambda x: -x[1][0]) terms = [SimpleVocabulary.createTerm(x, x, "%s (%s, %s)" % (x, y[0], y[1])) for x, y in values] return SimpleVocabulary(terms)
def render(self): if not self.request.slider_tool.show_slider(): return '' sizes = getAllowedSizes() width, height = sizes['simpleslider'] js = JS_TEMPLATE % {'width':width, 'height': height} return self.index(js=js)
def scales(self): """Returns information to initialize JCrop for all available scales on the current content with the given fieldname and interface.""" scales = [] croputils = IImageCroppingUtils(self.context) cropview = self.context.restrictedTraverse('@@crop-image') image_size = croputils.get_image_size(self.fieldname, self.interface) all_sizes = self.exclude_scales(getAllowedSizes()) scale_names = all_sizes.keys() scale_names.sort() current_selected = self.request.get('scalename', all_sizes.keys()[0]) # TODO: implement other imagefields large_image_url = self.image_url(self.fieldname) for size in scale_names: scale = dict() # scale jcrop config min_width, min_height = self._min_size(image_size, all_sizes[size]) max_width, max_height = self.default_cropping_max_size[0],\ self.default_cropping_max_size[1] ratio_width, ratio_height = all_sizes[size][0], all_sizes[size][1] # lookup saved crop info select_box = cropview._read(self.fieldname, size) is_cropped = True if select_box is None: select_box = (0, 0, min_width, min_height) is_cropped = False config = dict([ ("allowResize", True), ("allowMove", True), ("trueSize", [image_size[0], image_size[1]]), ("boxWidth", self.default_editor_size[0]), ("boxHeight", self.default_editor_size[1]), ("setSelect", select_box), ("aspectRatio", "%.2f" % ( float(ratio_width) / float(ratio_height))), ("minSize", [min_width, min_height]), ("maxSize", [max_width, max_height]), ("imageURL", large_image_url), ]) scale["config"] = json.dumps(config) # scale value/id scale["id"] = size scale["title"] = "%s %s" % (size, all_sizes[size]) scale["selected"] = size == current_selected and 'selected' or '' # flag if saved cropped scale was found # this helps to prevent generating unused # default scales in preview column scale["is_cropped"] = is_cropped # TODO: this is for thumbnail live-preview scale["thumb_width"] = ratio_width scale["thumb_height"] = ratio_height scales.append(scale) return scales
def get_image_width(self): if self.imaging_props is not None: # get from plone.app.imaging properties size = getAllowedSizes().get(config.IMAGE_SCALE_NAME, None) if size is not None: return int(size[0]) # height # fallback (Plone 3 or wrong configuration) return self.cli_props.image_width
def __call__(self, context): sizes = getAllowedSizes() scales = [{'size': size, 'value': key, 'title': "%s %s" % (key, size)} for key, size in sizes.items()] scales.sort(lambda x, y: cmp(x['size'][0], y['size'][0])) terms = [SimpleTerm(scale['value'], title=scale['title']) for scale in scales] return SimpleVocabulary(terms)
def __call__(self, context): terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): terms.append( SimpleTerm(scale, scale, "%s (%dx%d)" % (scale, width, height))) return SimpleVocabulary(terms)
def tinymce(self): generator = CastleTinyMCESettingsGenerator(self.context, self.request) settings = generator.settings folder = aq_inner(self.context) # Test if we are currently creating an Archetype object if IFactoryTempFolder.providedBy(aq_parent(folder)): folder = aq_parent(aq_parent(aq_parent(folder))) if not IFolderish.providedBy(folder): folder = aq_parent(folder) if IPloneSiteRoot.providedBy(folder): initial = None else: initial = IUUID(folder, None) current_path = folder.absolute_url()[len(generator.portal_url):] scales = [] for name, info in sorted(getAllowedSizes().items(), key=lambda x: x[1][0]): scales.append({ 'part': name, 'name': name, 'label': '{} ({}x{})'.format( name.capitalize(), info[0], info[1]) }) image_types = settings.image_objects or [] folder_types = settings.contains_objects or [] configuration = { 'relatedItems': { 'vocabularyUrl': '%s/@@getVocabulary?name=plone.app.vocabularies.Catalog' % ( generator.portal_url) }, 'upload': { 'initialFolder': initial, 'currentPath': current_path, 'baseUrl': generator.portal_url, 'relativePath': '@@fileUpload', 'uploadMultiple': False, 'maxFiles': 1, 'showTitle': False }, 'base_url': self.context.absolute_url(), 'tiny': generator.get_tiny_config(), # This is for loading the languages on tinymce 'loadingBaseUrl': '%s/++plone++static/components/tinymce-builded/js/tinymce' % generator.portal_url, # noqa 'prependToUrl': 'resolveuid/', 'linkAttribute': 'UID', 'prependToScalePart': '/@@images/image/', 'folderTypes': folder_types, 'imageTypes': image_types, 'scales': scales } return {'data-pat-tinymce': json.dumps(configuration)}
def setUp(self): super(IntegrationTestCase, self).setUp() self.portal = self.layer['portal'] self.request = self.layer['request'] testing.setRoles(self.portal, testing.TEST_USER_ID, ['Manager']) self.portal.invokeFactory('Image', 'myimage') testing.setRoles(self.portal, testing.TEST_USER_ID, ['Member']) self.image = self.portal['myimage'] from plone.app.imaging.utils import getAllowedSizes self.sizes = getAllowedSizes()
def set_image_width(self, image_width): if self.imaging_props is not None: # we have plone.app.imaging - store the size to imaging_properties sizes = getAllowedSizes() if config.IMAGE_SCALE_NAME in sizes.keys(): w, h = sizes[config.IMAGE_SCALE_NAME] w = image_width self._change_imaging_props(w, h) # store the size to cli_properties in any case self.cli_props.image_width = image_width
def thumbnail_sizes_vocabulary(context): """Builds a vocabulary of thumbnail sizes. An example item in vocabulary would have title set to "tile (64, 64)" and value to ('tile', 64, 64). :returns: Vocabulary items for each allowed thumbnail size." rtype: SimpleVocabulary """ terms = [] for name, size in getAllowedSizes().iteritems(): terms.append(SimpleVocabulary.createTerm(name, str(name), u"%s" % name)) return SimpleVocabulary(terms)
def ImageScalesVocabulary(context): """Return a vocabulary listing all image scales. An example item would have token set to 'tile (64, 64)' and value to ('tile', 64, 64). """ terms = [] for name, size in getAllowedSizes().iteritems(): terms.append(SimpleVocabulary.createTerm( tuple((name,) + size), str(name), u'{0} {1}'.format(name, size))) return SimpleVocabulary(terms)
def testAllowedSizes(self): # test the defaults self.assertEqual(getAllowedSizes(), dict( large = (768, 768), preview = (400, 400), mini = (200, 200), thumb = (128, 128), tile = ( 64, 64), icon = ( 32, 32), listing = ( 16, 16))) # override and test again iprops = self.portal.portal_properties.imaging_properties iprops.manage_changeProperties(allowed_sizes='foo 23:23') self.assertEqual(getAllowedSizes(), dict(foo = (23, 23))) # empty lines and white space should be ignored iprops.manage_changeProperties(allowed_sizes=['x 23 :23 ', '', ' ']) self.assertEqual(getAllowedSizes(), dict(x = (23, 23))) # however, white space within the name should be fine... iprops.manage_changeProperties(allowed_sizes=['foo bar 23:23']) self.assertEqual(getAllowedSizes(), dict(foo_bar = (23, 23)))
def getRelativePaths(self): if not getattr(self.context, 'image', None): return [] prefix = '/' + self.context.virtual_url_path() paths = [prefix + '/@@images/image'] for scale_name in getAllowedSizes().keys(): paths.append(prefix + '/@@images/image/' + scale_name) return paths
def thumbnail_sizes_vocabulary(context): """Builds a vocabulary of thumbnail sizes. An example item in vocabulary would have title set to "tile (64, 64)" and value to ('tile', 64, 64). :returns: Vocabulary items for each allowed thumbnail size." rtype: SimpleVocabulary """ terms = [] # TODO: we should query utility, but it's not certain it will be there for name, size in getAllowedSizes().iteritems(): terms.append(SimpleVocabulary.createTerm(tuple((name,) + size), str(name), u"%s %s" % (name, size))) return SimpleVocabulary(terms)
def ScalesVocabulary(context): """Obtains available scales from plone.app.imaging """ terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): translated = _( 'imagescale_{0:s}'.format(scale), default='{0:s} ${{width}}x${{height}}'.format(scale), mapping={'width': str(width), 'height': str(height)}) terms.append(SimpleTerm(scale, scale, translated)) return SimpleVocabulary(terms)
def testAllowedSizes(self): # test the defaults # for readability, pep8 is not applied to the dict below self.assertEqual( getAllowedSizes(), dict(large=(768, 768), preview=(400, 400), mini=(200, 200), thumb=(128, 128), tile=(64, 64), icon=(32, 32), listing=(16, 16))) # override and test again iprops = self.portal.portal_properties.imaging_properties iprops.manage_changeProperties(allowed_sizes='foo 23:23') self.assertEqual(getAllowedSizes(), dict(foo=(23, 23))) # empty lines and white space should be ignored iprops.manage_changeProperties(allowed_sizes=['x 23 :23 ', '', ' ']) self.assertEqual(getAllowedSizes(), dict(x=(23, 23))) # however, white space within the name should be fine... iprops.manage_changeProperties(allowed_sizes=['foo bar 23:23']) self.assertEqual(getAllowedSizes(), dict(foo_bar=(23, 23)))
def thumbnail_sizes_vocabulary(context): """Builds a vocabulary of thumbnail sizes. An example item in vocabulary would have title set to "tile (64, 64)" and value to ('tile', 64, 64). :returns: Vocabulary items for each allowed thumbnail size." rtype: SimpleVocabulary """ terms = [] # TODO: we should query utility, but it's not certain it will be there for name, size in getAllowedSizes().iteritems(): terms.append( SimpleVocabulary.createTerm(tuple((name, ) + size), str(name), u"%s %s" % (name, size))) return SimpleVocabulary(terms)
def ScalesVocabulary(context): """Obtains available scales from plone.app.imaging """ terms = [] for scale, (width, height) in getAllowedSizes().iteritems(): translated = _('imagescale_{0:s}'.format(scale), default='{0:s} ${{width}}x${{height}}'.format(scale), mapping={ 'width': str(width), 'height': str(height) }) terms.append(SimpleTerm(scale, scale, translated)) return SimpleVocabulary(terms)
def update(self): if not self.request: self.request = getRequest() # support viewpagetemplatefile if not self.fieldname: self.fieldname = 'image' if not self.context_url: self.context_url = self.context.getURL() if not self.base_url: self.base_url = self.context_url + '/@@images/' + self.fieldname + '/' if not self.sizes: self.sizes = getAllowedSizes() if not self.pictures or not self.noscript: pictures = getPictures(self.base_url, self.sizes) self.pictures, self.noscript = pictures
def update(self): self.context_url = self.context.absolute_url() if not self.fieldname: self.fieldname = self.request.get('field', 'image') if not self.base_url: base_url = self.context_url + '/@@images/' + self.fieldname + '/' self.base_url = base_url if not self.alt: self.alt = self.context.Title() if not self.sizes: self.sizes = getAllowedSizes() if not self.pictures or not self.noscript: pictures = getPictures(self.base_url, self.sizes) self.pictures, self.noscript = pictures
def size_map(self): image_sizes = { 'small': 'mini', 'medium': 'preview', 'large': 'large', 'thumb': 'tile' } # Here we try to get the custom sizes # we skip some scales, since they are already 'taken' from plone.app.imaging.utils import getAllowedSizes all_sizes = getAllowedSizes() for scale_name, sizes in all_sizes.items(): if scale_name not in ['small', 'medium', 'mini', 'preview', 'thumb', 'tile', 'large']: image_sizes[str(scale_name)] = str(scale_name) return image_sizes
def ImageSizeVocabulary(context): sizes = getAllowedSizes() #default vocabulary if everything else fails terms = [ SimpleTerm('mini', 'mini', u'Mini'), SimpleTerm('preview', 'preview', u'Preview'), SimpleTerm('large', 'large', u'Large'), SimpleTerm('original', 'original', u'Original'), ] if sizes: if not 'original' in sizes: sizes.update({'original': 'original'}) terms = [ SimpleTerm(value=format_size(pair), token=format_size(pair), title=pair) for pair in sizes ] return SimpleVocabulary(terms)
def size_map(self): image_sizes = {"small": "mini", "medium": "preview", "large": "large", "thumb": "tile"} # Here we try to get the custom sizes # we skip some scales, since they are already 'taken' try: from plone.app.imaging.utils import getAllowedSizes all_sizes = getAllowedSizes() for scale_name in all_sizes.keys(): if scale_name not in ["small", "medium", "mini", "preview", "thumb", "tile", "large"]: image_sizes[str(scale_name)] = str(scale_name) except (ImportError, AttributeError): # plone 3 without plone.app.blob... We still have defaults... pass return image_sizes
def sizes(self): if has_pai: from plone.app.imaging.utils import getAllowedSizes # user has plone.app.imaging installed, use # these image size settings _allowed_sizes = getAllowedSizes() allowed_sizes = {} for scale_name, sizes in _allowed_sizes.items(): width, height = sizes if scale_name not in self._inverted_size_map: continue size_name = self._inverted_size_map[scale_name] allowed_sizes[size_name] = {'width': width, 'height': height} if size_name in self.minimum_sizes: if width < self.minimum_sizes[size_name]['width']: allowed_sizes[size_name]['width'] = \ self.minimum_sizes[size_name]['width'] if height < self.minimum_sizes[size_name]['height']: allowed_sizes[size_name]['height'] = \ self.minimum_sizes[size_name]['height'] self.size_map[size_name] = \ self.minimum_sizes[size_name]['next_scale'] return allowed_sizes else: from Products.ATContentTypes.content.image import ATImageSchema return { 'small': { 'width': 320, 'height': 320 }, 'medium': { 'width': 576, 'height': 576 }, 'large': { 'width': ATImageSchema['image'].sizes['large'][0], 'height': ATImageSchema['image'].sizes['large'][1] }, 'thumb': { 'width': ATImageSchema['image'].sizes['tile'][0], 'height': ATImageSchema['image'].sizes['tile'][1] } }
def update(self): if not self.alt: self.alt = self.context.data.get('title', '') if not self.request: self.request = self.context.request if not self.fieldname: self.fieldname = 'picture' # plone.app.imagetile if not self.context_url: self.context_url = self.context.url if not self.base_url: self.base_url = self.context_url + '/@@images/' + self.fieldname + '/' if not self.sizes: self.sizes = getAllowedSizes() if not self.pictures or not self.noscript: pictures = getPictures(self.base_url, self.sizes) self.pictures, self.noscript = pictures #Tile doesn't support @@/images/fieldname without a scale... self.pictures = self.pictures[:-1]
def __call__(self, context): #importing here should prevent from erros when using w/o #plone.app.imaging from plone.app.imaging.utils import getAllowedSizes terms = [] sorted_scales = sorted(getAllowedSizes().iteritems(), cmp=lambda x, y: cmp(x[1][0], y[1][0]), reverse=True) for scale, (width, height) in sorted_scales: terms.append(SimpleTerm(value=scale, token=scale, title="%s (%dx%d)" % (scale.title(), width, height) ) ) return SimpleVocabulary(terms)
def save_cropped(self, fieldname, scale, image_file): """ see interface """ sizes = getAllowedSizes() w, h = sizes[scale] def crop_factory(fieldname, **parameters): # LMU patch: remove the scale parameter _parameters = { key: value for key, value in parameters.iteritems() if key != 'scale' } result = scaleImage(image_file.read(), **_parameters) if result is not None: data, format, dimensions = result mimetype = 'image/{0:s}'.format(format.lower()) field = self.get_image_field(fieldname) value = field.__class__(data, contentType=mimetype, filename=field.filename) value.fieldname = fieldname return value, format, dimensions # call storage with actual time in milliseconds # this always invalidates old scales storage = AnnotationStorage(self.context, _millis) # We need to pass direction='thumbnail' since this is the default # used by plone.namedfile.scaling, also for retrieval of scales. # Otherwise the key under which the scaled and cropped image is # saved in plone.scale.storage.AnnotationStorage will not match the # key used for retrieval (= the cropped scaled image will not be # found) # LMU patch: add the scale parameter storage.scale( factory=crop_factory, direction='thumbnail', fieldname=fieldname, scale=scale, width=w, height=h, )
def getAvailableSizes(self, instance): """ get available sizes for scaled down images; this uses the new, user-configurable settings, but still support instance methods and other callables; see Archetypes/Field.py """ sizes = getattr(aq_base(self), 'sizes', None) if isinstance(sizes, dict): return sizes elif isinstance(sizes, basestring): assert(shasattr(instance, sizes)) method = getattr(instance, sizes) data = method() assert(isinstance(data, dict)) return data elif callable(sizes): return sizes() else: sizes = getAllowedSizes() if sizes is None: sizes = self.original_getAvailableSizes(instance) return sizes
def getAvailableSizes(self, instance): """ get available sizes for scaled down images; this uses the new, user-configurable settings, but still support instance methods and other callables; see Archetypes/Field.py """ sizes = getattr(aq_base(self), 'sizes', None) if isinstance(sizes, dict): return sizes elif isinstance(sizes, six.string_types): assert(shasattr(instance, sizes)) method = getattr(instance, sizes) data = method() assert(isinstance(data, dict)) return data elif callable(sizes): return sizes() else: sizes = getAllowedSizes() if sizes is None: sizes = self.original_getAvailableSizes(instance) return sizes
def options(self): context = aq_inner(self.context) delay = field_getter(context, 'time_delay', 10) caps = field_getter(context, 'show_captions', True) scales = utils.getAllowedSizes() width, height = scales.get(self.slideshow_scale, (200, 200)) data = { 'animtype': 'slide', 'height': height, 'width': width, 'responsive': True, 'randomstart': False, 'showcontrols': True, 'showmarkers': False, 'animspeed': delay * 1000, 'usecaptions': caps } return "var opts = {}".format(json.dumps(data))
def size_map(self): image_sizes = { 'small': 'mini', 'medium': 'preview', 'large': 'large', 'thumb': 'tile' } # Here we try to get the custom sizes # we skip some scales, since they are already 'taken' try: from plone.app.imaging.utils import getAllowedSizes all_sizes = getAllowedSizes() for scale_name in all_sizes.keys(): if scale_name not in ['small', 'medium', 'mini', 'preview', 'thumb', 'tile', 'large']: image_sizes[str(scale_name)] = str(scale_name) except (ImportError, AttributeError): # plone 3 without plone.app.blob... We still have defaults... pass return image_sizes
def sizes(self): if has_pai: from plone.app.imaging.utils import getAllowedSizes # user has plone.app.imaging installed, use # these image size settings _allowed_sizes = getAllowedSizes() allowed_sizes = {} for scale_name, sizes in _allowed_sizes.items(): width, height = sizes if scale_name not in self._inverted_size_map: continue size_name = self._inverted_size_map[scale_name] allowed_sizes[size_name] = {"width": width, "height": height} if size_name in self.minimum_sizes: if width < self.minimum_sizes[size_name]["width"]: allowed_sizes[size_name]["width"] = self.minimum_sizes[size_name]["width"] if height < self.minimum_sizes[size_name]["height"]: allowed_sizes[size_name]["height"] = self.minimum_sizes[size_name]["height"] self.size_map[size_name] = self.minimum_sizes[size_name]["next_scale"] return allowed_sizes else: from Products.ATContentTypes.content.image import ATImageSchema return { "small": {"width": 320, "height": 320}, "medium": {"width": 576, "height": 576}, "large": { "width": ATImageSchema["image"].sizes["large"][0], "height": ATImageSchema["image"].sizes["large"][1], }, "thumb": { "width": ATImageSchema["image"].sizes["tile"][0], "height": ATImageSchema["image"].sizes["tile"][1], }, }
def unprettify(configuration): original = configuration for key, value in original.iteritems(): if isinstance(value, dict): # TODO: find a better name for 'htmltag' if 'scale' in value: allowed_sizes = getAllowedSizes() scale = value['scale'] assert scale in allowed_sizes width, height = allowed_sizes[scale] value['imgsize'] = '{0} {1}:{2}'.format(scale, width, height) del value['scale'] if 'order' in value: value['order'] = unicode(value['order']) if 'align' in value: value['position'] = value['align'] del value['align'] if 'visible' in value: value['visibility'] = u'on' if value['visible'] else u'off' del value['visible'] configuration[key] = value return configuration
def size_map(self): image_sizes = { 'small': 'mini', 'medium': 'preview', 'large': 'large', 'thumb': 'tile' } # Here we try to get the custom sizes # we skip some scales, since they are already 'taken' try: from plone.app.imaging.utils import getAllowedSizes all_sizes = getAllowedSizes() for scale_name in all_sizes.keys(): if scale_name not in [ 'small', 'medium', 'mini', 'preview', 'thumb', 'tile', 'large' ]: image_sizes[str(scale_name)] = str(scale_name) except (ImportError, AttributeError): # plone 3 without plone.app.blob... We still have defaults... pass return image_sizes
def ImageScaleVocabulary(context): allowed_sizes = getAllowedSizes() items = [(u'{0}({1}, {2})'.format(key, value[0], value[1]), key) for key, value in allowed_sizes.items() if allowed_sizes] return SimpleVocabulary.fromItems(items)
from Products.ATContentTypes.content import image from Products.ATContentTypes.content import schemata from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin from Products.CMFCore.permissions import View from zope.i18nmessageid import MessageFactory from zope.interface import implementer try: from Products.LinguaPlone import public as atapi except ImportError: # No multilingual support from Products.Archetypes import atapi _ = MessageFactory('collective.teaser') allowed_sizes = getAllowedSizes() type_schema = schemata.ATContentTypeSchema.copy() + atapi.Schema(( atapi.ImageField( 'image', required=False, languageIndependent=True, sizes=allowed_sizes, widget=atapi.ImageWidget( label=_(u"label_image", default=u"Image"), description=_(u"help_image", default=u"Image to display as teaser."), ), ), atapi.ReferenceField( 'link_internal',
def __call__(self, context): allowed_sizes = getAllowedSizes() size_names = allowed_sizes and allowed_sizes.keys() or [] return SimpleVocabulary.fromValues(size_names)
def image_size(self): return getAllowedSizes()
def __init__(self, *args): super(EmptyRedirect, self).__init__(*args) self.sizes = getAllowedSizes()
def ImageScaleVocabulary(context): allowed_sizes = getAllowedSizes() items = [(u'%s(%s, %s)' % (key, value[0], value[1]), key) for key, value in allowed_sizes.items() if allowed_sizes] return SimpleVocabulary.fromItems(items)
def scales(self, fieldname=None): """Returns information to initialize JCrop for all available scales on the current content with the given fieldname and interface.""" scales = [] croputils = IImageCroppingUtils(self.context) cropview = self.context.restrictedTraverse('@@crop-image') if fieldname is None: fieldname = self.fieldname image_size = croputils.get_image_size(fieldname, self.interface) all_sizes = getAllowedSizes() current_selected = self.request.get('scalename', all_sizes.keys()[0]) large_image_url = self.image_url(fieldname) constrain_cropping = self._editor_settings.constrain_cropping cropping_for = self._editor_settings.cropping_for for size in all_sizes: if constrain_cropping and size not in cropping_for: continue scale = dict() # scale jcrop config min_width, min_height = self._min_size(image_size, all_sizes[size]) max_width, max_height = self.default_cropping_max_size[0], \ self.default_cropping_max_size[1] ratio_width, ratio_height = all_sizes[size][0], all_sizes[size][1] # lookup saved crop info select_box = cropview._read(fieldname, size) is_cropped = True if select_box is None: select_box = (0, 0, min_width, min_height) is_cropped = False config = dict([ ("allowResize", True), ("allowMove", True), ("trueSize", [image_size[0], image_size[1]]), ("boxWidth", self.default_editor_size[0]), ("boxHeight", self.default_editor_size[1]), ("setSelect", select_box), ("aspectRatio", "%.2f" % (float(ratio_width) / float(ratio_height))), ("minSize", [min_width, min_height]), ("maxSize", [max_width, max_height]), ("imageURL", large_image_url), ]) scale["config"] = json.dumps(config) # scale value/id scale["id"] = size scale["title"] = "%s %s" % (size, all_sizes[size]) scale["selected"] = size == current_selected and 'selected' or '' # flag if saved cropped scale was found # this helps to prevent generating unused # default scales in preview column scale["is_cropped"] = is_cropped # TODO: this is for thumbnail live-preview scale["thumb_width"] = ratio_width scale["thumb_height"] = ratio_height # safe original image url scale["image_url"] = large_image_url scales.append(scale) return scales