PSD(Adobe Photoshop data) preview plugin

@param elFinder.commands.quicklook
324314
function(ql) {
				var fm      = ql.fm,
			mimes   = fm.arrayFlip(['image/vnd.adobe.photoshop', 'image/x-photoshop']),
			preview = ql.preview,
			load    = function(url, img, loading) {
				try {
					fm.replaceXhrSend();
					PSD.fromURL(url).then(function(psd) {
						var prop;
						img.attr('src', psd.image.toBase64());
						requestAnimationFrame(function() {
							prop = (img.width()/img.height()).toFixed(2);
							preview.on('changesize', function() {
								var pw = parseInt(preview.width()),
									ph = parseInt(preview.height()),
									w, h;
							
								if (prop < (pw/ph).toFixed(2)) {
									h = ph;
									w = Math.floor(h * prop);
								} else {
									w = pw;
									h = Math.floor(w/prop);
								}
								img.width(w).height(h).css('margin-top', h < ph ? Math.floor((ph - h)/2) : 0);
							}).trigger('changesize');
							
							loading.remove();
							// hide info/icon
							ql.hideinfo();
							//show image
							img.fadeIn(100);
						});
					}, function() {
						loading.remove();
						img.remove();
					});
					fm.restoreXhrSend();
				} catch(e) {
					fm.restoreXhrSend();
					loading.remove();
					img.remove();
				}
			},
			PSD;
		
		preview.on(ql.evUpdate, function(e) {
			var file = e.file,
				url, img, loading, m,
				_define, _require;

			if (mimes[file.mime] && fm.options.cdns.psd && ! fm.UA.ltIE10 && ql.dispInlineRegex.test(file.mime)) {
				// this is our file - stop event propagation
				e.stopImmediatePropagation();

				loading = $('<div class="elfinder-quicklook-info-data"> '+fm.i18n('nowLoading')+'<span class="elfinder-info-spinner"></div>').appendTo(ql.info.find('.elfinder-quicklook-info'));
				url = fm.openUrl(file.hash);
				if (!fm.isSameOrigin(url)) {
					url = fm.openUrl(file.hash, true);
				}
				img = $('<img/>').hide().appendTo(preview);
				
				if (PSD) {
					load(url, img, loading);
				} else {
					_define = window.define;
					_require = window.require;
					window.require = null;
					window.define = null;
					fm.loadScript(
						[ fm.options.cdns.psd ],
						function() {
							PSD = require('psd');
							_define? (window.define = _define) : (delete window.define);
							_require? (window.require = _require) : (delete window.require);
							load(url, img, loading);
						}
					);
				}
			}
		});
	}
991521
function(ql) {
				var fm      = ql.fm,
			preview = ql.preview,
			textMaxlen = parseInt(ql.options.textMaxlen) || 2000,
			prettify = function() {
				if (fm.options.cdns.prettify) {
					fm.loadScript([fm.options.cdns.prettify + (fm.options.cdns.prettify.match(/\?/)? '&' : '?') + 'autorun=false']);
					prettify = function() { return true; };
				} else {
					prettify = function() { return false; };
				}
			},
			PRcheck = function(node, cnt) {
				if (prettify()) {
					if (typeof window.PR === 'undefined' && cnt--) {
						setTimeout(function() { PRcheck(node, cnt); }, 100);
					} else {
						if (typeof window.PR === 'object') {
							node.css('cursor', 'wait');
							requestAnimationFrame(function() {
								PR.prettyPrint && PR.prettyPrint(null, node.get(0));
								node.css('cursor', '');
							});
						} else {
							prettify = function() { return false; };
						}
					}
				}
			};
		
		preview.on(ql.evUpdate, function(e) {
			var file = e.file,
				mime = file.mime,
				jqxhr, loading;
			
			if (fm.mimeIsText(file.mime) && (!ql.options.getSizeMax || file.size <= ql.options.getSizeMax)) {
				e.stopImmediatePropagation();
				
				(typeof window.PR === 'undefined') && prettify();
				
				loading = $('<div class="elfinder-quicklook-info-data"> '+fm.i18n('nowLoading')+'<span class="elfinder-info-spinner"></div>').appendTo(ql.info.find('.elfinder-quicklook-info'));

				// stop loading on change file if not loadin yet
				preview.one('change', function() {
					jqxhr.state() == 'pending' && jqxhr.reject();
				});
				
				jqxhr = fm.request({
					data           : {cmd : 'get', target : file.hash, conv : 1, _t : file.ts},
					options        : {type: 'get', cache : true},
					preventDefault : true
				})
				.done(function(data) {
					var reg = new RegExp('^(data:'+file.mime.replace(/([.+])/g, '\\$1')+';base64,)', 'i'),
						text = data.content,
						part, more, node, m;
					ql.hideinfo();
					if (window.atob && (m = text.match(reg))) {
						text = atob(text.substr(m[1].length));
					}
					
					more = text.length - textMaxlen;
					if (more > 100) {
						part = text.substr(0, textMaxlen) + '...';
					} else {
						more = 0;
					}
					
					node = $('<div class="elfinder-quicklook-preview-text-wrapper"><pre class="elfinder-quicklook-preview-text prettyprint"></pre></div>');
					
					if (more) {
						node.append($('<div class="elfinder-quicklook-preview-charsleft"><hr/><span>' + fm.i18n('charsLeft', fm.toLocaleString(more)) + '</span></div>')
							.on('click', function() {
								var top = node.scrollTop();
								$(this).remove();
								node.children('pre').removeClass('prettyprinted').text(text).scrollTop(top);
								PRcheck(node, 100);
							})
						);
					}
					node.children('pre').text(part || text);
					
					node.on('touchstart', function(e) {
						if ($(this)['scroll' + (fm.direction === 'ltr'? 'Right' : 'Left')]() > 5) {
							e.originalEvent._preventSwipeX = true;
						}
					}).appendTo(preview);
					
					PRcheck(node, 100);
				})
				.always(function() {
					loading.remove();
				});
			}
		});
	}
1293603
@Override
  public void loadImage(DataInputStream in, ImageVisitor v,
      boolean skipBlocks) throws IOException {
    try {
      InjectionHandler.processEvent(InjectionEvent.IMAGE_LOADER_CURRENT_START);
      v.start();
      v.visitEnclosingElement(ImageElement.FS_IMAGE);

      imageVersion = in.readInt();
      if( !canLoadVersion(imageVersion))
        throw new IOException("Cannot process fslayout version " + imageVersion);

      v.visit(ImageElement.IMAGE_VERSION, imageVersion);
      v.visit(ImageElement.NAMESPACE_ID, in.readInt());

      long numInodes = in.readLong();
      v.setNumberOfFiles(numInodes);

      v.visit(ImageElement.GENERATION_STAMP, in.readLong());
      if (imageVersion <= FSConstants.STORED_TXIDS) {
        v.visit(ImageElement.LAST_TXID, in.readLong());
      }
      
      if (LayoutVersion.supports(Feature.ADD_INODE_ID, imageVersion)) {
        v.visit(ImageElement.LAST_INODE_ID, in.readLong());
      }

      if (LayoutVersion.supports(Feature.FSIMAGE_COMPRESSION, imageVersion)) {
        boolean isCompressed = in.readBoolean();
        v.visit(ImageElement.IS_COMPRESSED, imageVersion);
        if (isCompressed) {
          String codecClassName = Text.readString(in);
          v.visit(ImageElement.COMPRESS_CODEC, codecClassName);
          CompressionCodecFactory codecFac = new CompressionCodecFactory(
              new Configuration());
          CompressionCodec codec = codecFac.getCodecByClassName(codecClassName);
          if (codec == null) {
            throw new IOException("Image compression codec not supported: "
                + codecClassName);
          }
          in = new DataInputStream(codec.createInputStream(in));
        }
      }
      in = BufferedByteInputStream.wrapInputStream(in, 8 * BASE_BUFFER_SIZE, BASE_BUFFER_SIZE);
      processINodes(in, v, numInodes, skipBlocks);

      processINodesUC(in, v, skipBlocks);

      v.leaveEnclosingElement(); // FSImage
      v.finish();
    } catch(IOException e) {
      // Tell the visitor to clean up, then re-throw the exception
      v.finishAbnormally();
      throw e;
    }
  }
892835
function(oRoadMap, iNewPos, bSkipAnim, fEndCallBack){
		var jStepArea = oRoadMap.$("steparea");
		jStepArea.stop(false, true);

		if (iNewPos == "next") {
			iNewPos = jStepArea.scrollLeft() + oRoadMap.iStepWidth * getRTLFactor();
		} else if (iNewPos == "prev") {
			iNewPos = jStepArea.scrollLeft() - oRoadMap.iStepWidth * getRTLFactor();
		} else if (iNewPos == "keep") {
			iNewPos = jStepArea.scrollLeft();
		} else {
			iNewPos = iNewPos * getRTLFactor();
		}

		var fDoAfterScroll = function(){
			updateDelimiters(oRoadMap);

			if (fEndCallBack) {
				var jFirstVisibleRef = RoadMapRenderer.getFirstVisibleRef(oRoadMap);
				fEndCallBack(jFirstVisibleRef.attr("id"));
			}
		};

		if (!jQuery.fx.off && !bSkipAnim) {
			jStepArea.animate({scrollLeft: iNewPos}, "fast", fDoAfterScroll);
		} else {
			jStepArea.scrollLeft(iNewPos);
			fDoAfterScroll();
		}
	}
1122726
function(ql) {
				var fm      = ql.fm,
			mime    = 'application/pdf',
			preview = ql.preview,
			active  = false;
			
		if ((fm.UA.Safari && fm.OS === 'mac' && !fm.UA.iOS) || fm.UA.IE) {
			active = true;
		} else {
			$.each(navigator.plugins, function(i, plugins) {
				$.each(plugins, function(i, plugin) {
					if (plugin.type === mime) {
						return !(active = true);
					}
				});
			});
		}

		active && preview.on(ql.evUpdate, function(e) {
			var file = e.file, node;
			
			if (file.mime === mime && ql.dispInlineRegex.test(file.mime)) {
				e.stopImmediatePropagation();
				ql.hideinfo();
				ql.cover.addClass('elfinder-quicklook-coverbg');
				node = $('<object class="elfinder-quicklook-preview-pdf" data="'+fm.openUrl(file.hash)+'" type="application/pdf" />')
					.appendTo(preview);
			}
			
		});
		
			
	}
985552
function previewfile(file) {
    if (false && tests.filereader === true) {
      var reader = new FileReader();
      reader.onload = function (event) {
        var image = new Image();
        image.src = event.target.result;
        image.width = 250; // a fake resize
        holder.appendChild(image);
      };

      reader.readAsDataURL(file);
    }  else {
      holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
//      console.log(file);
    }
  }
713195
def select_visible_page_image(infiles, output_file, log, context):
    """"""

    options = context.get_options()
    if options.clean_final:
        image_suffix = '.pp-clean.png'
    elif options.deskew:
        image_suffix = '.pp-deskew.png'
    elif options.remove_background:
        image_suffix = '.pp-background.png'
    else:
        image_suffix = '.page.png'
    image = next(ii for ii in infiles if ii.endswith(image_suffix))

    pageinfo = get_pageinfo(image, context)
    if pageinfo.images and all(im.enc == 'jpeg' for im in pageinfo.images):
        log.debug(f'{page_number(image):4d}: JPEG input -> JPEG output')
        # If all images were JPEGs originally, produce a JPEG as output
        with Image.open(image) as im:
            # At this point the image should be a .png, but deskew, unpaper
            # might have removed the DPI information. In this case, fall back to
            # square DPI used to rasterize. When the preview image was
            # rasterized, it was also converted to square resolution, which is
            # what we want to give tesseract, so keep it square.
            fallback_dpi = get_page_square_dpi(pageinfo, options)
            dpi = im.info.get('dpi', (fallback_dpi, fallback_dpi))

            # Pillow requires integer DPI
            dpi = round(dpi[0]), round(dpi[1])
            im.save(output_file, format='JPEG', dpi=dpi)
    else:
        re_symlink(image, output_file, log)
350796
function(jRef, bWidth, iValue, fDoBefore, fDoAfter){
		if (fDoBefore) {
			var iVal = fDoBefore(jRef);
			if (iVal != undefined) {
				iValue = iVal;
			}
		}
		var _fDoAfter = fDoAfter ? function(){fDoAfter(jRef);} : function(){};
		if (jQuery.fx.off) {
			if (bWidth) {
				jRef.width(iValue);
			} else {
				jRef.height(iValue);
			}
			_fDoAfter();
		} else {
			var oParam = bWidth ? {width: iValue} : {height: iValue};
			jRef.stop(true, true).animate(oParam, 200, 'linear', _fDoAfter);
		}
	}
379631
def paintEvent(self, event):
        
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.editor.sideareas_color)
        # This is needed to make that the font size of line numbers
        # be the same as the text one when zooming
        # See Issue 2296 and 4811
        font = self.editor.font()
        font_height = self.editor.fontMetrics().height()

        active_block = self.editor.textCursor().block()
        active_line_number = active_block.blockNumber() + 1

        def draw_pixmap(ytop, pixmap):
            if not QT55_VERSION:
                pixmap_height = pixmap.height()
            else:
                # scale pixmap height to device independent pixels
                pixmap_height = pixmap.height() / pixmap.devicePixelRatio()
            painter.drawPixmap(0, ytop + (font_height-pixmap_height) / 2,
                               pixmap)

        for top, line_number, block in self.editor.visible_blocks:
            if self._margin:
                if line_number == active_line_number:
                    font.setWeight(font.Bold)
                    painter.setFont(font)
                    painter.setPen(self.editor.normal_color)
                else:
                    font.setWeight(font.Normal)
                    painter.setFont(font)
                    painter.setPen(self.linenumbers_color)

                painter.drawText(0, top, self.width(),
                                 font_height,
                                 Qt.AlignRight | Qt.AlignBottom,
                                 to_text_string(line_number))

            data = block.userData()
            if self._markers_margin and data:
                if data.code_analysis:
                    for source, code, severity, message in data.code_analysis:
                        error = severity == DiagnosticSeverity.ERROR
                        if error:
                            break
                    if error:
                        draw_pixmap(top, self.error_pixmap)
                    else:
                        draw_pixmap(top, self.warning_pixmap)
                if data.todo:
                    draw_pixmap(top, self.todo_pixmap)
970271
def preview(self, stream=sys.stdout):
        """"""

        write = stream.write

        write(('[Quick preview of Docpie %s]' % self._version).center(80, '='))
        write('\n')

        write(' sections '.center(80, '-'))

        write('\n')
        write(self.usage_text)
        write('\n')
        option_sections = self.option_sections
        if option_sections:
            write('\n')
            write('\n'.join(option_sections.values()))
        write('\n')

        write(' str '.center(80, '-'))
        write('\n[%s]\n' % self.usage_name)
        for each in self.usages:
            write('    %s\n' % each)
        write('\n[Options:]\n\n')
        for title, sections in self.options.items():
            if title:
                full_title = '%s %s' % (title, self.option_name)
            else:
                full_title = self.option_name

            write(full_title)
            write('\n')

            for each in sections:
                write('    %s\n' % each)

            write('\n')

        write(' repr '.center(80, '-'))
        write('\n[%s]\n' % self.usage_name)
        for each in self.usages:
            write('    %r\n' % each)
        write('\n[Options:]\n\n')
        for title, sections in self.options.items():
            if title:
                full_title = '%s %s' % (title, self.option_name)
            else:
                full_title = self.option_name

            write(full_title)
            write('\n')

            for each in sections:
                write('    %r\n' % each)

            write('\n')

        write(' auto handlers '.center(80, '-'))
        write('\n')
        for key, value in self.extra.items():
            write('%s %s\n' % (key, value))
466879
function showPreview(editor, popover) {
        var token, cm;

        // Figure out which editor we are over
        if (!editor) {
            editor = getHoveredEditor(lastMousePos);
        }

        if (!editor || !editor._codeMirror) {
            hidePreview();
            return;
        }

        cm = editor._codeMirror;

        // Find char mouse is over
        var pos = cm.coordsChar({left: lastMousePos.clientX, top: lastMousePos.clientY});

        // No preview if mouse is past last char on line
        if (pos.ch >= editor.document.getLine(pos.line).length) {
            return;
        }

        if (popover) {
            popoverState = popover;
        } else {
            // Query providers and append to popoverState
            token = TokenUtils.getTokenAt(cm, pos);
            popoverState = $.extend({}, popoverState, queryPreviewProviders(editor, pos, token));
        }

        if (popoverState && popoverState.start && popoverState.end) {
            popoverState.marker = cm.markText(
                popoverState.start,
                popoverState.end,
                {className: "quick-view-highlight"}
            );

            $previewContent.append(popoverState.content);
            $previewContainer.show();

            popoverState.visible = true;

            if (popoverState.onShow) {
                popoverState.onShow();
            } else {
                positionPreview(editor, popoverState.xpos, popoverState.ytop, popoverState.ybot);
            }
        }
    }
588171
function (options, dir, callback) {
  if (_.isObject(options.icon)) {
    createHicolorIcon(options, dir, callback)
  } else if (options.icon) {
    createPixmapIcon(options, dir, callback)
  } else {
    callback()
  }
}
379498
private void seekToSId(final int pSId, final long pStreamSize) throws IOException {
        long pos;

        if (isShortStream(pStreamSize)) {
            // The short stream is not continuous...
            Entry root = getRootEntry();
            if (shortStreamSIdChain == null) {
                shortStreamSIdChain = getSIdChain(root.startSId, root.streamSize);
            }
            
//            System.err.println("pSId: " + pSId);
            int shortPerSId = sectorSize / shortSectorSize;
//            System.err.println("shortPerSId: " + shortPerSId);
            int offset = pSId / shortPerSId;
//            System.err.println("offset: " + offset);
            int shortOffset = pSId - (offset * shortPerSId);
//            System.err.println("shortOffset: " + shortOffset);
//            System.err.println("shortStreamSIdChain.offset: " + shortStreamSIdChain.get(offset));

            pos = HEADER_SIZE
                    + (shortStreamSIdChain.get(offset) * (long) sectorSize)
                    + (shortOffset * (long) shortSectorSize);
//            System.err.println("pos: " + pos);
        }
        else {
            pos = HEADER_SIZE + pSId * (long) sectorSize;
        }

        if (input instanceof LittleEndianRandomAccessFile) {
            ((LittleEndianRandomAccessFile) input).seek(pos);
        }
        else if (input instanceof ImageInputStream) {
            ((ImageInputStream) input).seek(pos);
        }
        else {
            ((SeekableLittleEndianDataInputStream) input).seek(pos);
        }
    }
994795
protected function processPsd()
    {
        $format = 'psd';
        $compression = \Imagick::COMPRESSION_UNDEFINED;

        $imagick = $this->image->getCore();
        $imagick->setFormat($format);
        $imagick->setImageFormat($format);
        $imagick->setCompression($compression);
        $imagick->setImageCompression($compression);

        return $imagick->getImagesBlob();
    }
845022
public void actionPreview() throws IOException, JspException {

        try {
            // save content of the editor only to the temporary file
            setEditorValues(getElementLocale());
            writeContent();
            CmsObject cloneCms = getCloneCms();
            CmsUUID tempProjectId = OpenCms.getWorkplaceManager().getTempFileProjectId();
            cloneCms.getRequestContext().setCurrentProject(getCms().readProject(tempProjectId));
            // remove eventual release & expiration date from temporary file to make preview work
            cloneCms.setDateReleased(getParamTempfile(), CmsResource.DATE_RELEASED_DEFAULT, false);
            cloneCms.setDateExpired(getParamTempfile(), CmsResource.DATE_EXPIRED_DEFAULT, false);

        } catch (CmsException e) {
            // show error page
            showErrorPage(this, e);
        }

        // get preview uri from content handler
        String previewUri = m_content.getHandler().getPreview(getCms(), m_content, getParamTempfile());

        // create locale request parameter
        StringBuffer param = new StringBuffer(8);
        if (previewUri.indexOf('?') != -1) {
            param.append("&");
        } else {
            param.append("?");
        }
        param.append(CmsLocaleManager.PARAMETER_LOCALE);
        param.append("=");
        param.append(getParamElementlanguage());

        // redirect to the temporary file with currently active element language or to the specified preview uri
        sendCmsRedirect(previewUri + param);
    }
876500
private void previewAlbum(int position) {
        if (mAlbumFiles == null || mAlbumFiles.size() == 0) {
            Toast.makeText(this, R.string.no_selected, Toast.LENGTH_LONG).show();
        } else {
            Album.galleryAlbum(this)
                    .checkable(true)
                    .checkedList(mAlbumFiles)
                    .currentPosition(position)
                    .widget(
                            Widget.newLightBuilder(this)
                                    .toolBarColor(Color.WHITE)
                                    .statusBarColor(Color.WHITE)
                                    .mediaItemCheckSelector(Color.GREEN, Color.RED)
                                    .bucketItemCheckSelector(Color.GREEN, Color.RED)
                                    .buttonStyle(
                                            Widget.ButtonStyle.newLightBuilder(this)
                                                    .setButtonSelector(Color.WHITE, Color.GRAY)
                                                    .build()
                                    )
                                    .build()
                    )
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(@NonNull ArrayList<AlbumFile> result) {
                            mAlbumFiles = result;
                            mAdapter.notifyDataSetChanged(mAlbumFiles);
                            mTvMessage.setVisibility(result.size() > 0 ? View.VISIBLE : View.GONE);
                        }
                    })
                    .start();
        }
    }
23273
private void renderBlurLayer(float slideOffset) {
        if (enableBlur) {
            if (slideOffset == 0 || forceRedraw) {
                clearBlurView();
            }

            if (slideOffset > 0f && blurView == null) {
                if (drawerLayout.getChildCount() == 2) {
                    blurView = new ImageView(drawerLayout.getContext());
                    blurView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    blurView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                    drawerLayout.addView(blurView, 1);
                }

                if (BuilderUtil.isOnUiThread()) {
                    if (cacheMode.equals(CacheMode.AUTO) || forceRedraw) {
                        dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().skipCache().into(blurView);
                        forceRedraw = false;
                    } else {
                        dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().into(blurView);
                    }
                }
            }

            if (slideOffset > 0f && slideOffset < 1f) {
                int alpha = (int) Math.ceil((double) slideOffset * 255d);
                LegacySDKUtil.setImageAlpha(blurView, alpha);
            }
        }
    }